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 // Percentage of the terminal window that this view takes up (from 0 to 100)
38 // Specifies whether or not this view holds a help buffer
41 // Actual with and height
45 // Where this view is located
48 // How much to offset because of line numbers
51 // Holds the list of gutter messages
52 messages map[string][]GutterMessage
54 // This is the index of this view in the views array
56 // What tab is this view stored in
64 // Since tcell doesn't differentiate between a mouse release event
65 // and a mouse move event with no keys pressed, we need to keep
66 // track of whether or not the mouse was pressed (or not released) last event to determine
67 // mouse release events
70 // This stores when the last click was
71 // This is useful for detecting double and triple clicks
72 lastClickTime time.Time
74 // lastCutTime stores when the last ctrl+k was issued.
75 // It is used for clearing the clipboard to replace it with fresh cut lines.
78 // freshClip returns true if the clipboard has never been pasted.
81 // Was the last mouse event actually a double click?
82 // Useful for detecting triple clicks -- if a double click is detected
83 // but the last mouse event was actually a double click, it's a triple click
85 // Same here, just to keep track for mouse move events
88 // Syntax highlighting matches
94 // NewView returns a new fullscreen view
95 func NewView(buf *Buffer) *View {
96 screenW, screenH := screen.Size()
97 return NewViewWidthHeight(buf, screenW, screenH)
100 // NewViewWidthHeight returns a new view with the specified width and height
101 // Note that w and h are raw column and row values
102 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
114 v.messages = make(map[string][]GutterMessage)
116 v.sline = Statusline{
120 if v.Buf.Settings["statusline"].(bool) {
124 for _, pl := range loadedPlugins {
125 _, err := Call(pl+".onViewOpen", v)
126 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
135 func (v *View) ToggleStatusLine() {
136 if v.Buf.Settings["statusline"].(bool) {
143 func (v *View) ToggleTabbar() {
146 // Include one line for the tab bar at the top
158 func (v *View) paste(clip string) {
159 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
161 if v.Cursor.HasSelection() {
162 v.Cursor.DeleteSelection()
163 v.Cursor.ResetSelection()
165 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
166 v.Buf.Insert(v.Cursor.Loc, clip)
167 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
169 messenger.Message("Pasted clipboard")
172 // ScrollUp scrolls the view up n lines (if possible)
173 func (v *View) ScrollUp(n int) {
174 // Try to scroll by n but if it would overflow, scroll by 1
175 if v.Topline-n >= 0 {
177 } else if v.Topline > 0 {
182 // ScrollDown scrolls the view down n lines (if possible)
183 func (v *View) ScrollDown(n int) {
184 // Try to scroll by n but if it would overflow, scroll by 1
185 if v.Topline+n <= v.Buf.NumLines-v.height {
187 } else if v.Topline < v.Buf.NumLines-v.height {
192 // CanClose returns whether or not the view can be closed
193 // If there are unsaved changes, the user will be asked if the view can be closed
194 // causing them to lose the unsaved changes
195 func (v *View) CanClose() bool {
196 if v.Type == vtDefault && v.Buf.IsModified {
197 char, canceled := messenger.LetterPrompt("Save changes to "+v.Buf.Name+" before closing? (y,n,esc) ", 'y', 'n')
202 } else if char == 'n' {
212 // OpenBuffer opens a new buffer in this view.
213 // This resets the topline, event handler and cursor.
214 func (v *View) OpenBuffer(buf *Buffer) {
218 v.Cursor = &buf.Cursor
221 v.Cursor.ResetSelection()
224 v.messages = make(map[string][]GutterMessage)
228 // Set mouseReleased to true because we assume the mouse is not being pressed when
229 // the editor is opened
230 v.mouseReleased = true
231 v.lastClickTime = time.Time{}
234 func (v *View) Open(filename string) {
235 home, _ := homedir.Dir()
236 filename = strings.Replace(filename, "~", home, 1)
237 file, err := ioutil.ReadFile(filename)
241 messenger.Message(err.Error())
242 // File does not exist -- create an empty buffer with that name
243 buf = NewBuffer([]byte{}, filename)
245 buf = NewBuffer(file, filename)
250 // CloseBuffer performs any closing functions on the buffer
251 func (v *View) CloseBuffer() {
257 // ReOpen reloads the current buffer
258 func (v *View) ReOpen() {
267 // HSplit opens a horizontal split with the given buffer
268 func (v *View) HSplit(buf *Buffer) bool {
269 v.splitNode.HSplit(buf)
270 tabs[v.TabNum].Resize()
274 // VSplit opens a vertical split with the given buffer
275 func (v *View) VSplit(buf *Buffer) bool {
276 v.splitNode.VSplit(buf)
277 tabs[v.TabNum].Resize()
281 // Relocate moves the view window so that the cursor is in view
282 // This is useful if the user has scrolled far away, and then starts typing
283 func (v *View) Relocate() bool {
286 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
287 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
288 v.Topline = cy - scrollmargin
290 } else if cy < v.Topline {
294 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
295 v.Topline = cy - v.height + 1 + scrollmargin
297 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
298 v.Topline = v.Buf.NumLines - v.height
302 cx := v.Cursor.GetVisualX()
307 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
308 v.leftCol = cx - v.width + v.lineNumOffset + 1
314 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
316 func (v *View) MoveToMouseClick(x, y int) {
317 if y-v.Topline > v.height-1 {
319 y = v.height + v.Topline - 1
321 if y >= v.Buf.NumLines {
322 y = v.Buf.NumLines - 1
331 x = v.Cursor.GetCharPosInLine(y, x)
332 if x > Count(v.Buf.Line(y)) {
333 x = Count(v.Buf.Line(y))
337 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
340 // HandleEvent handles an event passed by the main loop
341 func (v *View) HandleEvent(event tcell.Event) {
342 // This bool determines whether the view is relocated at the end of the function
343 // By default it's true because most events should cause a relocate
348 switch e := event.(type) {
349 case *tcell.EventResize:
351 tabs[v.TabNum].Resize()
352 case *tcell.EventKey:
353 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
355 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
356 for key, actions := range bindings {
357 if e.Key() == key.keyCode {
358 if e.Key() == tcell.KeyRune {
359 if e.Rune() != key.r {
363 if e.Modifiers() == key.modifiers {
366 for _, action := range actions {
367 relocate = action(v, true) || relocate
368 funcName := FuncName(action)
369 if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
371 curMacro = append(curMacro, action)
380 if !isBinding && e.Key() == tcell.KeyRune {
381 // Insert a character
382 if v.Cursor.HasSelection() {
383 v.Cursor.DeleteSelection()
384 v.Cursor.ResetSelection()
386 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
389 for _, pl := range loadedPlugins {
390 _, err := Call(pl+".onRune", string(e.Rune()), v)
391 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
397 curMacro = append(curMacro, e.Rune())
400 case *tcell.EventPaste:
401 if !PreActionCall("Paste", v) {
405 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
407 if v.Cursor.HasSelection() {
408 v.Cursor.DeleteSelection()
409 v.Cursor.ResetSelection()
412 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
413 v.Buf.Insert(v.Cursor.Loc, clip)
414 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
416 messenger.Message("Pasted clipboard")
418 PostActionCall("Paste", v)
419 case *tcell.EventMouse:
421 x -= v.lineNumOffset - v.leftCol + v.x
423 // Don't relocate for mouse events
426 button := e.Buttons()
432 v.MoveToMouseClick(x, y)
433 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
436 v.lastClickTime = time.Now()
439 v.doubleClick = false
441 v.Cursor.SelectLine()
444 v.lastClickTime = time.Now()
447 v.tripleClick = false
449 v.Cursor.SelectWord()
452 v.doubleClick = false
453 v.tripleClick = false
454 v.lastClickTime = time.Now()
456 v.Cursor.OrigSelection[0] = v.Cursor.Loc
457 v.Cursor.CurSelection[0] = v.Cursor.Loc
458 v.Cursor.CurSelection[1] = v.Cursor.Loc
460 v.mouseReleased = false
461 } else if !v.mouseReleased {
462 v.MoveToMouseClick(x, y)
464 v.Cursor.AddLineToSelection()
465 } else if v.doubleClick {
466 v.Cursor.AddWordToSelection()
468 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
472 // Middle mouse button was clicked,
473 // We should paste primary
475 case tcell.ButtonNone:
476 // Mouse event with no click
477 if !v.mouseReleased {
478 // Mouse was just released
480 // Relocating here isn't really necessary because the cursor will
481 // be in the right place from the last mouse event
482 // However, if we are running in a terminal that doesn't support mouse motion
483 // events, this still allows the user to make selections, except only after they
486 if !v.doubleClick && !v.tripleClick {
487 v.MoveToMouseClick(x, y)
488 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
490 v.mouseReleased = true
494 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
495 v.ScrollUp(scrollspeed)
496 case tcell.WheelDown:
498 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
499 v.ScrollDown(scrollspeed)
508 // GutterMessage creates a message in this view's gutter
509 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
511 gutterMsg := GutterMessage{
516 for _, v := range v.messages {
517 for _, gmsg := range v {
518 if gmsg.lineNum == lineN {
523 messages := v.messages[section]
524 v.messages[section] = append(messages, gutterMsg)
527 // ClearGutterMessages clears all gutter messages from a given section
528 func (v *View) ClearGutterMessages(section string) {
529 v.messages[section] = []GutterMessage{}
532 // ClearAllGutterMessages clears all the gutter messages
533 func (v *View) ClearAllGutterMessages() {
534 for k := range v.messages {
535 v.messages[k] = []GutterMessage{}
539 // Opens the given help page in a new horizontal split
540 func (v *View) openHelp(helpPage string) {
541 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
542 TermMessage("Unable to load help text", helpPage, "\n", err)
544 helpBuffer := NewBuffer(data, helpPage+".md")
545 helpBuffer.Name = "Help"
547 if v.Type == vtHelp {
548 v.OpenBuffer(helpBuffer)
551 CurView().Type = vtHelp
556 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
557 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
558 screen.SetContent(x, y, ch, combc, style)
562 // DisplayView renders the view to the screen
563 func (v *View) DisplayView() {
565 // Log views should always follow the cursor...
569 if v.Buf.Settings["syntax"].(bool) {
573 // The charNum we are currently displaying
574 // starts at the start of the viewport
575 charNum := Loc{0, v.Topline}
577 // Convert the length of buffer to a string, and get the length of the string
578 // We are going to have to offset by that amount
579 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
581 if v.Buf.Settings["ruler"] == true {
582 // + 1 for the little space after the line number
583 v.lineNumOffset = maxLineLength + 1
588 // We need to add to the line offset if there are gutter messages
589 var hasGutterMessages bool
590 for _, v := range v.messages {
592 hasGutterMessages = true
595 if hasGutterMessages {
600 // One space for the extra split divider
604 // These represent the current screen coordinates
605 screenX, screenY := 0, 0
607 highlightStyle := defStyle
609 // ViewLine is the current line from the top of the viewport
610 for viewLine := 0; viewLine < v.height; viewLine++ {
611 screenY = v.y + viewLine
614 // This is the current line number of the buffer that we are drawing
615 curLineN := viewLine + v.Topline
618 // Draw the split divider
619 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
623 // If the buffer is smaller than the view height we have to clear all this space
624 if curLineN >= v.Buf.NumLines {
625 for i := screenX; i < v.x+v.width; i++ {
626 v.drawCell(i, screenY, ' ', nil, defStyle)
631 line := v.Buf.Line(curLineN)
633 // If there are gutter messages we need to display the '>>' symbol here
634 if hasGutterMessages {
635 // msgOnLine stores whether or not there is a gutter message on this line in particular
637 for k := range v.messages {
638 for _, msg := range v.messages[k] {
639 if msg.lineNum == curLineN {
641 gutterStyle := defStyle
644 if style, ok := colorscheme["gutter-info"]; ok {
648 if style, ok := colorscheme["gutter-warning"]; ok {
652 if style, ok := colorscheme["gutter-error"]; ok {
656 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
658 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
660 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
661 messenger.Message(msg.msg)
662 messenger.gutterMessage = true
667 // If there is no message on this line we just display an empty offset
669 v.drawCell(screenX, screenY, ' ', nil, defStyle)
671 v.drawCell(screenX, screenY, ' ', nil, defStyle)
673 if v.Cursor.Y == curLineN && messenger.gutterMessage {
675 messenger.gutterMessage = false
680 if v.Buf.Settings["ruler"] == true {
681 // Write the line number
682 lineNumStyle := defStyle
683 if style, ok := colorscheme["line-number"]; ok {
686 if style, ok := colorscheme["current-line-number"]; ok {
687 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
692 lineNum := strconv.Itoa(curLineN + 1)
694 // Write the spaces before the line number if necessary
695 for i := 0; i < maxLineLength-len(lineNum); i++ {
696 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
699 // Write the actual line number
700 for _, ch := range lineNum {
701 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
705 // Write the extra space
706 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
710 // Now we actually draw the line
712 for _, ch := range line {
713 lineStyle := defStyle
715 if v.Buf.Settings["syntax"].(bool) {
716 // Syntax highlighting is enabled
717 highlightStyle = v.matches[viewLine][colN]
720 if v.Cursor.HasSelection() &&
721 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
722 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
723 // The current character is selected
724 lineStyle = defStyle.Reverse(true)
726 if style, ok := colorscheme["selection"]; ok {
730 lineStyle = highlightStyle
733 // We need to display the background of the linestyle with the correct color if cursorline is enabled
734 // and this is the current view and there is no selection on this line and the cursor is on this line
735 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
736 if style, ok := colorscheme["cursor-line"]; ok {
737 fg, _, _ := style.Decompose()
738 lineStyle = lineStyle.Background(fg)
743 // If the character we are displaying is a tab, we need to do a bunch of special things
745 // First the user may have configured an `indent-char` to be displayed to show that this
746 // is a tab character
747 lineIndentStyle := defStyle
748 if style, ok := colorscheme["indent-char"]; ok {
749 lineIndentStyle = style
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])) {
755 lineIndentStyle = defStyle.Reverse(true)
757 if style, ok := colorscheme["selection"]; ok {
758 lineIndentStyle = style
761 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
762 if style, ok := colorscheme["cursor-line"]; ok {
763 fg, _, _ := style.Decompose()
764 lineIndentStyle = lineIndentStyle.Background(fg)
767 // Here we get the indent char
768 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
769 if screenX-v.x-v.leftCol >= v.lineNumOffset {
770 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
772 // Now the tab has to be displayed as a bunch of spaces
773 tabSize := int(v.Buf.Settings["tabsize"].(float64))
774 for i := 0; i < tabSize-1; i++ {
776 if screenX-v.x-v.leftCol >= v.lineNumOffset {
777 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
780 } else if runewidth.RuneWidth(ch) > 1 {
781 if screenX-v.x-v.leftCol >= v.lineNumOffset {
782 v.drawCell(screenX, screenY, ch, nil, lineStyle)
784 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
786 if screenX-v.x-v.leftCol >= v.lineNumOffset {
787 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
791 if screenX-v.x-v.leftCol >= v.lineNumOffset {
792 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
795 charNum = charNum.Move(1, v.Buf)
799 // Here we are at a newline
801 // The newline may be selected, in which case we should draw the selection style
802 // with a space to represent it
803 if v.Cursor.HasSelection() &&
804 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
805 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
807 selectStyle := defStyle.Reverse(true)
809 if style, ok := colorscheme["selection"]; ok {
812 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
816 charNum = charNum.Move(1, v.Buf)
818 for i := 0; i < v.width; i++ {
819 lineStyle := defStyle
820 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
821 if style, ok := colorscheme["cursor-line"]; ok {
822 fg, _, _ := style.Decompose()
823 lineStyle = lineStyle.Background(fg)
826 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
827 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
828 if colorcolumn != 0 && screenX-v.leftCol+i == colorcolumn-1 {
829 if style, ok := colorscheme["color-column"]; ok {
830 fg, _, _ := style.Decompose()
831 lineStyle = lineStyle.Background(fg)
833 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
835 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
842 // DisplayCursor draws the current buffer's cursor to the screen
843 func (v *View) DisplayCursor() {
844 // Don't draw the cursor if it is out of the viewport or if it has a selection
845 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
848 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
852 // Display renders the view, the cursor, and statusline
853 func (v *View) Display() {
855 if v.Num == tabs[curTab].curView {
858 _, screenH := screen.Size()
859 if v.Buf.Settings["statusline"].(bool) {
861 } else if (v.y + v.height) != screenH-1 {
862 for x := 0; x < v.width; x++ {
863 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))