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
32 // The leftmost column, used for horizontal scrolling
35 // Percentage of the terminal window that this view takes up (from 0 to 100)
39 // Specifies whether or not this view holds a help buffer
42 // Actual width and height
46 // Where this view is located
49 // How much to offset because of line numbers
52 // Holds the list of gutter messages
53 messages map[string][]GutterMessage
55 // This is the index of this view in the views array
57 // What tab is this view stored in
65 // Since tcell doesn't differentiate between a mouse release event
66 // and a mouse move event with no keys pressed, we need to keep
67 // track of whether or not the mouse was pressed (or not released) last event to determine
68 // mouse release events
71 // This stores when the last click was
72 // This is useful for detecting double and triple clicks
73 lastClickTime time.Time
75 // lastCutTime stores when the last ctrl+k was issued.
76 // It is used for clearing the clipboard to replace it with fresh cut lines.
79 // freshClip returns true if the clipboard has never been pasted.
82 // Was the last mouse event actually a double click?
83 // Useful for detecting triple clicks -- if a double click is detected
84 // but the last mouse event was actually a double click, it's a triple click
86 // Same here, just to keep track for mouse move events
89 // Syntax highlighting matches
95 // NewView returns a new fullscreen view
96 func NewView(buf *Buffer) *View {
97 screenW, screenH := screen.Size()
98 return NewViewWidthHeight(buf, screenW, screenH)
101 // NewViewWidthHeight returns a new view with the specified width and height
102 // Note that w and h are raw column and row values
103 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
115 v.messages = make(map[string][]GutterMessage)
117 v.sline = Statusline{
121 if v.Buf.Settings["statusline"].(bool) {
125 for _, pl := range loadedPlugins {
126 _, err := Call(pl+".onViewOpen", v)
127 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
136 func (v *View) ToggleStatusLine() {
137 if v.Buf.Settings["statusline"].(bool) {
144 func (v *View) ToggleTabbar() {
147 // Include one line for the tab bar at the top
159 func (v *View) paste(clip string) {
160 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
162 if v.Cursor.HasSelection() {
163 v.Cursor.DeleteSelection()
164 v.Cursor.ResetSelection()
166 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
167 v.Buf.Insert(v.Cursor.Loc, clip)
168 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
170 messenger.Message("Pasted clipboard")
173 // ScrollUp scrolls the view up n lines (if possible)
174 func (v *View) ScrollUp(n int) {
175 // Try to scroll by n but if it would overflow, scroll by 1
176 if v.Topline-n >= 0 {
178 } else if v.Topline > 0 {
183 // ScrollDown scrolls the view down n lines (if possible)
184 func (v *View) ScrollDown(n int) {
185 // Try to scroll by n but if it would overflow, scroll by 1
186 if v.Topline+n <= v.Buf.NumLines-v.height {
188 } else if v.Topline < v.Buf.NumLines-v.height {
193 // CanClose returns whether or not the view can be closed
194 // If there are unsaved changes, the user will be asked if the view can be closed
195 // causing them to lose the unsaved changes
196 func (v *View) CanClose() bool {
197 if v.Type == vtDefault && v.Buf.IsModified {
200 if v.Buf.Settings["autosave"].(bool) {
203 char, canceled = messenger.LetterPrompt("Save changes to "+v.Buf.Name+" before closing? (y,n,esc) ", 'y', 'n')
209 } else if char == 'n' {
219 // OpenBuffer opens a new buffer in this view.
220 // This resets the topline, event handler and cursor.
221 func (v *View) OpenBuffer(buf *Buffer) {
225 v.Cursor = &buf.Cursor
228 v.Cursor.ResetSelection()
231 v.messages = make(map[string][]GutterMessage)
235 // Set mouseReleased to true because we assume the mouse is not being pressed when
236 // the editor is opened
237 v.mouseReleased = true
238 v.lastClickTime = time.Time{}
241 func (v *View) Open(filename string) {
242 home, _ := homedir.Dir()
243 filename = strings.Replace(filename, "~", home, 1)
244 file, err := ioutil.ReadFile(filename)
248 messenger.Message(err.Error())
249 // File does not exist -- create an empty buffer with that name
250 buf = NewBuffer([]byte{}, filename)
252 buf = NewBuffer(file, filename)
257 // CloseBuffer performs any closing functions on the buffer
258 func (v *View) CloseBuffer() {
264 // ReOpen reloads the current buffer
265 func (v *View) ReOpen() {
274 // HSplit opens a horizontal split with the given buffer
275 func (v *View) HSplit(buf *Buffer) bool {
276 v.splitNode.HSplit(buf)
277 tabs[v.TabNum].Resize()
281 // VSplit opens a vertical split with the given buffer
282 func (v *View) VSplit(buf *Buffer) bool {
283 v.splitNode.VSplit(buf)
284 tabs[v.TabNum].Resize()
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 {
291 height := v.Bottomline - v.Topline
294 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
295 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
296 v.Topline = cy - scrollmargin
298 } else if cy < v.Topline {
302 if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
303 v.Topline = cy - height + 1 + scrollmargin
305 } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
306 v.Topline = v.Buf.NumLines - height
310 if !v.Buf.Settings["softwrap"].(bool) {
311 cx := v.Cursor.GetVisualX()
316 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
317 v.leftCol = cx - v.width + v.lineNumOffset + 1
324 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
326 func (v *View) MoveToMouseClick(x, y int) {
327 if y-v.Topline > v.height-1 {
329 y = v.height + v.Topline - 1
331 if y >= v.Buf.NumLines {
332 y = v.Buf.NumLines - 1
341 x = v.Cursor.GetCharPosInLine(y, x)
342 if x > Count(v.Buf.Line(y)) {
343 x = Count(v.Buf.Line(y))
347 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
350 // HandleEvent handles an event passed by the main loop
351 func (v *View) HandleEvent(event tcell.Event) {
352 // This bool determines whether the view is relocated at the end of the function
353 // By default it's true because most events should cause a relocate
358 switch e := event.(type) {
359 case *tcell.EventResize:
361 tabs[v.TabNum].Resize()
362 case *tcell.EventKey:
363 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
365 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
366 for key, actions := range bindings {
367 if e.Key() == key.keyCode {
368 if e.Key() == tcell.KeyRune {
369 if e.Rune() != key.r {
373 if e.Modifiers() == key.modifiers {
376 for _, action := range actions {
377 relocate = action(v, true) || relocate
378 funcName := FuncName(action)
379 if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
381 curMacro = append(curMacro, action)
390 if !isBinding && e.Key() == tcell.KeyRune {
391 // Insert a character
392 if v.Cursor.HasSelection() {
393 v.Cursor.DeleteSelection()
394 v.Cursor.ResetSelection()
396 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
399 for _, pl := range loadedPlugins {
400 _, err := Call(pl+".onRune", string(e.Rune()), v)
401 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
407 curMacro = append(curMacro, e.Rune())
410 case *tcell.EventPaste:
411 if !PreActionCall("Paste", v) {
415 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
417 if v.Cursor.HasSelection() {
418 v.Cursor.DeleteSelection()
419 v.Cursor.ResetSelection()
422 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
423 v.Buf.Insert(v.Cursor.Loc, clip)
424 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
426 messenger.Message("Pasted clipboard")
428 PostActionCall("Paste", v)
429 case *tcell.EventMouse:
431 x -= v.lineNumOffset - v.leftCol + v.x
433 // Don't relocate for mouse events
436 button := e.Buttons()
442 v.MoveToMouseClick(x, y)
443 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
446 v.lastClickTime = time.Now()
449 v.doubleClick = false
451 v.Cursor.SelectLine()
454 v.lastClickTime = time.Now()
457 v.tripleClick = false
459 v.Cursor.SelectWord()
462 v.doubleClick = false
463 v.tripleClick = false
464 v.lastClickTime = time.Now()
466 v.Cursor.OrigSelection[0] = v.Cursor.Loc
467 v.Cursor.CurSelection[0] = v.Cursor.Loc
468 v.Cursor.CurSelection[1] = v.Cursor.Loc
470 v.mouseReleased = false
471 } else if !v.mouseReleased {
472 v.MoveToMouseClick(x, y)
474 v.Cursor.AddLineToSelection()
475 } else if v.doubleClick {
476 v.Cursor.AddWordToSelection()
478 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
482 // Middle mouse button was clicked,
483 // We should paste primary
485 case tcell.ButtonNone:
486 // Mouse event with no click
487 if !v.mouseReleased {
488 // Mouse was just released
490 // Relocating here isn't really necessary because the cursor will
491 // be in the right place from the last mouse event
492 // However, if we are running in a terminal that doesn't support mouse motion
493 // events, this still allows the user to make selections, except only after they
496 if !v.doubleClick && !v.tripleClick {
497 v.MoveToMouseClick(x, y)
498 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
500 v.mouseReleased = true
504 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
505 v.ScrollUp(scrollspeed)
506 case tcell.WheelDown:
508 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
509 v.ScrollDown(scrollspeed)
518 // GutterMessage creates a message in this view's gutter
519 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
521 gutterMsg := GutterMessage{
526 for _, v := range v.messages {
527 for _, gmsg := range v {
528 if gmsg.lineNum == lineN {
533 messages := v.messages[section]
534 v.messages[section] = append(messages, gutterMsg)
537 // ClearGutterMessages clears all gutter messages from a given section
538 func (v *View) ClearGutterMessages(section string) {
539 v.messages[section] = []GutterMessage{}
542 // ClearAllGutterMessages clears all the gutter messages
543 func (v *View) ClearAllGutterMessages() {
544 for k := range v.messages {
545 v.messages[k] = []GutterMessage{}
549 // Opens the given help page in a new horizontal split
550 func (v *View) openHelp(helpPage string) {
551 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
552 TermMessage("Unable to load help text", helpPage, "\n", err)
554 helpBuffer := NewBuffer(data, helpPage+".md")
555 helpBuffer.Name = "Help"
557 if v.Type == vtHelp {
558 v.OpenBuffer(helpBuffer)
561 CurView().Type = vtHelp
566 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
567 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
568 screen.SetContent(x, y, ch, combc, style)
572 // DisplayView renders the view to the screen
573 func (v *View) DisplayView() {
575 // Log views should always follow the cursor...
579 if v.Buf.Settings["syntax"].(bool) {
583 // The charNum we are currently displaying
584 // starts at the start of the viewport
585 charNum := Loc{0, v.Topline}
587 // Convert the length of buffer to a string, and get the length of the string
588 // We are going to have to offset by that amount
589 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
591 if v.Buf.Settings["ruler"] == true {
592 // + 1 for the little space after the line number
593 v.lineNumOffset = maxLineLength + 1
598 // We need to add to the line offset if there are gutter messages
599 var hasGutterMessages bool
600 for _, v := range v.messages {
602 hasGutterMessages = true
605 if hasGutterMessages {
610 // One space for the extra split divider
614 // These represent the current screen coordinates
615 screenX, screenY := v.x, v.y-1
617 highlightStyle := defStyle
619 // ViewLine is the current line from the top of the viewport
620 for viewLine := 0; viewLine < v.height; viewLine++ {
624 // This is the current line number of the buffer that we are drawing
625 curLineN := viewLine + v.Topline
627 if screenY >= v.height {
628 v.Bottomline = curLineN
633 // Draw the split divider
634 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
638 // If the buffer is smaller than the view height we have to clear all this space
639 if curLineN >= v.Buf.NumLines {
640 for i := screenX; i < v.x+v.width; i++ {
641 v.drawCell(i, screenY, ' ', nil, defStyle)
646 line := v.Buf.Line(curLineN)
648 // If there are gutter messages we need to display the '>>' symbol here
649 if hasGutterMessages {
650 // msgOnLine stores whether or not there is a gutter message on this line in particular
652 for k := range v.messages {
653 for _, msg := range v.messages[k] {
654 if msg.lineNum == curLineN {
656 gutterStyle := defStyle
659 if style, ok := colorscheme["gutter-info"]; ok {
663 if style, ok := colorscheme["gutter-warning"]; ok {
667 if style, ok := colorscheme["gutter-error"]; ok {
671 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
673 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
675 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
676 messenger.Message(msg.msg)
677 messenger.gutterMessage = true
682 // If there is no message on this line we just display an empty offset
684 v.drawCell(screenX, screenY, ' ', nil, defStyle)
686 v.drawCell(screenX, screenY, ' ', nil, defStyle)
688 if v.Cursor.Y == curLineN && messenger.gutterMessage {
690 messenger.gutterMessage = false
695 lineNumStyle := defStyle
696 if v.Buf.Settings["ruler"] == true {
697 // Write the line number
698 if style, ok := colorscheme["line-number"]; ok {
701 if style, ok := colorscheme["current-line-number"]; ok {
702 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
707 lineNum := strconv.Itoa(curLineN + 1)
709 // Write the spaces before the line number if necessary
710 for i := 0; i < maxLineLength-len(lineNum); i++ {
711 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
714 // Write the actual line number
715 for _, ch := range lineNum {
716 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
720 // Write the extra space
721 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
725 // Now we actually draw the line
728 tabSize := int(v.Buf.Settings["tabsize"].(float64))
729 for _, ch := range line {
730 if v.Buf.Settings["softwrap"].(bool) {
731 if screenX-v.x >= v.width {
733 for i := 0; i < v.lineNumOffset; i++ {
734 screen.SetContent(v.x+i, screenY, ' ', nil, lineNumStyle)
736 screenX = v.x + v.lineNumOffset
740 if tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN && colN == v.Cursor.X {
741 v.DisplayCursor(screenX, screenY)
744 lineStyle := defStyle
746 if v.Buf.Settings["syntax"].(bool) {
747 // Syntax highlighting is enabled
748 highlightStyle = v.matches[viewLine][colN]
751 if v.Cursor.HasSelection() &&
752 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
753 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
754 // The current character is selected
755 lineStyle = defStyle.Reverse(true)
757 if style, ok := colorscheme["selection"]; ok {
761 lineStyle = highlightStyle
764 // We need to display the background of the linestyle with the correct color if cursorline is enabled
765 // and this is the current view and there is no selection on this line and the cursor is on this line
766 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
767 if style, ok := colorscheme["cursor-line"]; ok {
768 fg, _, _ := style.Decompose()
769 lineStyle = lineStyle.Background(fg)
774 // If the character we are displaying is a tab, we need to do a bunch of special things
776 // First the user may have configured an `indent-char` to be displayed to show that this
777 // is a tab character
778 lineIndentStyle := defStyle
779 if style, ok := colorscheme["indent-char"]; ok && v.Buf.Settings["indentchar"].(string) != " " {
780 lineIndentStyle = style
782 if v.Cursor.HasSelection() &&
783 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
784 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
786 lineIndentStyle = defStyle.Reverse(true)
788 if style, ok := colorscheme["selection"]; ok {
789 lineIndentStyle = style
792 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
793 if style, ok := colorscheme["cursor-line"]; ok {
794 fg, _, _ := style.Decompose()
795 lineIndentStyle = lineIndentStyle.Background(fg)
798 // Here we get the indent char
799 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
800 if screenX-v.x-v.leftCol >= v.lineNumOffset {
801 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
803 // Now the tab has to be displayed as a bunch of spaces
805 remainder := tabSize - (visLoc % tabSize)
806 for i := 0; i < remainder-1; i++ {
808 if screenX-v.x-v.leftCol >= v.lineNumOffset {
809 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
812 } else if runewidth.RuneWidth(ch) > 1 {
813 if screenX-v.x-v.leftCol >= v.lineNumOffset {
814 v.drawCell(screenX, screenY, ch, nil, lineStyle)
816 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
818 if screenX-v.x-v.leftCol >= v.lineNumOffset {
819 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
823 if screenX-v.x-v.leftCol >= v.lineNumOffset {
824 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
827 charNum = charNum.Move(1, v.Buf)
830 strWidth += StringWidth(string(ch), tabSize)
832 // Here we are at a newline
834 if tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN && colN == v.Cursor.X {
835 v.DisplayCursor(screenX, screenY)
838 // The newline may be selected, in which case we should draw the selection style
839 // with a space to represent it
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 selectStyle := defStyle.Reverse(true)
846 if style, ok := colorscheme["selection"]; ok {
849 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
853 charNum = charNum.Move(1, v.Buf)
855 for i := 0; i < v.width; i++ {
856 lineStyle := defStyle
857 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
858 if style, ok := colorscheme["cursor-line"]; ok {
859 fg, _, _ := style.Decompose()
860 lineStyle = lineStyle.Background(fg)
863 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
864 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
865 if colorcolumn != 0 && screenX-v.lineNumOffset+i == colorcolumn-1 {
866 if style, ok := colorscheme["color-column"]; ok {
867 fg, _, _ := style.Decompose()
868 lineStyle = lineStyle.Background(fg)
871 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
877 // DisplayCursor draws the current buffer's cursor to the screen
878 func (v *View) DisplayCursor(x, y int) {
879 // screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, y)
880 screen.ShowCursor(x, y)
883 // Display renders the view, the cursor, and statusline
884 func (v *View) Display() {
886 // Don't draw the cursor if it is out of the viewport or if it has a selection
887 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
890 _, screenH := screen.Size()
891 if v.Buf.Settings["statusline"].(bool) {
893 } else if (v.y + v.height) != screenH-1 {
894 for x := 0; x < v.width; x++ {
895 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))