9 "github.com/mattn/go-runewidth"
10 "github.com/mitchellh/go-homedir"
11 "github.com/zyedidia/tcell"
17 vtDefault ViewType = iota
22 // The View struct stores information about a view into a buffer.
23 // It stores information about the cursor, and the viewport
24 // that the user sees the buffer from.
26 // A pointer to the buffer's cursor for ease of access
29 // The topmost line, used for vertical scrolling
31 // The leftmost column, used for horizontal scrolling
34 // Specifies whether or not this view holds a help buffer
37 // Actual width and height
41 // Where this view is located
44 // How much to offset because of line numbers
47 // Holds the list of gutter messages
48 messages map[string][]GutterMessage
50 // This is the index of this view in the views array
52 // What tab is this view stored in
60 // Since tcell doesn't differentiate between a mouse release event
61 // and a mouse move event with no keys pressed, we need to keep
62 // track of whether or not the mouse was pressed (or not released) last event to determine
63 // mouse release events
66 // This stores when the last click was
67 // This is useful for detecting double and triple clicks
68 lastClickTime time.Time
70 // lastCutTime stores when the last ctrl+k was issued.
71 // It is used for clearing the clipboard to replace it with fresh cut lines.
74 // freshClip returns true if the clipboard has never been pasted.
77 // Was the last mouse event actually a double click?
78 // Useful for detecting triple clicks -- if a double click is detected
79 // but the last mouse event was actually a double click, it's a triple click
81 // Same here, just to keep track for mouse move events
84 // Syntax highlighting matches
90 // NewView returns a new fullscreen view
91 func NewView(buf *Buffer) *View {
92 screenW, screenH := screen.Size()
93 return NewViewWidthHeight(buf, screenW, screenH)
96 // NewViewWidthHeight returns a new view with the specified width and height
97 // Note that w and h are raw column and row values
98 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
110 v.messages = make(map[string][]GutterMessage)
112 v.sline = Statusline{
116 if v.Buf.Settings["statusline"].(bool) {
120 for _, pl := range loadedPlugins {
121 _, err := Call(pl+".onViewOpen", v)
122 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
131 // ToggleStatusLine creates an extra row for the statusline if necessary
132 func (v *View) ToggleStatusLine() {
133 if v.Buf.Settings["statusline"].(bool) {
140 // ToggleTabbar creates an extra row for the tabbar if necessary
141 func (v *View) ToggleTabbar() {
144 // Include one line for the tab bar at the top
156 func (v *View) paste(clip string) {
157 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
159 if v.Cursor.HasSelection() {
160 v.Cursor.DeleteSelection()
161 v.Cursor.ResetSelection()
163 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
164 v.Buf.Insert(v.Cursor.Loc, clip)
165 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
167 messenger.Message("Pasted clipboard")
170 // ScrollUp scrolls the view up n lines (if possible)
171 func (v *View) ScrollUp(n int) {
172 // Try to scroll by n but if it would overflow, scroll by 1
173 if v.Topline-n >= 0 {
175 } else if v.Topline > 0 {
180 // ScrollDown scrolls the view down n lines (if possible)
181 func (v *View) ScrollDown(n int) {
182 // Try to scroll by n but if it would overflow, scroll by 1
183 if v.Topline+n <= v.Buf.NumLines-v.height {
185 } else if v.Topline < v.Buf.NumLines-v.height {
190 // CanClose returns whether or not the view can be closed
191 // If there are unsaved changes, the user will be asked if the view can be closed
192 // causing them to lose the unsaved changes
193 func (v *View) CanClose() bool {
194 if v.Type == vtDefault && v.Buf.IsModified {
197 if v.Buf.Settings["autosave"].(bool) {
200 char, canceled = messenger.LetterPrompt("Save changes to "+v.Buf.Name+" before closing? (y,n,esc) ", 'y', 'n')
206 } else if char == 'n' {
216 // OpenBuffer opens a new buffer in this view.
217 // This resets the topline, event handler and cursor.
218 func (v *View) OpenBuffer(buf *Buffer) {
222 v.Cursor = &buf.Cursor
225 v.Cursor.ResetSelection()
228 v.messages = make(map[string][]GutterMessage)
232 // Set mouseReleased to true because we assume the mouse is not being pressed when
233 // the editor is opened
234 v.mouseReleased = true
235 v.lastClickTime = time.Time{}
238 // Open opens the given file in the view
239 func (v *View) Open(filename string) {
240 home, _ := homedir.Dir()
241 filename = strings.Replace(filename, "~", home, 1)
242 file, err := ioutil.ReadFile(filename)
246 messenger.Message(err.Error())
247 // File does not exist -- create an empty buffer with that name
248 buf = NewBuffer([]byte{}, filename)
250 buf = NewBuffer(file, filename)
255 // CloseBuffer performs any closing functions on the buffer
256 func (v *View) CloseBuffer() {
262 // ReOpen reloads the current buffer
263 func (v *View) ReOpen() {
272 // HSplit opens a horizontal split with the given buffer
273 func (v *View) HSplit(buf *Buffer) bool {
274 v.splitNode.HSplit(buf)
275 tabs[v.TabNum].Resize()
279 // VSplit opens a vertical split with the given buffer
280 func (v *View) VSplit(buf *Buffer) bool {
281 v.splitNode.VSplit(buf)
282 tabs[v.TabNum].Resize()
286 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
287 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
288 if !v.Buf.Settings["softwrap"].(bool) {
289 vx = v.Cursor.GetCharPosInLine(vy, vx)
293 screenX, screenY := 0, v.Topline
294 for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
295 line := v.Buf.Line(lineN)
298 for _, ch := range line {
299 if screenX >= v.width-v.lineNumOffset {
304 if screenX == vx && screenY == vy {
309 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
325 func (v *View) Bottomline() int {
326 screenX, screenY := 0, 0
328 for lineN := v.Topline; lineN < v.Topline+v.height; lineN++ {
329 line := v.Buf.Line(lineN)
332 for _, ch := range line {
333 if screenX >= v.width-v.lineNumOffset {
339 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
349 if screenY >= v.height {
353 return numLines + v.Topline
356 // Relocate moves the view window so that the cursor is in view
357 // This is useful if the user has scrolled far away, and then starts typing
358 func (v *View) Relocate() bool {
359 height := v.Bottomline() - v.Topline
362 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
363 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
364 v.Topline = cy - scrollmargin
366 } else if cy < v.Topline {
370 if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
371 v.Topline = cy - height + 1 + scrollmargin
373 } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
374 v.Topline = v.Buf.NumLines - height
378 if !v.Buf.Settings["softwrap"].(bool) {
379 cx := v.Cursor.GetVisualX()
384 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
385 v.leftCol = cx - v.width + v.lineNumOffset + 1
392 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
394 func (v *View) MoveToMouseClick(x, y int) {
395 if y-v.Topline > v.height-1 {
397 y = v.height + v.Topline - 1
399 if y >= v.Buf.NumLines {
400 y = v.Buf.NumLines - 1
409 x, y = v.GetSoftWrapLocation(x, y)
410 // x = v.Cursor.GetCharPosInLine(y, x)
411 if x > Count(v.Buf.Line(y)) {
412 x = Count(v.Buf.Line(y))
416 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
419 // HandleEvent handles an event passed by the main loop
420 func (v *View) HandleEvent(event tcell.Event) {
421 // This bool determines whether the view is relocated at the end of the function
422 // By default it's true because most events should cause a relocate
427 switch e := event.(type) {
428 case *tcell.EventResize:
430 tabs[v.TabNum].Resize()
431 case *tcell.EventKey:
432 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
434 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
435 for key, actions := range bindings {
436 if e.Key() == key.keyCode {
437 if e.Key() == tcell.KeyRune {
438 if e.Rune() != key.r {
442 if e.Modifiers() == key.modifiers {
445 for _, action := range actions {
446 relocate = action(v, true) || relocate
447 funcName := FuncName(action)
448 if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
450 curMacro = append(curMacro, action)
459 if !isBinding && e.Key() == tcell.KeyRune {
460 // Insert a character
461 if v.Cursor.HasSelection() {
462 v.Cursor.DeleteSelection()
463 v.Cursor.ResetSelection()
465 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
468 for _, pl := range loadedPlugins {
469 _, err := Call(pl+".onRune", string(e.Rune()), v)
470 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
476 curMacro = append(curMacro, e.Rune())
479 case *tcell.EventPaste:
480 if !PreActionCall("Paste", v) {
486 PostActionCall("Paste", v)
487 case *tcell.EventMouse:
489 x -= v.lineNumOffset - v.leftCol + v.x
491 // Don't relocate for mouse events
494 button := e.Buttons()
500 v.MoveToMouseClick(x, y)
501 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
504 v.lastClickTime = time.Now()
507 v.doubleClick = false
509 v.Cursor.SelectLine()
512 v.lastClickTime = time.Now()
515 v.tripleClick = false
517 v.Cursor.SelectWord()
520 v.doubleClick = false
521 v.tripleClick = false
522 v.lastClickTime = time.Now()
524 v.Cursor.OrigSelection[0] = v.Cursor.Loc
525 v.Cursor.CurSelection[0] = v.Cursor.Loc
526 v.Cursor.CurSelection[1] = v.Cursor.Loc
528 v.mouseReleased = false
529 } else if !v.mouseReleased {
530 v.MoveToMouseClick(x, y)
532 v.Cursor.AddLineToSelection()
533 } else if v.doubleClick {
534 v.Cursor.AddWordToSelection()
536 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
540 // Middle mouse button was clicked,
541 // We should paste primary
543 case tcell.ButtonNone:
544 // Mouse event with no click
545 if !v.mouseReleased {
546 // Mouse was just released
548 // Relocating here isn't really necessary because the cursor will
549 // be in the right place from the last mouse event
550 // However, if we are running in a terminal that doesn't support mouse motion
551 // events, this still allows the user to make selections, except only after they
554 if !v.doubleClick && !v.tripleClick {
555 v.MoveToMouseClick(x, y)
556 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
558 v.mouseReleased = true
562 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
563 v.ScrollUp(scrollspeed)
564 case tcell.WheelDown:
566 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
567 v.ScrollDown(scrollspeed)
576 // GutterMessage creates a message in this view's gutter
577 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
579 gutterMsg := GutterMessage{
584 for _, v := range v.messages {
585 for _, gmsg := range v {
586 if gmsg.lineNum == lineN {
591 messages := v.messages[section]
592 v.messages[section] = append(messages, gutterMsg)
595 // ClearGutterMessages clears all gutter messages from a given section
596 func (v *View) ClearGutterMessages(section string) {
597 v.messages[section] = []GutterMessage{}
600 // ClearAllGutterMessages clears all the gutter messages
601 func (v *View) ClearAllGutterMessages() {
602 for k := range v.messages {
603 v.messages[k] = []GutterMessage{}
607 // Opens the given help page in a new horizontal split
608 func (v *View) openHelp(helpPage string) {
609 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
610 TermMessage("Unable to load help text", helpPage, "\n", err)
612 helpBuffer := NewBuffer(data, helpPage+".md")
613 helpBuffer.Name = "Help"
615 if v.Type == vtHelp {
616 v.OpenBuffer(helpBuffer)
619 CurView().Type = vtHelp
624 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
625 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
626 screen.SetContent(x, y, ch, combc, style)
630 // DisplayView renders the view to the screen
631 func (v *View) DisplayView() {
633 // Log views should always follow the cursor...
637 if v.Buf.Settings["syntax"].(bool) {
641 // The charNum we are currently displaying
642 // starts at the start of the viewport
643 charNum := Loc{0, v.Topline}
645 // Convert the length of buffer to a string, and get the length of the string
646 // We are going to have to offset by that amount
647 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
649 if v.Buf.Settings["ruler"] == true {
650 // + 1 for the little space after the line number
651 v.lineNumOffset = maxLineLength + 1
656 // We need to add to the line offset if there are gutter messages
657 var hasGutterMessages bool
658 for _, v := range v.messages {
660 hasGutterMessages = true
663 if hasGutterMessages {
668 // One space for the extra split divider
672 // These represent the current screen coordinates
673 screenX, screenY := v.x, v.y-1
675 highlightStyle := defStyle
678 // ViewLine is the current line from the top of the viewport
679 for viewLine := 0; viewLine < v.height; viewLine++ {
683 // This is the current line number of the buffer that we are drawing
684 curLineN = viewLine + v.Topline
686 if screenY-v.y >= v.height {
691 // Draw the split divider
692 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
696 // If the buffer is smaller than the view height we have to clear all this space
697 if curLineN >= v.Buf.NumLines {
698 for i := screenX; i < v.x+v.width; i++ {
699 v.drawCell(i, screenY, ' ', nil, defStyle)
704 line := v.Buf.Line(curLineN)
706 // If there are gutter messages we need to display the '>>' symbol here
707 if hasGutterMessages {
708 // msgOnLine stores whether or not there is a gutter message on this line in particular
710 for k := range v.messages {
711 for _, msg := range v.messages[k] {
712 if msg.lineNum == curLineN {
714 gutterStyle := defStyle
717 if style, ok := colorscheme["gutter-info"]; ok {
721 if style, ok := colorscheme["gutter-warning"]; ok {
725 if style, ok := colorscheme["gutter-error"]; ok {
729 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
731 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
733 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
734 messenger.Message(msg.msg)
735 messenger.gutterMessage = true
740 // If there is no message on this line we just display an empty offset
742 v.drawCell(screenX, screenY, ' ', nil, defStyle)
744 v.drawCell(screenX, screenY, ' ', nil, defStyle)
746 if v.Cursor.Y == curLineN && messenger.gutterMessage {
748 messenger.gutterMessage = false
753 lineNumStyle := defStyle
754 if v.Buf.Settings["ruler"] == true {
755 // Write the line number
756 if style, ok := colorscheme["line-number"]; ok {
759 if style, ok := colorscheme["current-line-number"]; ok {
760 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
765 lineNum := strconv.Itoa(curLineN + 1)
767 // Write the spaces before the line number if necessary
768 for i := 0; i < maxLineLength-len(lineNum); i++ {
769 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
772 // Write the actual line number
773 for _, ch := range lineNum {
774 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
778 // Write the extra space
779 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
783 // Now we actually draw the line
786 tabSize := int(v.Buf.Settings["tabsize"].(float64))
787 for _, ch := range line {
788 if v.Buf.Settings["softwrap"].(bool) {
789 if screenX-v.x >= v.width {
791 for i := 0; i < v.lineNumOffset; i++ {
792 screen.SetContent(v.x+i, screenY, ' ', nil, lineNumStyle)
794 screenX = v.x + v.lineNumOffset
798 if tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN && colN == v.Cursor.X {
799 v.DisplayCursor(screenX-v.leftCol, screenY)
802 lineStyle := defStyle
804 if v.Buf.Settings["syntax"].(bool) {
805 // Syntax highlighting is enabled
806 highlightStyle = v.matches[viewLine][colN]
809 if v.Cursor.HasSelection() &&
810 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
811 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
812 // The current character is selected
813 lineStyle = defStyle.Reverse(true)
815 if style, ok := colorscheme["selection"]; ok {
819 lineStyle = highlightStyle
822 // We need to display the background of the linestyle with the correct color if cursorline is enabled
823 // and this is the current view and there is no selection on this line and the cursor is on this line
824 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
825 if style, ok := colorscheme["cursor-line"]; ok {
826 fg, _, _ := style.Decompose()
827 lineStyle = lineStyle.Background(fg)
832 // If the character we are displaying is a tab, we need to do a bunch of special things
834 // First the user may have configured an `indent-char` to be displayed to show that this
835 // is a tab character
836 lineIndentStyle := defStyle
837 if style, ok := colorscheme["indent-char"]; ok && v.Buf.Settings["indentchar"].(string) != " " {
838 lineIndentStyle = style
840 if v.Cursor.HasSelection() &&
841 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
842 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
844 lineIndentStyle = defStyle.Reverse(true)
846 if style, ok := colorscheme["selection"]; ok {
847 lineIndentStyle = style
850 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
851 if style, ok := colorscheme["cursor-line"]; ok {
852 fg, _, _ := style.Decompose()
853 lineIndentStyle = lineIndentStyle.Background(fg)
856 // Here we get the indent char
857 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
858 if screenX-v.x-v.leftCol >= v.lineNumOffset {
859 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
861 // Now the tab has to be displayed as a bunch of spaces
863 remainder := tabSize - (visLoc % tabSize)
864 for i := 0; i < remainder-1; i++ {
866 if screenX-v.x-v.leftCol >= v.lineNumOffset {
867 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
870 } else if runewidth.RuneWidth(ch) > 1 {
871 if screenX-v.x-v.leftCol >= v.lineNumOffset {
872 v.drawCell(screenX, screenY, ch, nil, lineStyle)
874 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
876 if screenX-v.x-v.leftCol >= v.lineNumOffset {
877 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
881 if screenX-v.x-v.leftCol >= v.lineNumOffset {
882 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
885 charNum = charNum.Move(1, v.Buf)
888 strWidth += StringWidth(string(ch), tabSize)
890 // Here we are at a newline
892 if tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN && colN == v.Cursor.X {
893 v.DisplayCursor(screenX-v.leftCol, screenY)
896 // The newline may be selected, in which case we should draw the selection style
897 // with a space to represent it
898 if v.Cursor.HasSelection() &&
899 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
900 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
902 selectStyle := defStyle.Reverse(true)
904 if style, ok := colorscheme["selection"]; ok {
907 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
911 charNum = charNum.Move(1, v.Buf)
913 for i := 0; i < v.width; i++ {
914 lineStyle := defStyle
915 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
916 if style, ok := colorscheme["cursor-line"]; ok {
917 fg, _, _ := style.Decompose()
918 lineStyle = lineStyle.Background(fg)
921 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
922 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
923 if colorcolumn != 0 && screenX-v.lineNumOffset+i == colorcolumn-1 {
924 if style, ok := colorscheme["color-column"]; ok {
925 fg, _, _ := style.Decompose()
926 lineStyle = lineStyle.Background(fg)
929 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
935 // DisplayCursor draws the current buffer's cursor to the screen
936 func (v *View) DisplayCursor(x, y int) {
937 // screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, y)
938 screen.ShowCursor(x, y)
941 // Display renders the view, the cursor, and statusline
942 func (v *View) Display() {
944 // Don't draw the cursor if it is out of the viewport or if it has a selection
945 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
948 _, screenH := screen.Size()
949 if v.Buf.Settings["statusline"].(bool) {
951 } else if (v.y + v.height) != screenH-1 {
952 for x := 0; x < v.width; x++ {
953 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))