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 width 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 {
199 if v.Buf.Settings["autosave"].(bool) {
202 char, canceled = messenger.LetterPrompt("Save changes to "+v.Buf.Name+" before closing? (y,n,esc) ", 'y', 'n')
208 } else if char == 'n' {
218 // OpenBuffer opens a new buffer in this view.
219 // This resets the topline, event handler and cursor.
220 func (v *View) OpenBuffer(buf *Buffer) {
224 v.Cursor = &buf.Cursor
227 v.Cursor.ResetSelection()
230 v.messages = make(map[string][]GutterMessage)
234 // Set mouseReleased to true because we assume the mouse is not being pressed when
235 // the editor is opened
236 v.mouseReleased = true
237 v.lastClickTime = time.Time{}
240 func (v *View) Open(filename string) {
241 home, _ := homedir.Dir()
242 filename = strings.Replace(filename, "~", home, 1)
243 file, err := ioutil.ReadFile(filename)
247 messenger.Message(err.Error())
248 // File does not exist -- create an empty buffer with that name
249 buf = NewBuffer([]byte{}, filename)
251 buf = NewBuffer(file, filename)
256 // CloseBuffer performs any closing functions on the buffer
257 func (v *View) CloseBuffer() {
263 // ReOpen reloads the current buffer
264 func (v *View) ReOpen() {
273 // HSplit opens a horizontal split with the given buffer
274 func (v *View) HSplit(buf *Buffer) bool {
275 v.splitNode.HSplit(buf)
276 tabs[v.TabNum].Resize()
280 // VSplit opens a vertical split with the given buffer
281 func (v *View) VSplit(buf *Buffer) bool {
282 v.splitNode.VSplit(buf)
283 tabs[v.TabNum].Resize()
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(v.Buf.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:
357 tabs[v.TabNum].Resize()
358 case *tcell.EventKey:
359 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
361 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
362 for key, actions := range bindings {
363 if e.Key() == key.keyCode {
364 if e.Key() == tcell.KeyRune {
365 if e.Rune() != key.r {
369 if e.Modifiers() == key.modifiers {
372 for _, action := range actions {
373 relocate = action(v, true) || relocate
374 funcName := FuncName(action)
375 if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
377 curMacro = append(curMacro, action)
386 if !isBinding && e.Key() == tcell.KeyRune {
387 // Insert a character
388 if v.Cursor.HasSelection() {
389 v.Cursor.DeleteSelection()
390 v.Cursor.ResetSelection()
392 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
395 for _, pl := range loadedPlugins {
396 _, err := Call(pl+".onRune", string(e.Rune()), v)
397 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
403 curMacro = append(curMacro, e.Rune())
406 case *tcell.EventPaste:
407 if !PreActionCall("Paste", v) {
411 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
413 if v.Cursor.HasSelection() {
414 v.Cursor.DeleteSelection()
415 v.Cursor.ResetSelection()
418 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
419 v.Buf.Insert(v.Cursor.Loc, clip)
420 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
422 messenger.Message("Pasted clipboard")
424 PostActionCall("Paste", v)
425 case *tcell.EventMouse:
427 x -= v.lineNumOffset - v.leftCol + v.x
429 // Don't relocate for mouse events
432 button := e.Buttons()
438 v.MoveToMouseClick(x, y)
439 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
442 v.lastClickTime = time.Now()
445 v.doubleClick = false
447 v.Cursor.SelectLine()
450 v.lastClickTime = time.Now()
453 v.tripleClick = false
455 v.Cursor.SelectWord()
458 v.doubleClick = false
459 v.tripleClick = false
460 v.lastClickTime = time.Now()
462 v.Cursor.OrigSelection[0] = v.Cursor.Loc
463 v.Cursor.CurSelection[0] = v.Cursor.Loc
464 v.Cursor.CurSelection[1] = v.Cursor.Loc
466 v.mouseReleased = false
467 } else if !v.mouseReleased {
468 v.MoveToMouseClick(x, y)
470 v.Cursor.AddLineToSelection()
471 } else if v.doubleClick {
472 v.Cursor.AddWordToSelection()
474 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
478 // Middle mouse button was clicked,
479 // We should paste primary
481 case tcell.ButtonNone:
482 // Mouse event with no click
483 if !v.mouseReleased {
484 // Mouse was just released
486 // Relocating here isn't really necessary because the cursor will
487 // be in the right place from the last mouse event
488 // However, if we are running in a terminal that doesn't support mouse motion
489 // events, this still allows the user to make selections, except only after they
492 if !v.doubleClick && !v.tripleClick {
493 v.MoveToMouseClick(x, y)
494 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
496 v.mouseReleased = true
500 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
501 v.ScrollUp(scrollspeed)
502 case tcell.WheelDown:
504 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
505 v.ScrollDown(scrollspeed)
514 // GutterMessage creates a message in this view's gutter
515 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
517 gutterMsg := GutterMessage{
522 for _, v := range v.messages {
523 for _, gmsg := range v {
524 if gmsg.lineNum == lineN {
529 messages := v.messages[section]
530 v.messages[section] = append(messages, gutterMsg)
533 // ClearGutterMessages clears all gutter messages from a given section
534 func (v *View) ClearGutterMessages(section string) {
535 v.messages[section] = []GutterMessage{}
538 // ClearAllGutterMessages clears all the gutter messages
539 func (v *View) ClearAllGutterMessages() {
540 for k := range v.messages {
541 v.messages[k] = []GutterMessage{}
545 // Opens the given help page in a new horizontal split
546 func (v *View) openHelp(helpPage string) {
547 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
548 TermMessage("Unable to load help text", helpPage, "\n", err)
550 helpBuffer := NewBuffer(data, helpPage+".md")
551 helpBuffer.Name = "Help"
553 if v.Type == vtHelp {
554 v.OpenBuffer(helpBuffer)
557 CurView().Type = vtHelp
562 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
563 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
564 screen.SetContent(x, y, ch, combc, style)
568 // DisplayView renders the view to the screen
569 func (v *View) DisplayView() {
571 // Log views should always follow the cursor...
575 if v.Buf.Settings["syntax"].(bool) {
579 // The charNum we are currently displaying
580 // starts at the start of the viewport
581 charNum := Loc{0, v.Topline}
583 // Convert the length of buffer to a string, and get the length of the string
584 // We are going to have to offset by that amount
585 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
587 if v.Buf.Settings["ruler"] == true {
588 // + 1 for the little space after the line number
589 v.lineNumOffset = maxLineLength + 1
594 // We need to add to the line offset if there are gutter messages
595 var hasGutterMessages bool
596 for _, v := range v.messages {
598 hasGutterMessages = true
601 if hasGutterMessages {
606 // One space for the extra split divider
610 // These represent the current screen coordinates
611 screenX, screenY := 0, 0
613 highlightStyle := defStyle
615 // ViewLine is the current line from the top of the viewport
616 for viewLine := 0; viewLine < v.height; viewLine++ {
617 screenY = v.y + viewLine
620 // This is the current line number of the buffer that we are drawing
621 curLineN := viewLine + v.Topline
624 // Draw the split divider
625 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
629 // If the buffer is smaller than the view height we have to clear all this space
630 if curLineN >= v.Buf.NumLines {
631 for i := screenX; i < v.x+v.width; i++ {
632 v.drawCell(i, screenY, ' ', nil, defStyle)
637 line := v.Buf.Line(curLineN)
639 // If there are gutter messages we need to display the '>>' symbol here
640 if hasGutterMessages {
641 // msgOnLine stores whether or not there is a gutter message on this line in particular
643 for k := range v.messages {
644 for _, msg := range v.messages[k] {
645 if msg.lineNum == curLineN {
647 gutterStyle := defStyle
650 if style, ok := colorscheme["gutter-info"]; ok {
654 if style, ok := colorscheme["gutter-warning"]; ok {
658 if style, ok := colorscheme["gutter-error"]; ok {
662 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
664 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
666 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
667 messenger.Message(msg.msg)
668 messenger.gutterMessage = true
673 // If there is no message on this line we just display an empty offset
675 v.drawCell(screenX, screenY, ' ', nil, defStyle)
677 v.drawCell(screenX, screenY, ' ', nil, defStyle)
679 if v.Cursor.Y == curLineN && messenger.gutterMessage {
681 messenger.gutterMessage = false
686 if v.Buf.Settings["ruler"] == true {
687 // Write the line number
688 lineNumStyle := defStyle
689 if style, ok := colorscheme["line-number"]; ok {
692 if style, ok := colorscheme["current-line-number"]; ok {
693 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
698 lineNum := strconv.Itoa(curLineN + 1)
700 // Write the spaces before the line number if necessary
701 for i := 0; i < maxLineLength-len(lineNum); i++ {
702 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
705 // Write the actual line number
706 for _, ch := range lineNum {
707 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
711 // Write the extra space
712 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
716 // Now we actually draw the line
719 tabSize := int(v.Buf.Settings["tabsize"].(float64))
720 for _, ch := range line {
721 lineStyle := defStyle
723 if v.Buf.Settings["syntax"].(bool) {
724 // Syntax highlighting is enabled
725 highlightStyle = v.matches[viewLine][colN]
728 if v.Cursor.HasSelection() &&
729 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
730 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
731 // The current character is selected
732 lineStyle = defStyle.Reverse(true)
734 if style, ok := colorscheme["selection"]; ok {
738 lineStyle = highlightStyle
741 // We need to display the background of the linestyle with the correct color if cursorline is enabled
742 // and this is the current view and there is no selection on this line and the cursor is on this line
743 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
744 if style, ok := colorscheme["cursor-line"]; ok {
745 fg, _, _ := style.Decompose()
746 lineStyle = lineStyle.Background(fg)
751 // If the character we are displaying is a tab, we need to do a bunch of special things
753 // First the user may have configured an `indent-char` to be displayed to show that this
754 // is a tab character
755 lineIndentStyle := defStyle
756 if style, ok := colorscheme["indent-char"]; ok && v.Buf.Settings["indentchar"].(string) != " " {
757 lineIndentStyle = style
759 if v.Cursor.HasSelection() &&
760 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
761 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
763 lineIndentStyle = defStyle.Reverse(true)
765 if style, ok := colorscheme["selection"]; ok {
766 lineIndentStyle = style
769 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
770 if style, ok := colorscheme["cursor-line"]; ok {
771 fg, _, _ := style.Decompose()
772 lineIndentStyle = lineIndentStyle.Background(fg)
775 // Here we get the indent char
776 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
777 if screenX-v.x-v.leftCol >= v.lineNumOffset {
778 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
780 // Now the tab has to be displayed as a bunch of spaces
782 remainder := tabSize - (visLoc % tabSize)
783 for i := 0; i < remainder-1; i++ {
785 if screenX-v.x-v.leftCol >= v.lineNumOffset {
786 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
789 } else if runewidth.RuneWidth(ch) > 1 {
790 if screenX-v.x-v.leftCol >= v.lineNumOffset {
791 v.drawCell(screenX, screenY, ch, nil, lineStyle)
793 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
795 if screenX-v.x-v.leftCol >= v.lineNumOffset {
796 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
800 if screenX-v.x-v.leftCol >= v.lineNumOffset {
801 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
804 charNum = charNum.Move(1, v.Buf)
807 strWidth += StringWidth(string(ch), tabSize)
809 // Here we are at a newline
811 // The newline may be selected, in which case we should draw the selection style
812 // with a space to represent it
813 if v.Cursor.HasSelection() &&
814 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
815 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
817 selectStyle := defStyle.Reverse(true)
819 if style, ok := colorscheme["selection"]; ok {
822 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
826 charNum = charNum.Move(1, v.Buf)
828 for i := 0; i < v.width; i++ {
829 lineStyle := defStyle
830 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
831 if style, ok := colorscheme["cursor-line"]; ok {
832 fg, _, _ := style.Decompose()
833 lineStyle = lineStyle.Background(fg)
836 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
837 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
838 if colorcolumn != 0 && screenX-v.lineNumOffset+i == colorcolumn-1 {
839 if style, ok := colorscheme["color-column"]; ok {
840 fg, _, _ := style.Decompose()
841 lineStyle = lineStyle.Background(fg)
844 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
850 // DisplayCursor draws the current buffer's cursor to the screen
851 func (v *View) DisplayCursor() {
852 // Don't draw the cursor if it is out of the viewport or if it has a selection
853 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
856 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
860 // Display renders the view, the cursor, and statusline
861 func (v *View) Display() {
863 if v.Num == tabs[curTab].curView {
866 _, screenH := screen.Size()
867 if v.Buf.Settings["statusline"].(bool) {
869 } else if (v.y + v.height) != screenH-1 {
870 for x := 0; x < v.width; x++ {
871 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))