9 "github.com/mattn/go-runewidth"
10 "github.com/mitchellh/go-homedir"
11 "github.com/zyedidia/tcell"
14 // The View struct stores information about a view into a buffer.
15 // It stores information about the cursor, and the viewport
16 // that the user sees the buffer from.
18 // A pointer to the buffer's cursor for ease of access
21 // The topmost line, used for vertical scrolling
23 // The leftmost column, used for horizontal scrolling
26 // Percentage of the terminal window that this view takes up (from 0 to 100)
30 // Specifies whether or not this view holds a help buffer
33 // Actual with and height
37 // Where this view is located
40 // How much to offset because of line numbers
43 // Holds the list of gutter messages
44 messages map[string][]GutterMessage
46 // This is the index of this view in the views array
48 // What tab is this view stored in
56 // Since tcell doesn't differentiate between a mouse release event
57 // and a mouse move event with no keys pressed, we need to keep
58 // track of whether or not the mouse was pressed (or not released) last event to determine
59 // mouse release events
62 // This stores when the last click was
63 // This is useful for detecting double and triple clicks
64 lastClickTime time.Time
66 // lastCutTime stores when the last ctrl+k was issued.
67 // It is used for clearing the clipboard to replace it with fresh cut lines.
70 // freshClip returns true if the clipboard has never been pasted.
73 // Was the last mouse event actually a double click?
74 // Useful for detecting triple clicks -- if a double click is detected
75 // but the last mouse event was actually a double click, it's a triple click
77 // Same here, just to keep track for mouse move events
80 // Syntax highlighting matches
86 // NewView returns a new fullscreen view
87 func NewView(buf *Buffer) *View {
88 screenW, screenH := screen.Size()
89 return NewViewWidthHeight(buf, screenW, screenH)
92 // NewViewWidthHeight returns a new view with the specified width and height
93 // Note that w and h are raw column and row values
94 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
106 v.messages = make(map[string][]GutterMessage)
108 v.sline = Statusline{
112 if v.Buf.Settings["statusline"].(bool) {
116 for _, pl := range loadedPlugins {
117 _, err := Call(pl+".onViewOpen", v)
118 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
127 func (v *View) ToggleStatusLine() {
128 if v.Buf.Settings["statusline"].(bool) {
135 func (v *View) ToggleTabbar() {
138 // Include one line for the tab bar at the top
150 func (v *View) paste(clip string) {
151 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
153 if v.Cursor.HasSelection() {
154 v.Cursor.DeleteSelection()
155 v.Cursor.ResetSelection()
157 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
158 v.Buf.Insert(v.Cursor.Loc, clip)
159 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
161 messenger.Message("Pasted clipboard")
164 // ScrollUp scrolls the view up n lines (if possible)
165 func (v *View) ScrollUp(n int) {
166 // Try to scroll by n but if it would overflow, scroll by 1
167 if v.Topline-n >= 0 {
169 } else if v.Topline > 0 {
174 // ScrollDown scrolls the view down n lines (if possible)
175 func (v *View) ScrollDown(n int) {
176 // Try to scroll by n but if it would overflow, scroll by 1
177 if v.Topline+n <= v.Buf.NumLines-v.height {
179 } else if v.Topline < v.Buf.NumLines-v.height {
184 // CanClose returns whether or not the view can be closed
185 // If there are unsaved changes, the user will be asked if the view can be closed
186 // causing them to lose the unsaved changes
187 func (v *View) CanClose() bool {
188 if v.Buf.IsModified {
189 char, canceled := messenger.LetterPrompt("Save changes to "+v.Buf.Name+" before closing? (y,n,esc) ", 'y', 'n')
194 } else if char == 'n' {
204 // OpenBuffer opens a new buffer in this view.
205 // This resets the topline, event handler and cursor.
206 func (v *View) OpenBuffer(buf *Buffer) {
210 v.Cursor = &buf.Cursor
213 v.Cursor.ResetSelection()
216 v.messages = make(map[string][]GutterMessage)
220 // Set mouseReleased to true because we assume the mouse is not being pressed when
221 // the editor is opened
222 v.mouseReleased = true
223 v.lastClickTime = time.Time{}
226 func (v *View) Open(filename string) {
227 home, _ := homedir.Dir()
228 filename = strings.Replace(filename, "~", home, 1)
229 file, err := ioutil.ReadFile(filename)
233 messenger.Message(err.Error())
234 // File does not exist -- create an empty buffer with that name
235 buf = NewBuffer([]byte{}, filename)
237 buf = NewBuffer(file, filename)
242 // CloseBuffer performs any closing functions on the buffer
243 func (v *View) CloseBuffer() {
249 // ReOpen reloads the current buffer
250 func (v *View) ReOpen() {
259 // HSplit opens a horizontal split with the given buffer
260 func (v *View) HSplit(buf *Buffer) bool {
261 v.splitNode.HSplit(buf)
262 tabs[v.TabNum].Resize()
266 // VSplit opens a vertical split with the given buffer
267 func (v *View) VSplit(buf *Buffer) bool {
268 v.splitNode.VSplit(buf)
269 tabs[v.TabNum].Resize()
273 // Relocate moves the view window so that the cursor is in view
274 // This is useful if the user has scrolled far away, and then starts typing
275 func (v *View) Relocate() bool {
278 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
279 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
280 v.Topline = cy - scrollmargin
282 } else if cy < v.Topline {
286 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
287 v.Topline = cy - v.height + 1 + scrollmargin
289 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
290 v.Topline = v.Buf.NumLines - v.height
294 cx := v.Cursor.GetVisualX()
299 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
300 v.leftCol = cx - v.width + v.lineNumOffset + 1
306 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
308 func (v *View) MoveToMouseClick(x, y int) {
309 if y-v.Topline > v.height-1 {
311 y = v.height + v.Topline - 1
313 if y >= v.Buf.NumLines {
314 y = v.Buf.NumLines - 1
323 x = v.Cursor.GetCharPosInLine(y, x)
324 if x > Count(v.Buf.Line(y)) {
325 x = Count(v.Buf.Line(y))
329 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
332 // HandleEvent handles an event passed by the main loop
333 func (v *View) HandleEvent(event tcell.Event) {
334 // This bool determines whether the view is relocated at the end of the function
335 // By default it's true because most events should cause a relocate
340 switch e := event.(type) {
341 case *tcell.EventResize:
343 tabs[v.TabNum].Resize()
344 case *tcell.EventKey:
345 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
347 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
348 for key, actions := range bindings {
349 if e.Key() == key.keyCode {
350 if e.Key() == tcell.KeyRune {
351 if e.Rune() != key.r {
355 if e.Modifiers() == key.modifiers {
358 for _, action := range actions {
359 relocate = action(v, true) || relocate
360 funcName := FuncName(action)
361 if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
363 curMacro = append(curMacro, action)
371 if !isBinding && e.Key() == tcell.KeyRune {
372 // Insert a character
373 if v.Cursor.HasSelection() {
374 v.Cursor.DeleteSelection()
375 v.Cursor.ResetSelection()
377 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
380 for _, pl := range loadedPlugins {
381 _, err := Call(pl+".onRune", string(e.Rune()), v)
382 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
388 curMacro = append(curMacro, e.Rune())
391 case *tcell.EventPaste:
392 if !PreActionCall("Paste", v) {
396 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
398 if v.Cursor.HasSelection() {
399 v.Cursor.DeleteSelection()
400 v.Cursor.ResetSelection()
403 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
404 v.Buf.Insert(v.Cursor.Loc, clip)
405 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
407 messenger.Message("Pasted clipboard")
409 PostActionCall("Paste", v)
410 case *tcell.EventMouse:
412 x -= v.lineNumOffset - v.leftCol + v.x
414 // Don't relocate for mouse events
417 button := e.Buttons()
423 v.MoveToMouseClick(x, y)
424 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
427 v.lastClickTime = time.Now()
430 v.doubleClick = false
432 v.Cursor.SelectLine()
435 v.lastClickTime = time.Now()
438 v.tripleClick = false
440 v.Cursor.SelectWord()
443 v.doubleClick = false
444 v.tripleClick = false
445 v.lastClickTime = time.Now()
447 v.Cursor.OrigSelection[0] = v.Cursor.Loc
448 v.Cursor.CurSelection[0] = v.Cursor.Loc
449 v.Cursor.CurSelection[1] = v.Cursor.Loc
451 v.mouseReleased = false
452 } else if !v.mouseReleased {
453 v.MoveToMouseClick(x, y)
455 v.Cursor.AddLineToSelection()
456 } else if v.doubleClick {
457 v.Cursor.AddWordToSelection()
459 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
463 // Middle mouse button was clicked,
464 // We should paste primary
466 case tcell.ButtonNone:
467 // Mouse event with no click
468 if !v.mouseReleased {
469 // Mouse was just released
471 // Relocating here isn't really necessary because the cursor will
472 // be in the right place from the last mouse event
473 // However, if we are running in a terminal that doesn't support mouse motion
474 // events, this still allows the user to make selections, except only after they
477 if !v.doubleClick && !v.tripleClick {
478 v.MoveToMouseClick(x, y)
479 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
481 v.mouseReleased = true
485 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
486 v.ScrollUp(scrollspeed)
487 case tcell.WheelDown:
489 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
490 v.ScrollDown(scrollspeed)
497 if v.Buf.Settings["syntax"].(bool) {
502 // GutterMessage creates a message in this view's gutter
503 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
505 gutterMsg := GutterMessage{
510 for _, v := range v.messages {
511 for _, gmsg := range v {
512 if gmsg.lineNum == lineN {
517 messages := v.messages[section]
518 v.messages[section] = append(messages, gutterMsg)
521 // ClearGutterMessages clears all gutter messages from a given section
522 func (v *View) ClearGutterMessages(section string) {
523 v.messages[section] = []GutterMessage{}
526 // ClearAllGutterMessages clears all the gutter messages
527 func (v *View) ClearAllGutterMessages() {
528 for k := range v.messages {
529 v.messages[k] = []GutterMessage{}
533 // Opens the given help page in a new horizontal split
534 func (v *View) openHelp(helpPage string) {
536 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
537 helpBuffer.Name = "Help"
538 v.OpenBuffer(helpBuffer)
540 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
541 helpBuffer.Name = "Help"
543 CurView().Help = true
547 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
548 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
549 screen.SetContent(x, y, ch, combc, style)
553 // DisplayView renders the view to the screen
554 func (v *View) DisplayView() {
555 // The charNum we are currently displaying
556 // starts at the start of the viewport
557 charNum := Loc{0, v.Topline}
559 // Convert the length of buffer to a string, and get the length of the string
560 // We are going to have to offset by that amount
561 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
563 if v.Buf.Settings["ruler"] == true {
564 // + 1 for the little space after the line number
565 v.lineNumOffset = maxLineLength + 1
570 // We need to add to the line offset if there are gutter messages
571 var hasGutterMessages bool
572 for _, v := range v.messages {
574 hasGutterMessages = true
577 if hasGutterMessages {
582 // One space for the extra split divider
586 // These represent the current screen coordinates
587 screenX, screenY := 0, 0
589 highlightStyle := defStyle
591 // ViewLine is the current line from the top of the viewport
592 for viewLine := 0; viewLine < v.height; viewLine++ {
593 screenY = v.y + viewLine
596 // This is the current line number of the buffer that we are drawing
597 curLineN := viewLine + v.Topline
600 // Draw the split divider
601 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
605 // If the buffer is smaller than the view height we have to clear all this space
606 if curLineN >= v.Buf.NumLines {
607 for i := screenX; i < v.x+v.width; i++ {
608 v.drawCell(i, screenY, ' ', nil, defStyle)
613 line := v.Buf.Line(curLineN)
615 // If there are gutter messages we need to display the '>>' symbol here
616 if hasGutterMessages {
617 // msgOnLine stores whether or not there is a gutter message on this line in particular
619 for k := range v.messages {
620 for _, msg := range v.messages[k] {
621 if msg.lineNum == curLineN {
623 gutterStyle := defStyle
626 if style, ok := colorscheme["gutter-info"]; ok {
630 if style, ok := colorscheme["gutter-warning"]; ok {
634 if style, ok := colorscheme["gutter-error"]; ok {
638 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
640 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
642 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
643 messenger.Message(msg.msg)
644 messenger.gutterMessage = true
649 // If there is no message on this line we just display an empty offset
651 v.drawCell(screenX, screenY, ' ', nil, defStyle)
653 v.drawCell(screenX, screenY, ' ', nil, defStyle)
655 if v.Cursor.Y == curLineN && messenger.gutterMessage {
657 messenger.gutterMessage = false
662 if v.Buf.Settings["ruler"] == true {
663 // Write the line number
664 lineNumStyle := defStyle
665 if style, ok := colorscheme["line-number"]; ok {
668 if style, ok := colorscheme["current-line-number"]; ok {
669 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
674 lineNum := strconv.Itoa(curLineN + 1)
676 // Write the spaces before the line number if necessary
677 for i := 0; i < maxLineLength-len(lineNum); i++ {
678 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
681 // Write the actual line number
682 for _, ch := range lineNum {
683 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
687 // Write the extra space
688 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
692 // Now we actually draw the line
694 for _, ch := range line {
695 lineStyle := defStyle
697 if v.Buf.Settings["syntax"].(bool) {
698 // Syntax highlighting is enabled
699 highlightStyle = v.matches[viewLine][colN]
702 if v.Cursor.HasSelection() &&
703 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
704 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
705 // The current character is selected
706 lineStyle = defStyle.Reverse(true)
708 if style, ok := colorscheme["selection"]; ok {
712 lineStyle = highlightStyle
715 // We need to display the background of the linestyle with the correct color if cursorline is enabled
716 // and this is the current view and there is no selection on this line and the cursor is on this line
717 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
718 if style, ok := colorscheme["cursor-line"]; ok {
719 fg, _, _ := style.Decompose()
720 lineStyle = lineStyle.Background(fg)
725 // If the character we are displaying is a tab, we need to do a bunch of special things
727 // First the user may have configured an `indent-char` to be displayed to show that this
728 // is a tab character
729 lineIndentStyle := defStyle
730 if style, ok := colorscheme["indent-char"]; ok {
731 lineIndentStyle = style
733 if v.Cursor.HasSelection() &&
734 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
735 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
737 lineIndentStyle = defStyle.Reverse(true)
739 if style, ok := colorscheme["selection"]; ok {
740 lineIndentStyle = style
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 lineIndentStyle = lineIndentStyle.Background(fg)
749 // Here we get the indent char
750 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
751 if screenX-v.x-v.leftCol >= v.lineNumOffset {
752 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
754 // Now the tab has to be displayed as a bunch of spaces
755 tabSize := int(v.Buf.Settings["tabsize"].(float64))
756 for i := 0; i < tabSize-1; i++ {
758 if screenX-v.x-v.leftCol >= v.lineNumOffset {
759 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
762 } else if runewidth.RuneWidth(ch) > 1 {
763 if screenX-v.x-v.leftCol >= v.lineNumOffset {
764 v.drawCell(screenX, screenY, ch, nil, lineStyle)
766 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
768 if screenX-v.x-v.leftCol >= v.lineNumOffset {
769 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
773 if screenX-v.x-v.leftCol >= v.lineNumOffset {
774 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
777 charNum = charNum.Move(1, v.Buf)
781 // Here we are at a newline
783 // The newline may be selected, in which case we should draw the selection style
784 // with a space to represent it
785 if v.Cursor.HasSelection() &&
786 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
787 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
789 selectStyle := defStyle.Reverse(true)
791 if style, ok := colorscheme["selection"]; ok {
794 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
798 charNum = charNum.Move(1, v.Buf)
800 for i := 0; i < v.width; i++ {
801 lineStyle := defStyle
802 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
803 if style, ok := colorscheme["cursor-line"]; ok {
804 fg, _, _ := style.Decompose()
805 lineStyle = lineStyle.Background(fg)
808 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
809 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
810 if colorcolumn != 0 && screenX-v.leftCol+i == colorcolumn-1 {
811 if style, ok := colorscheme["color-column"]; ok {
812 fg, _, _ := style.Decompose()
813 lineStyle = lineStyle.Background(fg)
815 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
817 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
824 // DisplayCursor draws the current buffer's cursor to the screen
825 func (v *View) DisplayCursor() {
826 // Don't draw the cursor if it is out of the viewport or if it has a selection
827 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
830 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
834 // Display renders the view, the cursor, and statusline
835 func (v *View) Display() {
837 if v.Num == tabs[curTab].curView {
840 _, screenH := screen.Size()
841 if v.Buf.Settings["statusline"].(bool) {
843 } else if (v.y + v.height) != screenH-1 {
844 for x := 0; x < v.width; x++ {
845 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))