9 "github.com/mitchellh/go-homedir"
10 "github.com/zyedidia/tcell"
13 type ViewType struct {
15 readonly bool // The file cannot be edited
16 scratch bool // The file cannot be saved
20 vtDefault = ViewType{0, false, false}
21 vtHelp = ViewType{1, true, true}
22 vtLog = ViewType{2, true, true}
23 vtScratch = ViewType{3, false, true}
26 // The View struct stores information about a view into a buffer.
27 // It stores information about the cursor, and the viewport
28 // that the user sees the buffer from.
30 // A pointer to the buffer's cursor for ease of access
33 // The topmost line, used for vertical scrolling
35 // The leftmost column, used for horizontal scrolling
38 // Specifies whether or not this view holds a help buffer
41 // Actual width and height
48 // Where this view is located
51 // How much to offset because of line numbers
54 // Holds the list of gutter messages
55 messages map[string][]GutterMessage
57 // This is the index of this view in the views array
59 // What tab is this view stored in
67 // Since tcell doesn't differentiate between a mouse release event
68 // and a mouse move event with no keys pressed, we need to keep
69 // track of whether or not the mouse was pressed (or not released) last event to determine
70 // mouse release events
73 // This stores when the last click was
74 // This is useful for detecting double and triple clicks
75 lastClickTime time.Time
77 // lastCutTime stores when the last ctrl+k was issued.
78 // It is used for clearing the clipboard to replace it with fresh cut lines.
81 // freshClip returns true if the clipboard has never been pasted.
84 // Was the last mouse event actually a double click?
85 // Useful for detecting triple clicks -- if a double click is detected
86 // but the last mouse event was actually a double click, it's a triple click
88 // Same here, just to keep track for mouse move events
96 // NewView returns a new fullscreen view
97 func NewView(buf *Buffer) *View {
98 screenW, screenH := screen.Size()
99 return NewViewWidthHeight(buf, screenW, screenH)
102 // NewViewWidthHeight returns a new view with the specified width and height
103 // Note that w and h are raw column and row values
104 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
111 v.cellview = new(CellView)
117 v.messages = make(map[string][]GutterMessage)
119 v.sline = Statusline{
123 if v.Buf.Settings["statusline"].(bool) {
127 for pl := range loadedPlugins {
128 _, err := Call(pl+".onViewOpen", v)
129 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
138 // ToggleStatusLine creates an extra row for the statusline if necessary
139 func (v *View) ToggleStatusLine() {
140 if v.Buf.Settings["statusline"].(bool) {
147 // ToggleTabbar creates an extra row for the tabbar if necessary
148 func (v *View) ToggleTabbar() {
151 // Include one line for the tab bar at the top
163 func (v *View) paste(clip string) {
164 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
166 if v.Cursor.HasSelection() {
167 v.Cursor.DeleteSelection()
168 v.Cursor.ResetSelection()
170 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
171 v.Buf.Insert(v.Cursor.Loc, clip)
172 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
174 messenger.Message("Pasted clipboard")
177 // ScrollUp scrolls the view up n lines (if possible)
178 func (v *View) ScrollUp(n int) {
179 // Try to scroll by n but if it would overflow, scroll by 1
180 if v.Topline-n >= 0 {
182 } else if v.Topline > 0 {
187 // ScrollDown scrolls the view down n lines (if possible)
188 func (v *View) ScrollDown(n int) {
189 // Try to scroll by n but if it would overflow, scroll by 1
190 if v.Topline+n <= v.Buf.NumLines {
192 } else if v.Topline < v.Buf.NumLines-1 {
197 // CanClose returns whether or not the view can be closed
198 // If there are unsaved changes, the user will be asked if the view can be closed
199 // causing them to lose the unsaved changes
200 func (v *View) CanClose() bool {
201 if v.Type == vtDefault && v.Buf.IsModified {
204 if v.Buf.Settings["autosave"].(bool) {
207 char, canceled = messenger.LetterPrompt("Save changes to "+v.Buf.GetName()+" before closing? (y,n,esc) ", 'y', 'n')
213 } else if char == 'n' {
223 // OpenBuffer opens a new buffer in this view.
224 // This resets the topline, event handler and cursor.
225 func (v *View) OpenBuffer(buf *Buffer) {
229 v.Cursor = &buf.Cursor
232 v.Cursor.ResetSelection()
235 v.messages = make(map[string][]GutterMessage)
237 // Set mouseReleased to true because we assume the mouse is not being pressed when
238 // the editor is opened
239 v.mouseReleased = true
240 v.lastClickTime = time.Time{}
243 // Open opens the given file in the view
244 func (v *View) Open(filename string) {
245 home, _ := homedir.Dir()
246 filename = strings.Replace(filename, "~", home, 1)
247 file, err := os.Open(filename)
248 fileInfo, _ := os.Stat(filename)
250 if err == nil && fileInfo.IsDir() {
251 messenger.Error(filename, " is a directory")
259 messenger.Message(err.Error())
260 // File does not exist -- create an empty buffer with that name
261 buf = NewBufferFromString("", filename)
263 buf = NewBuffer(file, FSize(file), filename)
268 // CloseBuffer performs any closing functions on the buffer
269 func (v *View) CloseBuffer() {
275 // ReOpen reloads the current buffer
276 func (v *View) ReOpen() {
284 // HSplit opens a horizontal split with the given buffer
285 func (v *View) HSplit(buf *Buffer) {
287 if v.Buf.Settings["splitBottom"].(bool) {
290 v.splitNode.HSplit(buf, v.Num+i)
293 // VSplit opens a vertical split with the given buffer
294 func (v *View) VSplit(buf *Buffer) {
296 if v.Buf.Settings["splitRight"].(bool) {
299 v.splitNode.VSplit(buf, v.Num+i)
302 // HSplitIndex opens a horizontal split with the given buffer at the given index
303 func (v *View) HSplitIndex(buf *Buffer, splitIndex int) {
304 v.splitNode.HSplit(buf, splitIndex)
307 // VSplitIndex opens a vertical split with the given buffer at the given index
308 func (v *View) VSplitIndex(buf *Buffer, splitIndex int) {
309 v.splitNode.VSplit(buf, splitIndex)
312 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
313 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
314 if !v.Buf.Settings["softwrap"].(bool) {
315 if vy >= v.Buf.NumLines {
316 vy = v.Buf.NumLines - 1
318 vx = v.Cursor.GetCharPosInLine(vy, vx)
322 screenX, screenY := 0, v.Topline
323 for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
324 line := v.Buf.Line(lineN)
325 if lineN >= v.Buf.NumLines {
326 return 0, v.Buf.NumLines - 1
330 for _, ch := range line {
331 if screenX >= v.Width-v.lineNumOffset {
336 if screenX == vx && screenY == vy {
341 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
357 func (v *View) Bottomline() int {
358 if !v.Buf.Settings["softwrap"].(bool) {
359 return v.Topline + v.Height
362 screenX, screenY := 0, 0
364 for lineN := v.Topline; lineN < v.Topline+v.Height; lineN++ {
365 line := v.Buf.Line(lineN)
368 for _, ch := range line {
369 if screenX >= v.Width-v.lineNumOffset {
375 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
385 if screenY >= v.Height {
389 return numLines + v.Topline
392 // Relocate moves the view window so that the cursor is in view
393 // This is useful if the user has scrolled far away, and then starts typing
394 func (v *View) Relocate() bool {
395 height := v.Bottomline() - v.Topline
398 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
399 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
400 v.Topline = cy - scrollmargin
402 } else if cy < v.Topline {
406 if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
407 v.Topline = cy - height + 1 + scrollmargin
409 } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
410 v.Topline = v.Buf.NumLines - height
414 if !v.Buf.Settings["softwrap"].(bool) {
415 cx := v.Cursor.GetVisualX()
420 if cx+v.lineNumOffset+1 > v.leftCol+v.Width {
421 v.leftCol = cx - v.Width + v.lineNumOffset + 1
428 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
430 func (v *View) MoveToMouseClick(x, y int) {
431 if y-v.Topline > v.Height-1 {
433 y = v.Height + v.Topline - 1
442 x, y = v.GetSoftWrapLocation(x, y)
443 // x = v.Cursor.GetCharPosInLine(y, x)
444 if x > Count(v.Buf.Line(y)) {
445 x = Count(v.Buf.Line(y))
449 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
452 // HandleEvent handles an event passed by the main loop
453 func (v *View) HandleEvent(event tcell.Event) {
454 // This bool determines whether the view is relocated at the end of the function
455 // By default it's true because most events should cause a relocate
460 switch e := event.(type) {
461 case *tcell.EventKey:
462 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
464 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
465 for key, actions := range bindings {
466 if e.Key() == key.keyCode {
467 if e.Key() == tcell.KeyRune {
468 if e.Rune() != key.r {
472 if e.Modifiers() == key.modifiers {
475 for _, action := range actions {
476 relocate = action(v, true) || relocate
477 funcName := FuncName(action)
478 if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
480 curMacro = append(curMacro, action)
489 if !isBinding && e.Key() == tcell.KeyRune {
490 // Insert a character
491 if v.Cursor.HasSelection() {
492 v.Cursor.DeleteSelection()
493 v.Cursor.ResetSelection()
495 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
498 for pl := range loadedPlugins {
499 _, err := Call(pl+".onRune", string(e.Rune()), v)
500 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
506 curMacro = append(curMacro, e.Rune())
509 case *tcell.EventPaste:
510 if !PreActionCall("Paste", v) {
516 PostActionCall("Paste", v)
517 case *tcell.EventMouse:
519 x -= v.lineNumOffset - v.leftCol + v.x
521 // Don't relocate for mouse events
524 button := e.Buttons()
530 v.MoveToMouseClick(x, y)
531 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
534 v.lastClickTime = time.Now()
537 v.doubleClick = false
539 v.Cursor.SelectLine()
540 v.Cursor.CopySelection("primary")
543 v.lastClickTime = time.Now()
546 v.tripleClick = false
548 v.Cursor.SelectWord()
549 v.Cursor.CopySelection("primary")
552 v.doubleClick = false
553 v.tripleClick = false
554 v.lastClickTime = time.Now()
556 v.Cursor.OrigSelection[0] = v.Cursor.Loc
557 v.Cursor.CurSelection[0] = v.Cursor.Loc
558 v.Cursor.CurSelection[1] = v.Cursor.Loc
560 v.mouseReleased = false
561 } else if !v.mouseReleased {
562 v.MoveToMouseClick(x, y)
564 v.Cursor.AddLineToSelection()
565 } else if v.doubleClick {
566 v.Cursor.AddWordToSelection()
568 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
569 v.Cursor.CopySelection("primary")
573 // Middle mouse button was clicked,
574 // We should paste primary
576 case tcell.ButtonNone:
577 // Mouse event with no click
578 if !v.mouseReleased {
579 // Mouse was just released
581 // Relocating here isn't really necessary because the cursor will
582 // be in the right place from the last mouse event
583 // However, if we are running in a terminal that doesn't support mouse motion
584 // events, this still allows the user to make selections, except only after they
587 if !v.doubleClick && !v.tripleClick {
588 v.MoveToMouseClick(x, y)
589 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
590 v.Cursor.CopySelection("primary")
592 v.mouseReleased = true
596 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
597 v.ScrollUp(scrollspeed)
598 case tcell.WheelDown:
600 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
601 v.ScrollDown(scrollspeed)
607 // We run relocate again because there's a bug with relocating with softwrap
608 // when for example you jump to the bottom of the buffer and it tries to
609 // calculate where to put the topline so that the bottom line is at the bottom
610 // of the terminal and it runs into problems with visual lines vs real lines.
611 // This is (hopefully) a temporary solution
616 // GutterMessage creates a message in this view's gutter
617 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
619 gutterMsg := GutterMessage{
624 for _, v := range v.messages {
625 for _, gmsg := range v {
626 if gmsg.lineNum == lineN {
631 messages := v.messages[section]
632 v.messages[section] = append(messages, gutterMsg)
635 // ClearGutterMessages clears all gutter messages from a given section
636 func (v *View) ClearGutterMessages(section string) {
637 v.messages[section] = []GutterMessage{}
640 // ClearAllGutterMessages clears all the gutter messages
641 func (v *View) ClearAllGutterMessages() {
642 for k := range v.messages {
643 v.messages[k] = []GutterMessage{}
647 // Opens the given help page in a new horizontal split
648 func (v *View) openHelp(helpPage string) {
649 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
650 TermMessage("Unable to load help text", helpPage, "\n", err)
652 helpBuffer := NewBufferFromString(string(data), helpPage+".md")
653 helpBuffer.name = "Help"
655 if v.Type == vtHelp {
656 v.OpenBuffer(helpBuffer)
659 CurView().Type = vtHelp
664 func (v *View) DisplayView() {
666 // Log views should always follow the cursor...
670 // We need to know the string length of the largest line number
671 // so we can pad appropriately when displaying line numbers
672 maxLineNumLength := len(strconv.Itoa(v.Buf.NumLines))
674 if v.Buf.Settings["ruler"] == true {
675 // + 1 for the little space after the line number
676 v.lineNumOffset = maxLineNumLength + 1
681 // We need to add to the line offset if there are gutter messages
682 var hasGutterMessages bool
683 for _, v := range v.messages {
685 hasGutterMessages = true
688 if hasGutterMessages {
693 // One space for the extra split divider
697 xOffset := v.x + v.lineNumOffset
705 v.cellview.Draw(v.Buf, top, height, left, width-v.lineNumOffset)
711 for visualLineN, line = range v.cellview.lines {
718 if firstChar != nil {
719 if firstChar.realLoc.Y == realLineN {
722 realLineN = firstChar.realLoc.Y
727 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
728 if colorcolumn != 0 {
729 style := GetColor("color-column")
730 fg, _, _ := style.Decompose()
731 st := defStyle.Background(fg)
732 screen.SetContent(xOffset+colorcolumn, yOffset+visualLineN, ' ', nil, st)
737 // If there are gutter messages we need to display the '>>' symbol here
738 if hasGutterMessages {
739 // msgOnLine stores whether or not there is a gutter message on this line in particular
741 for k := range v.messages {
742 for _, msg := range v.messages[k] {
743 if msg.lineNum == realLineN {
745 gutterStyle := defStyle
748 if style, ok := colorscheme["gutter-info"]; ok {
752 if style, ok := colorscheme["gutter-warning"]; ok {
756 if style, ok := colorscheme["gutter-error"]; ok {
760 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
762 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
764 if v.Cursor.Y == realLineN && !messenger.hasPrompt {
765 messenger.Message(msg.msg)
766 messenger.gutterMessage = true
771 // If there is no message on this line we just display an empty offset
773 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
775 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
777 if v.Cursor.Y == realLineN && messenger.gutterMessage {
779 messenger.gutterMessage = false
784 lineNumStyle := defStyle
785 if v.Buf.Settings["ruler"] == true {
786 // Write the line number
787 if style, ok := colorscheme["line-number"]; ok {
790 if style, ok := colorscheme["current-line-number"]; ok {
791 if realLineN == v.Cursor.Y && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() {
796 lineNum := strconv.Itoa(realLineN + 1)
798 // Write the spaces before the line number if necessary
799 for i := 0; i < maxLineNumLength-len(lineNum); i++ {
800 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, lineNumStyle)
803 if softwrapped && visualLineN != 0 {
804 // Pad without the line number because it was written on the visual line before
806 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, lineNumStyle)
810 // Write the actual line number
811 for _, ch := range lineNum {
812 screen.SetContent(screenX, yOffset+visualLineN, ch, nil, lineNumStyle)
817 // Write the extra space
818 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, lineNumStyle)
824 for _, char := range line {
826 lineStyle := char.style
828 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
829 if colorcolumn != 0 && char.visualLoc.X == colorcolumn {
830 style := GetColor("color-column")
831 fg, _, _ := style.Decompose()
832 lineStyle = lineStyle.Background(fg)
835 charLoc := char.realLoc
836 if v.Cursor.HasSelection() &&
837 (charLoc.GreaterEqual(v.Cursor.CurSelection[0]) && charLoc.LessThan(v.Cursor.CurSelection[1]) ||
838 charLoc.LessThan(v.Cursor.CurSelection[0]) && charLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
839 // The current character is selected
840 lineStyle = defStyle.Reverse(true)
842 if style, ok := colorscheme["selection"]; ok {
847 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
848 v.Cursor.Y == char.realLoc.Y && v.Cursor.X == char.realLoc.X && !cursorSet {
849 screen.ShowCursor(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y)
853 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
854 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
855 style := GetColor("cursor-line")
856 fg, _, _ := style.Decompose()
857 lineStyle = lineStyle.Background(fg)
860 screen.SetContent(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, char.drawChar, nil, lineStyle)
871 lastX = xOffset + lastChar.visualLoc.X + lastChar.width
872 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
873 v.Cursor.Y == lastChar.realLoc.Y && v.Cursor.X == lastChar.realLoc.X+1 {
874 screen.ShowCursor(lastX, yOffset+lastChar.visualLoc.Y)
875 cx, cy = lastX, yOffset+lastChar.visualLoc.Y
877 realLoc = Loc{lastChar.realLoc.X, realLineN}
878 visualLoc = Loc{lastX - xOffset, lastChar.visualLoc.Y}
879 } else if len(line) == 0 {
880 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
881 v.Cursor.Y == realLineN {
882 screen.ShowCursor(xOffset, yOffset+visualLineN)
883 cx, cy = xOffset, yOffset+visualLineN
886 realLoc = Loc{0, realLineN}
887 visualLoc = Loc{0, visualLineN}
890 if v.Cursor.HasSelection() &&
891 (realLoc.GreaterEqual(v.Cursor.CurSelection[0]) && realLoc.LessThan(v.Cursor.CurSelection[1]) ||
892 realLoc.LessThan(v.Cursor.CurSelection[0]) && realLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
893 // The current character is selected
894 selectStyle := defStyle.Reverse(true)
896 if style, ok := colorscheme["selection"]; ok {
899 screen.SetContent(xOffset+visualLoc.X, yOffset+visualLoc.Y, ' ', nil, selectStyle)
902 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
903 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
904 for i := lastX; i < xOffset+v.Width; i++ {
905 style := GetColor("cursor-line")
906 fg, _, _ := style.Decompose()
907 style = style.Background(fg)
908 if !(tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && i == cx && yOffset+visualLineN == cy) {
909 screen.SetContent(i, yOffset+visualLineN, ' ', nil, style)
915 if v.x != 0 && visualLineN < v.Height {
916 dividerStyle := defStyle
917 if style, ok := colorscheme["divider"]; ok {
920 for i := visualLineN + 1; i < v.Height; i++ {
921 screen.SetContent(v.x, yOffset+i, '|', nil, dividerStyle.Reverse(true))
926 // DisplayCursor draws the current buffer's cursor to the screen
927 func (v *View) DisplayCursor(x, y int) {
928 // screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, y)
929 screen.ShowCursor(x, y)
932 // Display renders the view, the cursor, and statusline
933 func (v *View) Display() {
935 // Don't draw the cursor if it is out of the viewport or if it has a selection
936 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.Height-1) || v.Cursor.HasSelection() {
939 _, screenH := screen.Size()
940 if v.Buf.Settings["statusline"].(bool) {
942 } else if (v.y + v.Height) != screenH-1 {
943 for x := 0; x < v.Width; x++ {
944 screen.SetContent(v.x+x, v.y+v.Height, '-', nil, defStyle.Reverse(true))