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)
499 // GutterMessage creates a message in this view's gutter
500 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
502 gutterMsg := GutterMessage{
507 for _, v := range v.messages {
508 for _, gmsg := range v {
509 if gmsg.lineNum == lineN {
514 messages := v.messages[section]
515 v.messages[section] = append(messages, gutterMsg)
518 // ClearGutterMessages clears all gutter messages from a given section
519 func (v *View) ClearGutterMessages(section string) {
520 v.messages[section] = []GutterMessage{}
523 // ClearAllGutterMessages clears all the gutter messages
524 func (v *View) ClearAllGutterMessages() {
525 for k := range v.messages {
526 v.messages[k] = []GutterMessage{}
530 // Opens the given help page in a new horizontal split
531 func (v *View) openHelp(helpPage string) {
532 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
533 TermMessage("Unable to load help text", helpPage, "\n", err)
535 helpBuffer := NewBuffer(data, helpPage+".md")
536 helpBuffer.Name = "Help"
539 v.OpenBuffer(helpBuffer)
542 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 if v.Buf.Settings["syntax"].(bool) {
558 // The charNum we are currently displaying
559 // starts at the start of the viewport
560 charNum := Loc{0, v.Topline}
562 // Convert the length of buffer to a string, and get the length of the string
563 // We are going to have to offset by that amount
564 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
566 if v.Buf.Settings["ruler"] == true {
567 // + 1 for the little space after the line number
568 v.lineNumOffset = maxLineLength + 1
573 // We need to add to the line offset if there are gutter messages
574 var hasGutterMessages bool
575 for _, v := range v.messages {
577 hasGutterMessages = true
580 if hasGutterMessages {
585 // One space for the extra split divider
589 // These represent the current screen coordinates
590 screenX, screenY := 0, 0
592 highlightStyle := defStyle
594 // ViewLine is the current line from the top of the viewport
595 for viewLine := 0; viewLine < v.height; viewLine++ {
596 screenY = v.y + viewLine
599 // This is the current line number of the buffer that we are drawing
600 curLineN := viewLine + v.Topline
603 // Draw the split divider
604 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
608 // If the buffer is smaller than the view height we have to clear all this space
609 if curLineN >= v.Buf.NumLines {
610 for i := screenX; i < v.x+v.width; i++ {
611 v.drawCell(i, screenY, ' ', nil, defStyle)
616 line := v.Buf.Line(curLineN)
618 // If there are gutter messages we need to display the '>>' symbol here
619 if hasGutterMessages {
620 // msgOnLine stores whether or not there is a gutter message on this line in particular
622 for k := range v.messages {
623 for _, msg := range v.messages[k] {
624 if msg.lineNum == curLineN {
626 gutterStyle := defStyle
629 if style, ok := colorscheme["gutter-info"]; ok {
633 if style, ok := colorscheme["gutter-warning"]; ok {
637 if style, ok := colorscheme["gutter-error"]; ok {
641 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
643 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
645 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
646 messenger.Message(msg.msg)
647 messenger.gutterMessage = true
652 // If there is no message on this line we just display an empty offset
654 v.drawCell(screenX, screenY, ' ', nil, defStyle)
656 v.drawCell(screenX, screenY, ' ', nil, defStyle)
658 if v.Cursor.Y == curLineN && messenger.gutterMessage {
660 messenger.gutterMessage = false
665 if v.Buf.Settings["ruler"] == true {
666 // Write the line number
667 lineNumStyle := defStyle
668 if style, ok := colorscheme["line-number"]; ok {
671 if style, ok := colorscheme["current-line-number"]; ok {
672 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
677 lineNum := strconv.Itoa(curLineN + 1)
679 // Write the spaces before the line number if necessary
680 for i := 0; i < maxLineLength-len(lineNum); i++ {
681 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
684 // Write the actual line number
685 for _, ch := range lineNum {
686 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
690 // Write the extra space
691 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
695 // Now we actually draw the line
697 for _, ch := range line {
698 lineStyle := defStyle
700 if v.Buf.Settings["syntax"].(bool) {
701 // Syntax highlighting is enabled
702 highlightStyle = v.matches[viewLine][colN]
705 if v.Cursor.HasSelection() &&
706 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
707 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
708 // The current character is selected
709 lineStyle = defStyle.Reverse(true)
711 if style, ok := colorscheme["selection"]; ok {
715 lineStyle = highlightStyle
718 // We need to display the background of the linestyle with the correct color if cursorline is enabled
719 // and this is the current view and there is no selection on this line and the cursor is on this line
720 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
721 if style, ok := colorscheme["cursor-line"]; ok {
722 fg, _, _ := style.Decompose()
723 lineStyle = lineStyle.Background(fg)
728 // If the character we are displaying is a tab, we need to do a bunch of special things
730 // First the user may have configured an `indent-char` to be displayed to show that this
731 // is a tab character
732 lineIndentStyle := defStyle
733 if style, ok := colorscheme["indent-char"]; ok {
734 lineIndentStyle = style
736 if v.Cursor.HasSelection() &&
737 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
738 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
740 lineIndentStyle = defStyle.Reverse(true)
742 if style, ok := colorscheme["selection"]; ok {
743 lineIndentStyle = style
746 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
747 if style, ok := colorscheme["cursor-line"]; ok {
748 fg, _, _ := style.Decompose()
749 lineIndentStyle = lineIndentStyle.Background(fg)
752 // Here we get the indent char
753 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
754 if screenX-v.x-v.leftCol >= v.lineNumOffset {
755 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
757 // Now the tab has to be displayed as a bunch of spaces
758 tabSize := int(v.Buf.Settings["tabsize"].(float64))
759 for i := 0; i < tabSize-1; i++ {
761 if screenX-v.x-v.leftCol >= v.lineNumOffset {
762 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
765 } else if runewidth.RuneWidth(ch) > 1 {
766 if screenX-v.x-v.leftCol >= v.lineNumOffset {
767 v.drawCell(screenX, screenY, ch, nil, lineStyle)
769 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
771 if screenX-v.x-v.leftCol >= v.lineNumOffset {
772 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
776 if screenX-v.x-v.leftCol >= v.lineNumOffset {
777 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
780 charNum = charNum.Move(1, v.Buf)
784 // Here we are at a newline
786 // The newline may be selected, in which case we should draw the selection style
787 // with a space to represent it
788 if v.Cursor.HasSelection() &&
789 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
790 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
792 selectStyle := defStyle.Reverse(true)
794 if style, ok := colorscheme["selection"]; ok {
797 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
801 charNum = charNum.Move(1, v.Buf)
803 for i := 0; i < v.width; i++ {
804 lineStyle := defStyle
805 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
806 if style, ok := colorscheme["cursor-line"]; ok {
807 fg, _, _ := style.Decompose()
808 lineStyle = lineStyle.Background(fg)
811 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
812 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
813 if colorcolumn != 0 && screenX-v.leftCol+i == colorcolumn-1 {
814 if style, ok := colorscheme["color-column"]; ok {
815 fg, _, _ := style.Decompose()
816 lineStyle = lineStyle.Background(fg)
818 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
820 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
827 // DisplayCursor draws the current buffer's cursor to the screen
828 func (v *View) DisplayCursor() {
829 // Don't draw the cursor if it is out of the viewport or if it has a selection
830 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
833 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
837 // Display renders the view, the cursor, and statusline
838 func (v *View) Display() {
840 if v.Num == tabs[curTab].curView {
843 _, screenH := screen.Size()
844 if v.Buf.Settings["statusline"].(bool) {
846 } else if (v.y + v.height) != screenH-1 {
847 for x := 0; x < v.width; x++ {
848 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))