10 "github.com/mattn/go-runewidth"
11 "github.com/yuin/gopher-lua"
12 "github.com/zyedidia/tcell"
15 // The View struct stores information about a view into a buffer.
16 // It stores information about the cursor, and the viewport
17 // that the user sees the buffer from.
19 // A pointer to the buffer's cursor for ease of access
22 // The topmost line, used for vertical scrolling
24 // The leftmost column, used for horizontal scrolling
27 // Percentage of the terminal window that this view takes up (from 0 to 100)
31 // Specifies whether or not this view holds a help buffer
34 // Actual with and height
38 // Where this view is located
41 // How much to offset because of line numbers
44 // Holds the list of gutter messages
45 messages map[string][]GutterMessage
47 // This is the index of this view in the views array
49 // What tab is this view stored in
57 // Since tcell doesn't differentiate between a mouse release event
58 // and a mouse move event with no keys pressed, we need to keep
59 // track of whether or not the mouse was pressed (or not released) last event to determine
60 // mouse release events
63 // This stores when the last click was
64 // This is useful for detecting double and triple clicks
65 lastClickTime time.Time
67 // lastCutTime stores when the last ctrl+k was issued.
68 // It is used for clearing the clipboard to replace it with fresh cut lines.
71 // freshClip returns true if the clipboard has never been pasted.
74 // Was the last mouse event actually a double click?
75 // Useful for detecting triple clicks -- if a double click is detected
76 // but the last mouse event was actually a double click, it's a triple click
78 // Same here, just to keep track for mouse move events
81 // Syntax highlighting matches
83 // The matches from the last frame
84 lastMatches SyntaxMatches
88 splitOrigDimensions [2]int
92 // NewView returns a new fullscreen view
93 func NewView(buf *Buffer) *View {
94 return NewViewWidthHeight(buf, 100, 100)
97 // NewViewWidthHeight returns a new view with the specified width and height percentages
98 // Note that w and h are percentages not actual values
99 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
106 v.Resize(screen.Size())
110 v.messages = make(map[string][]GutterMessage)
112 v.sline = Statusline{
119 // Resize recalculates the actual width and height of the view from the width and height
121 // This is usually called when the window is resized, or when a split has been added and
122 // the percentages have changed
123 func (v *View) Resize(w, h int) {
124 // Always include 1 line for the command line at the bottom
128 // Include one line for the tab bar at the top
137 v.width = int(float32(w) * float32(v.widthPercent) / 100)
138 // We subtract 1 for the statusline
139 v.height = int(float32(h) * float32(v.heightPercent) / 100)
140 if w%2 == 0 && v.x > 1 && v.widthPercent < 100 {
144 if h%2 == 1 && v.y > 1 && v.heightPercent < 100 {
147 if settings["statusline"].(bool) {
148 // Make room for the status line if it is enabled
153 // ScrollUp scrolls the view up n lines (if possible)
154 func (v *View) ScrollUp(n int) {
155 // Try to scroll by n but if it would overflow, scroll by 1
156 if v.Topline-n >= 0 {
158 } else if v.Topline > 0 {
163 // ScrollDown scrolls the view down n lines (if possible)
164 func (v *View) ScrollDown(n int) {
165 // Try to scroll by n but if it would overflow, scroll by 1
166 if v.Topline+n <= v.Buf.NumLines-v.height {
168 } else if v.Topline < v.Buf.NumLines-v.height {
173 // CanClose returns whether or not the view can be closed
174 // If there are unsaved changes, the user will be asked if the view can be closed
175 // causing them to lose the unsaved changes
176 // The message is what to print after saying "You have unsaved changes. "
177 func (v *View) CanClose(msg string) bool {
178 if v.Buf.IsModified {
179 quit, canceled := messenger.Prompt("You have unsaved changes. "+msg, "Unsaved", NoCompletion)
181 if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
183 } else if strings.ToLower(quit) == "save" || strings.ToLower(quit) == "s" {
194 // OpenBuffer opens a new buffer in this view.
195 // This resets the topline, event handler and cursor.
196 func (v *View) OpenBuffer(buf *Buffer) {
200 v.Cursor = &buf.Cursor
203 v.Cursor.ResetSelection()
205 v.messages = make(map[string][]GutterMessage)
209 // Set mouseReleased to true because we assume the mouse is not being pressed when
210 // the editor is opened
211 v.mouseReleased = true
212 v.lastClickTime = time.Time{}
215 // CloseBuffer performs any closing functions on the buffer
216 func (v *View) CloseBuffer() {
222 // ReOpen reloads the current buffer
223 func (v *View) ReOpen() {
224 if v.CanClose("Continue? (yes, no, save) ") {
232 // HSplit opens a horizontal split with the given buffer
233 func (v *View) HSplit(buf *Buffer) bool {
234 origDimensions := [2]int{v.widthPercent, v.heightPercent}
235 origPos := [2]int{v.x, v.y}
238 v.Resize(screen.Size())
240 newView := NewViewWidthHeight(buf, v.widthPercent, v.heightPercent)
242 v.splitOrigDimensions = origDimensions
243 v.splitOrigPos = origPos
244 newView.splitOrigDimensions = origDimensions
245 newView.splitOrigPos = origPos
247 newView.TabNum = v.TabNum
248 newView.y = v.y + v.height + 1
250 tab := tabs[v.TabNum]
252 newView.Num = len(tab.views)
253 newView.splitParent = v
254 v.splitChild = newView
255 tab.views = append(tab.views, newView)
256 newView.Resize(screen.Size())
260 // VSplit opens a vertical split with the given buffer
261 func (v *View) VSplit(buf *Buffer) bool {
262 origDimensions := [2]int{v.widthPercent, v.heightPercent}
263 origPos := [2]int{v.x, v.y}
266 v.Resize(screen.Size())
268 newView := NewViewWidthHeight(buf, v.widthPercent, v.heightPercent)
270 v.splitOrigDimensions = origDimensions
271 v.splitOrigPos = origPos
272 newView.splitOrigDimensions = origDimensions
273 newView.splitOrigPos = origPos
275 newView.TabNum = v.TabNum
277 newView.x = v.x + v.width
278 tab := tabs[v.TabNum]
280 newView.Num = len(tab.views)
281 newView.splitParent = v
282 v.splitChild = newView
283 tab.views = append(tab.views, newView)
284 newView.Resize(screen.Size())
288 // Relocate moves the view window so that the cursor is in view
289 // This is useful if the user has scrolled far away, and then starts typing
290 func (v *View) Relocate() bool {
293 scrollmargin := int(settings["scrollmargin"].(float64))
294 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
295 v.Topline = cy - scrollmargin
297 } else if cy < v.Topline {
301 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
302 v.Topline = cy - v.height + 1 + scrollmargin
304 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
305 v.Topline = v.Buf.NumLines - v.height
309 cx := v.Cursor.GetVisualX()
314 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
315 v.leftCol = cx - v.width + v.lineNumOffset + 1
321 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
323 func (v *View) MoveToMouseClick(x, y int) {
324 if y-v.Topline > v.height-1 {
326 y = v.height + v.Topline - 1
328 if y >= v.Buf.NumLines {
329 y = v.Buf.NumLines - 1
338 x = v.Cursor.GetCharPosInLine(y, x)
339 if x > Count(v.Buf.Line(y)) {
340 x = Count(v.Buf.Line(y))
344 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
347 // HandleEvent handles an event passed by the main loop
348 func (v *View) HandleEvent(event tcell.Event) {
349 // This bool determines whether the view is relocated at the end of the function
350 // By default it's true because most events should cause a relocate
355 switch e := event.(type) {
356 case *tcell.EventResize:
359 case *tcell.EventKey:
360 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
361 // Insert a character
362 if v.Cursor.HasSelection() {
363 v.Cursor.DeleteSelection()
364 v.Cursor.ResetSelection()
366 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
369 for _, pl := range loadedPlugins {
370 _, err := Call(pl+".onRune", []string{string(e.Rune())})
371 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
376 for key, actions := range bindings {
377 if e.Key() == key.keyCode {
378 if e.Key() == tcell.KeyRune {
379 if e.Rune() != key.r {
383 if e.Modifiers() == key.modifiers {
385 for _, action := range actions {
386 executeAction := true
387 funcName := strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
388 for _, pl := range loadedPlugins {
389 ret, err := Call(pl+".pre"+funcName[len(funcName)-1], nil)
390 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
394 if ret == lua.LFalse {
395 executeAction = false
399 relocate = action(v) || relocate
400 for _, pl := range loadedPlugins {
401 _, err := Call(pl+".on"+funcName[len(funcName)-1], nil)
402 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
413 case *tcell.EventPaste:
414 if v.Cursor.HasSelection() {
415 v.Cursor.DeleteSelection()
416 v.Cursor.ResetSelection()
419 v.Buf.Insert(v.Cursor.Loc, clip)
420 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
422 case *tcell.EventMouse:
424 x -= v.lineNumOffset - v.leftCol + v.x
426 // Don't relocate for mouse events
429 button := e.Buttons()
435 v.MoveToMouseClick(x, y)
436 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
439 v.lastClickTime = time.Now()
442 v.doubleClick = false
444 v.Cursor.SelectLine()
447 v.lastClickTime = time.Now()
450 v.tripleClick = false
452 v.Cursor.SelectWord()
455 v.doubleClick = false
456 v.tripleClick = false
457 v.lastClickTime = time.Now()
459 v.Cursor.OrigSelection[0] = v.Cursor.Loc
460 v.Cursor.CurSelection[0] = v.Cursor.Loc
461 v.Cursor.CurSelection[1] = v.Cursor.Loc
463 v.mouseReleased = false
464 } else if !v.mouseReleased {
465 v.MoveToMouseClick(x, y)
467 v.Cursor.AddLineToSelection()
468 } else if v.doubleClick {
469 v.Cursor.AddWordToSelection()
471 v.Cursor.CurSelection[1] = v.Cursor.Loc
474 case tcell.ButtonNone:
475 // Mouse event with no click
476 if !v.mouseReleased {
477 // Mouse was just released
479 // Relocating here isn't really necessary because the cursor will
480 // be in the right place from the last mouse event
481 // However, if we are running in a terminal that doesn't support mouse motion
482 // events, this still allows the user to make selections, except only after they
485 if !v.doubleClick && !v.tripleClick {
486 v.MoveToMouseClick(x, y)
487 v.Cursor.CurSelection[1] = v.Cursor.Loc
489 v.mouseReleased = true
493 scrollspeed := int(settings["scrollspeed"].(float64))
494 v.ScrollUp(scrollspeed)
495 case tcell.WheelDown:
497 scrollspeed := int(settings["scrollspeed"].(float64))
498 v.ScrollDown(scrollspeed)
505 if settings["syntax"].(bool) {
510 // GutterMessage creates a message in this view's gutter
511 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
513 gutterMsg := GutterMessage{
518 for _, v := range v.messages {
519 for _, gmsg := range v {
520 if gmsg.lineNum == lineN {
525 messages := v.messages[section]
526 v.messages[section] = append(messages, gutterMsg)
529 // ClearGutterMessages clears all gutter messages from a given section
530 func (v *View) ClearGutterMessages(section string) {
531 v.messages[section] = []GutterMessage{}
534 // ClearAllGutterMessages clears all the gutter messages
535 func (v *View) ClearAllGutterMessages() {
536 for k := range v.messages {
537 v.messages[k] = []GutterMessage{}
541 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
542 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
543 screen.SetContent(x, y, ch, combc, style)
547 // DisplayView renders the view to the screen
548 func (v *View) DisplayView() {
549 // The charNum we are currently displaying
550 // starts at the start of the viewport
551 charNum := Loc{0, v.Topline}
553 // Convert the length of buffer to a string, and get the length of the string
554 // We are going to have to offset by that amount
555 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
557 if settings["ruler"] == true {
558 // + 1 for the little space after the line number
559 v.lineNumOffset = maxLineLength + 1
564 // We need to add to the line offset if there are gutter messages
565 var hasGutterMessages bool
566 for _, v := range v.messages {
568 hasGutterMessages = true
571 if hasGutterMessages {
576 // One space for the extra split divider
580 // These represent the current screen coordinates
581 screenX, screenY := 0, 0
583 highlightStyle := defStyle
585 // ViewLine is the current line from the top of the viewport
586 for viewLine := 0; viewLine < v.height; viewLine++ {
587 screenY = v.y + viewLine
590 // This is the current line number of the buffer that we are drawing
591 curLineN := viewLine + v.Topline
594 // Draw the split divider
595 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
599 // If the buffer is smaller than the view height we have to clear all this space
600 if curLineN >= v.Buf.NumLines {
601 for i := screenX; i < v.x+v.width; i++ {
602 v.drawCell(i, screenY, ' ', nil, defStyle)
607 line := v.Buf.Line(curLineN)
609 // If there are gutter messages we need to display the '>>' symbol here
610 if hasGutterMessages {
611 // msgOnLine stores whether or not there is a gutter message on this line in particular
613 for k := range v.messages {
614 for _, msg := range v.messages[k] {
615 if msg.lineNum == curLineN {
617 gutterStyle := defStyle
620 if style, ok := colorscheme["gutter-info"]; ok {
624 if style, ok := colorscheme["gutter-warning"]; ok {
628 if style, ok := colorscheme["gutter-error"]; ok {
632 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
634 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
636 if v.Cursor.Y == curLineN {
637 messenger.Message(msg.msg)
638 messenger.gutterMessage = true
643 // If there is no message on this line we just display an empty offset
645 v.drawCell(screenX, screenY, ' ', nil, defStyle)
647 v.drawCell(screenX, screenY, ' ', nil, defStyle)
649 if v.Cursor.Y == curLineN && messenger.gutterMessage {
651 messenger.gutterMessage = false
656 if settings["ruler"] == true {
657 // Write the line number
658 lineNumStyle := defStyle
659 if style, ok := colorscheme["line-number"]; ok {
663 lineNum := strconv.Itoa(curLineN + 1)
665 // Write the spaces before the line number if necessary
666 for i := 0; i < maxLineLength-len(lineNum); i++ {
667 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
670 // Write the actual line number
671 for _, ch := range lineNum {
672 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
676 // Write the extra space
677 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
681 // Now we actually draw the line
682 for colN, ch := range line {
683 lineStyle := defStyle
685 if settings["syntax"].(bool) {
686 // Syntax highlighting is enabled
687 highlightStyle = v.matches[viewLine][colN]
690 if v.Cursor.HasSelection() &&
691 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
692 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
693 // The current character is selected
694 lineStyle = defStyle.Reverse(true)
696 if style, ok := colorscheme["selection"]; ok {
700 lineStyle = highlightStyle
703 // We need to display the background of the linestyle with the correct color if cursorline is enabled
704 // and this is the current view and there is no selection on this line and the cursor is on this line
705 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
706 if style, ok := colorscheme["cursor-line"]; ok {
707 fg, _, _ := style.Decompose()
708 lineStyle = lineStyle.Background(fg)
713 // If the character we are displaying is a tab, we need to do a bunch of special things
715 // First the user may have configured an `indent-char` to be displayed to show that this
716 // is a tab character
717 lineIndentStyle := defStyle
718 if style, ok := colorscheme["indent-char"]; ok {
719 lineIndentStyle = style
721 if v.Cursor.HasSelection() &&
722 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
723 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
725 lineIndentStyle = defStyle.Reverse(true)
727 if style, ok := colorscheme["selection"]; ok {
728 lineIndentStyle = style
731 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
732 if style, ok := colorscheme["cursor-line"]; ok {
733 fg, _, _ := style.Decompose()
734 lineIndentStyle = lineIndentStyle.Background(fg)
737 // Here we get the indent char
738 indentChar := []rune(settings["indentchar"].(string))
739 if screenX-v.x-v.leftCol >= v.lineNumOffset {
740 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
742 // Now the tab has to be displayed as a bunch of spaces
743 tabSize := int(settings["tabsize"].(float64))
744 for i := 0; i < tabSize-1; i++ {
746 if screenX-v.x-v.leftCol >= v.lineNumOffset {
747 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
750 } else if runewidth.RuneWidth(ch) > 1 {
751 if screenX-v.x-v.leftCol >= v.lineNumOffset {
752 v.drawCell(screenX, screenY, ch, nil, lineStyle)
754 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
756 if screenX-v.x-v.leftCol >= v.lineNumOffset {
757 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
761 if screenX-v.x-v.leftCol >= v.lineNumOffset {
762 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
765 charNum = charNum.Move(1, v.Buf)
768 // Here we are at a newline
770 // The newline may be selected, in which case we should draw the selection style
771 // with a space to represent it
772 if v.Cursor.HasSelection() &&
773 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
774 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
776 selectStyle := defStyle.Reverse(true)
778 if style, ok := colorscheme["selection"]; ok {
781 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
785 charNum = charNum.Move(1, v.Buf)
787 for i := 0; i < v.width; i++ {
788 lineStyle := defStyle
789 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
790 if style, ok := colorscheme["cursor-line"]; ok {
791 fg, _, _ := style.Decompose()
792 lineStyle = lineStyle.Background(fg)
795 if screenX-v.x-v.leftCol >= v.lineNumOffset {
796 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
802 // DisplayCursor draws the current buffer's cursor to the screen
803 func (v *View) DisplayCursor() {
804 // Don't draw the cursor if it is out of the viewport or if it has a selection
805 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
808 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
812 // Display renders the view, the cursor, and statusline
813 func (v *View) Display() {
815 if v.Num == tabs[curTab].curView {
818 _, screenH := screen.Size()
819 if settings["statusline"].(bool) {
821 } else if (v.y + v.height) != screenH-1 {
822 for x := 0; x < v.width; x++ {
823 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))