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 // Specifies whether or not this view holds a help buffer
33 // Actual with and height
37 // Where this view is located
40 // How much to offset because of line numbers
43 // Holds the list of gutter messages
44 messages map[string][]GutterMessage
46 // This is the index of this view in the views array
48 // What tab is this view stored in
56 // Since tcell doesn't differentiate between a mouse release event
57 // and a mouse move event with no keys pressed, we need to keep
58 // track of whether or not the mouse was pressed (or not released) last event to determine
59 // mouse release events
62 // This stores when the last click was
63 // This is useful for detecting double and triple clicks
64 lastClickTime time.Time
66 // lastCutTime stores when the last ctrl+k was issued.
67 // It is used for clearing the clipboard to replace it with fresh cut lines.
70 // freshClip returns true if the clipboard has never been pasted.
73 // Was the last mouse event actually a double click?
74 // Useful for detecting triple clicks -- if a double click is detected
75 // but the last mouse event was actually a double click, it's a triple click
77 // Same here, just to keep track for mouse move events
80 // Syntax highlighting matches
82 // The matches from the last frame
83 lastMatches SyntaxMatches
87 splitOrigDimensions [2]int
91 // NewView returns a new fullscreen view
92 func NewView(buf *Buffer) *View {
93 return NewViewWidthHeight(buf, 100, 100)
96 // NewViewWidthHeight returns a new view with the specified width and height percentages
97 // Note that w and h are percentages not actual values
98 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
105 v.Resize(screen.Size())
109 v.messages = make(map[string][]GutterMessage)
111 v.sline = Statusline{
118 // Resize recalculates the actual width and height of the view from the width and height
120 // This is usually called when the window is resized, or when a split has been added and
121 // the percentages have changed
122 func (v *View) Resize(w, h int) {
123 // Always include 1 line for the command line at the bottom
127 // Include one line for the tab bar at the top
136 v.width = int(float32(w) * float32(v.widthPercent) / 100)
137 // We subtract 1 for the statusline
138 v.height = int(float32(h) * float32(v.heightPercent) / 100)
139 if w%2 == 0 && v.x > 1 && v.widthPercent < 100 {
143 if h%2 == 1 && v.y > 1 && v.heightPercent < 100 {
146 if settings["statusline"].(bool) {
147 // Make room for the status line if it is enabled
152 // ScrollUp scrolls the view up n lines (if possible)
153 func (v *View) ScrollUp(n int) {
154 // Try to scroll by n but if it would overflow, scroll by 1
155 if v.Topline-n >= 0 {
157 } else if v.Topline > 0 {
162 // ScrollDown scrolls the view down n lines (if possible)
163 func (v *View) ScrollDown(n int) {
164 // Try to scroll by n but if it would overflow, scroll by 1
165 if v.Topline+n <= v.Buf.NumLines-v.height {
167 } else if v.Topline < v.Buf.NumLines-v.height {
172 // CanClose returns whether or not the view can be closed
173 // If there are unsaved changes, the user will be asked if the view can be closed
174 // causing them to lose the unsaved changes
175 // The message is what to print after saying "You have unsaved changes. "
176 func (v *View) CanClose(msg string) bool {
177 if v.Buf.IsModified {
178 quit, canceled := messenger.Prompt("You have unsaved changes. "+msg, "Unsaved", NoCompletion)
180 if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
182 } else if strings.ToLower(quit) == "save" || strings.ToLower(quit) == "s" {
193 // OpenBuffer opens a new buffer in this view.
194 // This resets the topline, event handler and cursor.
195 func (v *View) OpenBuffer(buf *Buffer) {
199 v.Cursor = &buf.Cursor
202 v.Cursor.ResetSelection()
204 v.messages = make(map[string][]GutterMessage)
208 // Set mouseReleased to true because we assume the mouse is not being pressed when
209 // the editor is opened
210 v.mouseReleased = true
211 v.lastClickTime = time.Time{}
214 // CloseBuffer performs any closing functions on the buffer
215 func (v *View) CloseBuffer() {
221 // ReOpen reloads the current buffer
222 func (v *View) ReOpen() {
223 if v.CanClose("Continue? (yes, no, save) ") {
231 // HSplit opens a horizontal split with the given buffer
232 func (v *View) HSplit(buf *Buffer) bool {
233 origDimensions := [2]int{v.widthPercent, v.heightPercent}
234 origPos := [2]int{v.x, v.y}
237 v.Resize(screen.Size())
239 newView := NewViewWidthHeight(buf, v.widthPercent, v.heightPercent)
241 v.splitOrigDimensions = origDimensions
242 v.splitOrigPos = origPos
243 newView.splitOrigDimensions = origDimensions
244 newView.splitOrigPos = origPos
246 newView.TabNum = v.TabNum
247 newView.y = v.y + v.height + 1
249 tab := tabs[v.TabNum]
251 newView.Num = len(tab.views)
252 newView.splitParent = v
253 v.splitChild = newView
254 tab.views = append(tab.views, newView)
255 newView.Resize(screen.Size())
259 // VSplit opens a vertical split with the given buffer
260 func (v *View) VSplit(buf *Buffer) bool {
261 origDimensions := [2]int{v.widthPercent, v.heightPercent}
262 origPos := [2]int{v.x, v.y}
265 v.Resize(screen.Size())
267 newView := NewViewWidthHeight(buf, v.widthPercent, v.heightPercent)
269 v.splitOrigDimensions = origDimensions
270 v.splitOrigPos = origPos
271 newView.splitOrigDimensions = origDimensions
272 newView.splitOrigPos = origPos
274 newView.TabNum = v.TabNum
276 newView.x = v.x + v.width
277 tab := tabs[v.TabNum]
279 newView.Num = len(tab.views)
280 newView.splitParent = v
281 v.splitChild = newView
282 tab.views = append(tab.views, newView)
283 newView.Resize(screen.Size())
287 // Relocate moves the view window so that the cursor is in view
288 // This is useful if the user has scrolled far away, and then starts typing
289 func (v *View) Relocate() bool {
292 scrollmargin := int(settings["scrollmargin"].(float64))
293 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
294 v.Topline = cy - scrollmargin
296 } else if cy < v.Topline {
300 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
301 v.Topline = cy - v.height + 1 + scrollmargin
303 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
304 v.Topline = v.Buf.NumLines - v.height
308 cx := v.Cursor.GetVisualX()
313 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
314 v.leftCol = cx - v.width + v.lineNumOffset + 1
320 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
322 func (v *View) MoveToMouseClick(x, y int) {
323 if y-v.Topline > v.height-1 {
325 y = v.height + v.Topline - 1
327 if y >= v.Buf.NumLines {
328 y = v.Buf.NumLines - 1
337 x = v.Cursor.GetCharPosInLine(y, x)
338 if x > Count(v.Buf.Line(y)) {
339 x = Count(v.Buf.Line(y))
343 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
346 // HandleEvent handles an event passed by the main loop
347 func (v *View) HandleEvent(event tcell.Event) {
348 // This bool determines whether the view is relocated at the end of the function
349 // By default it's true because most events should cause a relocate
354 switch e := event.(type) {
355 case *tcell.EventResize:
358 case *tcell.EventKey:
359 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
360 // Insert a character
361 if v.Cursor.HasSelection() {
362 v.Cursor.DeleteSelection()
363 v.Cursor.ResetSelection()
365 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
368 for _, pl := range loadedPlugins {
369 err := Call(pl+".onRune", []string{string(e.Rune())})
370 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
375 for key, actions := range bindings {
376 if e.Key() == key.keyCode {
377 if e.Key() == tcell.KeyRune {
378 if e.Rune() != key.r {
382 if e.Modifiers() == key.modifiers {
384 for _, action := range actions {
385 relocate = action(v) || relocate
386 for _, pl := range loadedPlugins {
387 funcName := strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
388 err := Call(pl+".on"+funcName[len(funcName)-1], nil)
389 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
398 case *tcell.EventPaste:
399 if v.Cursor.HasSelection() {
400 v.Cursor.DeleteSelection()
401 v.Cursor.ResetSelection()
404 v.Buf.Insert(v.Cursor.Loc, clip)
405 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
407 case *tcell.EventMouse:
409 x -= v.lineNumOffset - v.leftCol + v.x
411 // Don't relocate for mouse events
414 button := e.Buttons()
420 v.MoveToMouseClick(x, y)
421 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
424 v.lastClickTime = time.Now()
427 v.doubleClick = false
429 v.Cursor.SelectLine()
432 v.lastClickTime = time.Now()
435 v.tripleClick = false
437 v.Cursor.SelectWord()
440 v.doubleClick = false
441 v.tripleClick = false
442 v.lastClickTime = time.Now()
444 v.Cursor.OrigSelection[0] = v.Cursor.Loc
445 v.Cursor.CurSelection[0] = v.Cursor.Loc
446 v.Cursor.CurSelection[1] = v.Cursor.Loc
448 v.mouseReleased = false
449 } else if !v.mouseReleased {
450 v.MoveToMouseClick(x, y)
452 v.Cursor.AddLineToSelection()
453 } else if v.doubleClick {
454 v.Cursor.AddWordToSelection()
456 v.Cursor.CurSelection[1] = v.Cursor.Loc
459 case tcell.ButtonNone:
460 // Mouse event with no click
461 if !v.mouseReleased {
462 // Mouse was just released
464 // Relocating here isn't really necessary because the cursor will
465 // be in the right place from the last mouse event
466 // However, if we are running in a terminal that doesn't support mouse motion
467 // events, this still allows the user to make selections, except only after they
470 if !v.doubleClick && !v.tripleClick {
471 v.MoveToMouseClick(x, y)
472 v.Cursor.CurSelection[1] = v.Cursor.Loc
474 v.mouseReleased = true
478 scrollspeed := int(settings["scrollspeed"].(float64))
479 v.ScrollUp(scrollspeed)
480 case tcell.WheelDown:
482 scrollspeed := int(settings["scrollspeed"].(float64))
483 v.ScrollDown(scrollspeed)
490 if settings["syntax"].(bool) {
495 // GutterMessage creates a message in this view's gutter
496 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
498 gutterMsg := GutterMessage{
503 for _, v := range v.messages {
504 for _, gmsg := range v {
505 if gmsg.lineNum == lineN {
510 messages := v.messages[section]
511 v.messages[section] = append(messages, gutterMsg)
514 // ClearGutterMessages clears all gutter messages from a given section
515 func (v *View) ClearGutterMessages(section string) {
516 v.messages[section] = []GutterMessage{}
519 // ClearAllGutterMessages clears all the gutter messages
520 func (v *View) ClearAllGutterMessages() {
521 for k := range v.messages {
522 v.messages[k] = []GutterMessage{}
526 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
527 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
528 screen.SetContent(x, y, ch, combc, style)
532 // DisplayView renders the view to the screen
533 func (v *View) DisplayView() {
534 // The charNum we are currently displaying
535 // starts at the start of the viewport
536 charNum := Loc{0, v.Topline}
538 // Convert the length of buffer to a string, and get the length of the string
539 // We are going to have to offset by that amount
540 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
542 if settings["ruler"] == true {
543 // + 1 for the little space after the line number
544 v.lineNumOffset = maxLineLength + 1
549 // We need to add to the line offset if there are gutter messages
550 var hasGutterMessages bool
551 for _, v := range v.messages {
553 hasGutterMessages = true
556 if hasGutterMessages {
561 // One space for the extra split divider
565 // These represent the current screen coordinates
566 screenX, screenY := 0, 0
568 highlightStyle := defStyle
570 // ViewLine is the current line from the top of the viewport
571 for viewLine := 0; viewLine < v.height; viewLine++ {
572 screenY = v.y + viewLine
575 // This is the current line number of the buffer that we are drawing
576 curLineN := viewLine + v.Topline
579 // Draw the split divider
580 v.drawCell(screenX, screenY, ' ', nil, defStyle.Reverse(true))
584 // If the buffer is smaller than the view height we have to clear all this space
585 if curLineN >= v.Buf.NumLines {
586 for i := screenX; i < v.x+v.width; i++ {
587 v.drawCell(i, screenY, ' ', nil, defStyle)
592 line := v.Buf.Line(curLineN)
594 // If there are gutter messages we need to display the '>>' symbol here
595 if hasGutterMessages {
596 // msgOnLine stores whether or not there is a gutter message on this line in particular
598 for k := range v.messages {
599 for _, msg := range v.messages[k] {
600 if msg.lineNum == curLineN {
602 gutterStyle := defStyle
605 if style, ok := colorscheme["gutter-info"]; ok {
609 if style, ok := colorscheme["gutter-warning"]; ok {
613 if style, ok := colorscheme["gutter-error"]; ok {
617 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
619 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
621 if v.Cursor.Y == curLineN {
622 messenger.Message(msg.msg)
623 messenger.gutterMessage = true
628 // If there is no message on this line we just display an empty offset
630 v.drawCell(screenX, screenY, ' ', nil, defStyle)
632 v.drawCell(screenX, screenY, ' ', nil, defStyle)
634 if v.Cursor.Y == curLineN && messenger.gutterMessage {
636 messenger.gutterMessage = false
641 if settings["ruler"] == true {
642 // Write the line number
643 lineNumStyle := defStyle
644 if style, ok := colorscheme["line-number"]; ok {
648 lineNum := strconv.Itoa(curLineN + 1)
650 // Write the spaces before the line number if necessary
651 for i := 0; i < maxLineLength-len(lineNum); i++ {
652 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
655 // Write the actual line number
656 for _, ch := range lineNum {
657 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
661 // Write the extra space
662 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
666 // Now we actually draw the line
667 for colN, ch := range line {
668 lineStyle := defStyle
670 if settings["syntax"].(bool) {
671 // Syntax highlighting is enabled
672 highlightStyle = v.matches[viewLine][colN]
675 if v.Cursor.HasSelection() &&
676 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
677 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
678 // The current character is selected
679 lineStyle = defStyle.Reverse(true)
681 if style, ok := colorscheme["selection"]; ok {
685 lineStyle = highlightStyle
688 // We need to display the background of the linestyle with the correct color if cursorline is enabled
689 // and this is the current view and there is no selection on this line and the cursor is on this line
690 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
691 if style, ok := colorscheme["cursor-line"]; ok {
692 fg, _, _ := style.Decompose()
693 lineStyle = lineStyle.Background(fg)
698 // If the character we are displaying is a tab, we need to do a bunch of special things
700 // First the user may have configured an `indent-char` to be displayed to show that this
701 // is a tab character
702 lineIndentStyle := defStyle
703 if style, ok := colorscheme["indent-char"]; ok {
704 lineIndentStyle = style
706 if v.Cursor.HasSelection() &&
707 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
708 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
710 lineIndentStyle = defStyle.Reverse(true)
712 if style, ok := colorscheme["selection"]; ok {
713 lineIndentStyle = style
716 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
717 if style, ok := colorscheme["cursor-line"]; ok {
718 fg, _, _ := style.Decompose()
719 lineIndentStyle = lineIndentStyle.Background(fg)
722 // Here we get the indent char
723 indentChar := []rune(settings["indentchar"].(string))
724 if screenX-v.x-v.leftCol >= v.lineNumOffset {
725 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
727 // Now the tab has to be displayed as a bunch of spaces
728 tabSize := int(settings["tabsize"].(float64))
729 for i := 0; i < tabSize-1; i++ {
731 if screenX-v.x-v.leftCol >= v.lineNumOffset {
732 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
735 } else if runewidth.RuneWidth(ch) > 1 {
736 if screenX-v.x-v.leftCol >= v.lineNumOffset {
737 v.drawCell(screenX, screenY, ch, nil, lineStyle)
739 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
741 if screenX-v.x-v.leftCol >= v.lineNumOffset {
742 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
746 if screenX-v.x-v.leftCol >= v.lineNumOffset {
747 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
750 charNum = charNum.Move(1, v.Buf)
753 // Here we are at a newline
755 // The newline may be selected, in which case we should draw the selection style
756 // with a space to represent it
757 if v.Cursor.HasSelection() &&
758 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
759 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
761 selectStyle := defStyle.Reverse(true)
763 if style, ok := colorscheme["selection"]; ok {
766 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
770 charNum = charNum.Move(1, v.Buf)
772 for i := 0; i < v.width; i++ {
773 lineStyle := defStyle
774 if settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
775 if style, ok := colorscheme["cursor-line"]; ok {
776 fg, _, _ := style.Decompose()
777 lineStyle = lineStyle.Background(fg)
780 if screenX-v.x-v.leftCol >= v.lineNumOffset {
781 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
787 // DisplayCursor draws the current buffer's cursor to the screen
788 func (v *View) DisplayCursor() {
789 // Don't draw the cursor if it is out of the viewport or if it has a selection
790 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
793 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
797 // Display renders the view, the cursor, and statusline
798 func (v *View) Display() {
800 if v.Num == tabs[curTab].curView {
803 if settings["statusline"].(bool) {