10 "github.com/mattn/go-runewidth"
11 "github.com/zyedidia/tcell"
14 // The View struct stores information about a view into a buffer.
15 // It stores information about the cursor, and the viewport
16 // that the user sees the buffer from.
18 // A pointer to the buffer's cursor for ease of access
21 // The topmost line, used for vertical scrolling
23 // The leftmost column, used for horizontal scrolling
26 // Percentage of the terminal window that this view takes up (from 0 to 100)
30 // Actual with and height
34 // Where this view is located
37 // How much to offset because of line numbers
40 // Holds the list of gutter messages
41 messages map[string][]GutterMessage
43 // Is the help text opened in this view
46 // This is the index of this view in the views array
48 // What tab is this view stored in
51 // Is this view modifiable?
56 // This is the buffer that was last opened
57 // This is used to open help, and then go back to the previously opened buffer
62 // Since tcell doesn't differentiate between a mouse release event
63 // and a mouse move event with no keys pressed, we need to keep
64 // track of whether or not the mouse was pressed (or not released) last event to determine
65 // mouse release events
68 // This stores when the last click was
69 // This is useful for detecting double and triple clicks
70 lastClickTime time.Time
72 // lastCutTime stores when the last ctrl+k was issued.
73 // It is used for clearing the clipboard to replace it with fresh cut lines.
76 // freshClip returns true if the clipboard has never been pasted.
79 // Was the last mouse event actually a double click?
80 // Useful for detecting triple clicks -- if a double click is detected
81 // but the last mouse event was actually a double click, it's a triple click
83 // Same here, just to keep track for mouse move events
86 // Syntax highlighting matches
88 // The matches from the last frame
89 lastMatches SyntaxMatches
93 splitOrigDimensions [2]int
97 // NewView returns a new fullscreen view
98 func NewView(buf *Buffer) *View {
99 return NewViewWidthHeight(buf, 100, 100)
102 // NewViewWidthHeight returns a new view with the specified width and height percentages
103 // Note that w and h are percentages not actual values
104 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
111 v.Resize(screen.Size())
115 v.messages = make(map[string][]GutterMessage)
117 v.sline = Statusline{
124 // Resize recalculates the actual width and height of the view from the width and height
126 // This is usually called when the window is resized, or when a split has been added and
127 // the percentages have changed
128 func (v *View) Resize(w, h int) {
129 // Always include 1 line for the command line at the bottom
133 // Include one line for the tab bar at the top
142 v.width = int(float32(w) * float32(v.widthPercent) / 100)
143 // We subtract 1 for the statusline
144 v.height = int(float32(h) * float32(v.heightPercent) / 100)
145 if w%2 == 0 && v.x > 1 && v.widthPercent < 100 {
149 if h%2 == 1 && v.y > 1 && v.heightPercent < 100 {
152 if settings["statusline"].(bool) {
153 // Make room for the status line if it is enabled
158 // ScrollUp scrolls the view up n lines (if possible)
159 func (v *View) ScrollUp(n int) {
160 // Try to scroll by n but if it would overflow, scroll by 1
161 if v.Topline-n >= 0 {
163 } else if v.Topline > 0 {
168 // ScrollDown scrolls the view down n lines (if possible)
169 func (v *View) ScrollDown(n int) {
170 // Try to scroll by n but if it would overflow, scroll by 1
171 if v.Topline+n <= v.Buf.NumLines-v.height {
173 } else if v.Topline < v.Buf.NumLines-v.height {
178 // CanClose returns whether or not the view can be closed
179 // If there are unsaved changes, the user will be asked if the view can be closed
180 // causing them to lose the unsaved changes
181 // The message is what to print after saying "You have unsaved changes. "
182 func (v *View) CanClose(msg string) bool {
183 if v.Buf.IsModified {
184 quit, canceled := messenger.Prompt("You have unsaved changes. "+msg, "Unsaved", NoCompletion)
186 if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
188 } else if strings.ToLower(quit) == "save" || strings.ToLower(quit) == "s" {
199 // OpenBuffer opens a new buffer in this view.
200 // This resets the topline, event handler and cursor.
201 func (v *View) OpenBuffer(buf *Buffer) {
205 v.Cursor = &buf.Cursor
208 v.Cursor.ResetSelection()
210 v.messages = make(map[string][]GutterMessage)
214 // Set mouseReleased to true because we assume the mouse is not being pressed when
215 // the editor is opened
216 v.mouseReleased = true
217 v.lastClickTime = time.Time{}
220 // CloseBuffer performs any closing functions on the buffer
221 func (v *View) CloseBuffer() {
227 // ReOpen reloads the current buffer
228 func (v *View) ReOpen() {
229 if v.CanClose("Continue? (yes, no, save) ") {
237 // HSplit opens a horizontal split with the given buffer
238 func (v *View) HSplit(buf *Buffer) bool {
239 origDimensions := [2]int{v.widthPercent, v.heightPercent}
240 origPos := [2]int{v.x, v.y}
243 v.Resize(screen.Size())
245 newView := NewViewWidthHeight(buf, v.widthPercent, v.heightPercent)
247 v.splitOrigDimensions = origDimensions
248 v.splitOrigPos = origPos
249 newView.splitOrigDimensions = origDimensions
250 newView.splitOrigPos = origPos
252 newView.TabNum = v.TabNum
253 newView.y = v.y + v.height + 1
255 tab := tabs[v.TabNum]
257 newView.Num = len(tab.views)
258 newView.splitParent = v
259 v.splitChild = newView
260 tab.views = append(tab.views, newView)
261 newView.Resize(screen.Size())
265 // VSplit opens a vertical split with the given buffer
266 func (v *View) VSplit(buf *Buffer) bool {
267 origDimensions := [2]int{v.widthPercent, v.heightPercent}
268 origPos := [2]int{v.x, v.y}
271 v.Resize(screen.Size())
273 newView := NewViewWidthHeight(buf, v.widthPercent, v.heightPercent)
275 v.splitOrigDimensions = origDimensions
276 v.splitOrigPos = origPos
277 newView.splitOrigDimensions = origDimensions
278 newView.splitOrigPos = origPos
280 newView.TabNum = v.TabNum
282 newView.x = v.x + v.width
283 tab := tabs[v.TabNum]
285 newView.Num = len(tab.views)
286 newView.splitParent = v
287 v.splitChild = newView
288 tab.views = append(tab.views, newView)
289 newView.Resize(screen.Size())
293 // Relocate moves the view window so that the cursor is in view
294 // This is useful if the user has scrolled far away, and then starts typing
295 func (v *View) Relocate() bool {
298 scrollmargin := int(settings["scrollmargin"].(float64))
299 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
300 v.Topline = cy - scrollmargin
302 } else if cy < v.Topline {
306 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
307 v.Topline = cy - v.height + 1 + scrollmargin
309 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
310 v.Topline = v.Buf.NumLines - v.height
314 cx := v.Cursor.GetVisualX()
319 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
320 v.leftCol = cx - v.width + v.lineNumOffset + 1
326 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
328 func (v *View) MoveToMouseClick(x, y int) {
329 if y-v.Topline > v.height-1 {
331 y = v.height + v.Topline - 1
333 if y >= v.Buf.NumLines {
334 y = v.Buf.NumLines - 1
343 x = v.Cursor.GetCharPosInLine(y, x)
344 if x > Count(v.Buf.Line(y)) {
345 x = Count(v.Buf.Line(y))
349 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
352 // HandleEvent handles an event passed by the main loop
353 func (v *View) HandleEvent(event tcell.Event) {
354 // This bool determines whether the view is relocated at the end of the function
355 // By default it's true because most events should cause a relocate
360 switch e := event.(type) {
361 case *tcell.EventResize:
364 case *tcell.EventKey:
365 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
366 // Insert a character
367 if v.Cursor.HasSelection() {
368 v.Cursor.DeleteSelection()
369 v.Cursor.ResetSelection()
371 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
374 for _, pl := range loadedPlugins {
375 err := Call(pl+".onRune", []string{string(e.Rune())})
376 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
381 for key, actions := range bindings {
382 if e.Key() == key.keyCode {
383 if e.Key() == tcell.KeyRune {
384 if e.Rune() != key.r {
388 if e.Modifiers() == key.modifiers {
390 for _, action := range actions {
391 relocate = action(v) || relocate
392 for _, pl := range loadedPlugins {
393 funcName := strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
394 err := Call(pl+".on"+funcName[len(funcName)-1], nil)
395 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
404 case *tcell.EventPaste:
405 if v.Cursor.HasSelection() {
406 v.Cursor.DeleteSelection()
407 v.Cursor.ResetSelection()
410 v.Buf.Insert(v.Cursor.Loc, clip)
411 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
413 case *tcell.EventMouse:
415 x -= v.lineNumOffset - v.leftCol + v.x
417 // Don't relocate for mouse events
420 button := e.Buttons()
426 v.MoveToMouseClick(x, y)
427 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
430 v.lastClickTime = time.Now()
433 v.doubleClick = false
435 v.Cursor.SelectLine()
438 v.lastClickTime = time.Now()
441 v.tripleClick = false
443 v.Cursor.SelectWord()
446 v.doubleClick = false
447 v.tripleClick = false
448 v.lastClickTime = time.Now()
450 v.Cursor.OrigSelection[0] = v.Cursor.Loc
451 v.Cursor.CurSelection[0] = v.Cursor.Loc
452 v.Cursor.CurSelection[1] = v.Cursor.Loc
454 v.mouseReleased = false
455 } else if !v.mouseReleased {
456 v.MoveToMouseClick(x, y)
458 v.Cursor.AddLineToSelection()
459 } else if v.doubleClick {
460 v.Cursor.AddWordToSelection()
462 v.Cursor.CurSelection[1] = v.Cursor.Loc
465 case tcell.ButtonNone:
466 // Mouse event with no click
467 if !v.mouseReleased {
468 // Mouse was just released
470 // Relocating here isn't really necessary because the cursor will
471 // be in the right place from the last mouse event
472 // However, if we are running in a terminal that doesn't support mouse motion
473 // events, this still allows the user to make selections, except only after they
476 if !v.doubleClick && !v.tripleClick {
477 v.MoveToMouseClick(x, y)
478 v.Cursor.CurSelection[1] = v.Cursor.Loc
480 v.mouseReleased = true
484 scrollspeed := int(settings["scrollspeed"].(float64))
485 v.ScrollUp(scrollspeed)
486 case tcell.WheelDown:
488 scrollspeed := int(settings["scrollspeed"].(float64))
489 v.ScrollDown(scrollspeed)
496 if settings["syntax"].(bool) {
501 // GutterMessage creates a message in this view's gutter
502 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
504 gutterMsg := GutterMessage{
509 for _, v := range v.messages {
510 for _, gmsg := range v {
511 if gmsg.lineNum == lineN {
516 messages := v.messages[section]
517 v.messages[section] = append(messages, gutterMsg)
520 // ClearGutterMessages clears all gutter messages from a given section
521 func (v *View) ClearGutterMessages(section string) {
522 v.messages[section] = []GutterMessage{}
525 // ClearAllGutterMessages clears all the gutter messages
526 func (v *View) ClearAllGutterMessages() {
527 for k := range v.messages {
528 v.messages[k] = []GutterMessage{}
532 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
533 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
534 screen.SetContent(x, y, ch, combc, style)
538 // DisplayView renders the view to the screen
539 func (v *View) DisplayView() {
540 // The charNum we are currently displaying
541 // starts at the start of the viewport
542 charNum := Loc{0, v.Topline}
544 // Convert the length of buffer to a string, and get the length of the string
545 // We are going to have to offset by that amount
546 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
548 if settings["ruler"] == true {
549 // + 1 for the little space after the line number
550 v.lineNumOffset = maxLineLength + 1
555 // We need to add to the line offset if there are gutter messages
556 var hasGutterMessages bool
557 for _, v := range v.messages {
559 hasGutterMessages = true
562 if hasGutterMessages {
567 // One space for the extra split divider
571 // These represent the current screen coordinates
572 screenX, screenY := 0, 0
574 highlightStyle := defStyle
576 // ViewLine is the current line from the top of the viewport
577 for viewLine := 0; viewLine < v.height; viewLine++ {
578 screenY = v.y + viewLine
581 // This is the current line number of the buffer that we are drawing
582 curLineN := viewLine + v.Topline
585 // Draw the split divider
586 v.drawCell(screenX, screenY, ' ', nil, defStyle.Reverse(true))
590 // If the buffer is smaller than the view height we have to clear all this space
591 if curLineN >= v.Buf.NumLines {
592 for i := screenX; i < v.x+v.width; i++ {
593 v.drawCell(i, screenY, ' ', nil, defStyle)
598 line := v.Buf.Line(curLineN)
600 // If there are gutter messages we need to display the '>>' symbol here
601 if hasGutterMessages {
602 // msgOnLine stores whether or not there is a gutter message on this line in particular
604 for k := range v.messages {
605 for _, msg := range v.messages[k] {
606 if msg.lineNum == curLineN {
608 gutterStyle := defStyle
611 if style, ok := colorscheme["gutter-info"]; ok {
615 if style, ok := colorscheme["gutter-warning"]; ok {
619 if style, ok := colorscheme["gutter-error"]; ok {
623 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
625 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
627 if v.Cursor.Y == curLineN {
628 messenger.Message(msg.msg)
629 messenger.gutterMessage = true
634 // If there is no message on this line we just display an empty offset
636 v.drawCell(screenX, screenY, ' ', nil, defStyle)
638 v.drawCell(screenX, screenY, ' ', nil, defStyle)
640 if v.Cursor.Y == curLineN && messenger.gutterMessage {
642 messenger.gutterMessage = false
647 if settings["ruler"] == true {
648 // Write the line number
649 lineNumStyle := defStyle
650 if style, ok := colorscheme["line-number"]; ok {
654 lineNum := strconv.Itoa(curLineN + 1)
656 // Write the spaces before the line number if necessary
657 for i := 0; i < maxLineLength-len(lineNum); i++ {
658 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
661 // Write the actual line number
662 for _, ch := range lineNum {
663 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
667 // Write the extra space
668 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
672 // Now we actually draw the line
673 for colN, ch := range line {
674 lineStyle := defStyle
676 if settings["syntax"].(bool) {
677 // Syntax highlighting is enabled
678 highlightStyle = v.matches[viewLine][colN]
681 if v.Cursor.HasSelection() &&
682 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
683 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
684 // The current character is selected
685 lineStyle = defStyle.Reverse(true)
687 if style, ok := colorscheme["selection"]; ok {
691 lineStyle = highlightStyle
694 // We need to display the background of the linestyle with the correct color if cursorline is enabled
695 // and this is the current view and there is no selection on this line and the cursor is on this line
696 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
697 if style, ok := colorscheme["cursor-line"]; ok {
698 fg, _, _ := style.Decompose()
699 lineStyle = lineStyle.Background(fg)
704 // If the character we are displaying is a tab, we need to do a bunch of special things
706 // First the user may have configured an `indent-char` to be displayed to show that this
707 // is a tab character
708 lineIndentStyle := defStyle
709 if style, ok := colorscheme["indent-char"]; ok {
710 lineIndentStyle = style
712 if v.Cursor.HasSelection() &&
713 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
714 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
716 lineIndentStyle = defStyle.Reverse(true)
718 if style, ok := colorscheme["selection"]; ok {
719 lineIndentStyle = style
722 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
723 if style, ok := colorscheme["cursor-line"]; ok {
724 fg, _, _ := style.Decompose()
725 lineIndentStyle = lineIndentStyle.Background(fg)
728 // Here we get the indent char
729 indentChar := []rune(settings["indentchar"].(string))
730 if screenX-v.x-v.leftCol >= v.lineNumOffset {
731 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
733 // Now the tab has to be displayed as a bunch of spaces
734 tabSize := int(settings["tabsize"].(float64))
735 for i := 0; i < tabSize-1; i++ {
737 if screenX-v.x-v.leftCol >= v.lineNumOffset {
738 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
741 } else if runewidth.RuneWidth(ch) > 1 {
742 if screenX-v.x-v.leftCol >= v.lineNumOffset {
743 v.drawCell(screenX, screenY, ch, nil, lineStyle)
745 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
747 if screenX-v.x-v.leftCol >= v.lineNumOffset {
748 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
752 if screenX-v.x-v.leftCol >= v.lineNumOffset {
753 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
756 charNum = charNum.Move(1, v.Buf)
759 // Here we are at a newline
761 // The newline may be selected, in which case we should draw the selection style
762 // with a space to represent it
763 if v.Cursor.HasSelection() &&
764 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
765 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
767 selectStyle := defStyle.Reverse(true)
769 if style, ok := colorscheme["selection"]; ok {
772 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
776 charNum = charNum.Move(1, v.Buf)
778 for i := 0; i < v.width; i++ {
779 lineStyle := defStyle
780 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
781 if style, ok := colorscheme["cursor-line"]; ok {
782 fg, _, _ := style.Decompose()
783 lineStyle = lineStyle.Background(fg)
786 if screenX-v.x-v.leftCol >= v.lineNumOffset {
787 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
793 // DisplayCursor draws the current buffer's cursor to the screen
794 func (v *View) DisplayCursor() {
795 // Don't draw the cursor if it is out of the viewport or if it has a selection
796 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
799 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
803 // Display renders the view, the cursor, and statusline
804 func (v *View) Display() {
806 if v.Num == tabs[curTab].curView {
809 if settings["statusline"].(bool) {