8 "github.com/mattn/go-runewidth"
9 "github.com/zyedidia/tcell"
12 // The View struct stores information about a view into a buffer.
13 // It stores information about the cursor, and the viewport
14 // that the user sees the buffer from.
16 // A pointer to the buffer's cursor for ease of access
19 // The topmost line, used for vertical scrolling
21 // The leftmost column, used for horizontal scrolling
24 // Percentage of the terminal window that this view takes up (from 0 to 100)
28 // Specifies whether or not this view holds a help buffer
31 // Actual with and height
35 // Where this view is located
38 // How much to offset because of line numbers
41 // Holds the list of gutter messages
42 messages map[string][]GutterMessage
44 // This is the index of this view in the views array
46 // What tab is this view stored in
54 // Since tcell doesn't differentiate between a mouse release event
55 // and a mouse move event with no keys pressed, we need to keep
56 // track of whether or not the mouse was pressed (or not released) last event to determine
57 // mouse release events
60 // This stores when the last click was
61 // This is useful for detecting double and triple clicks
62 lastClickTime time.Time
64 // lastCutTime stores when the last ctrl+k was issued.
65 // It is used for clearing the clipboard to replace it with fresh cut lines.
68 // freshClip returns true if the clipboard has never been pasted.
71 // Was the last mouse event actually a double click?
72 // Useful for detecting triple clicks -- if a double click is detected
73 // but the last mouse event was actually a double click, it's a triple click
75 // Same here, just to keep track for mouse move events
78 // Syntax highlighting matches
84 // NewView returns a new fullscreen view
85 func NewView(buf *Buffer) *View {
86 screenW, screenH := screen.Size()
87 return NewViewWidthHeight(buf, screenW, screenH)
90 // NewViewWidthHeight returns a new view with the specified width and height
91 // Note that w and h are raw column and row values
92 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
104 v.messages = make(map[string][]GutterMessage)
106 v.sline = Statusline{
110 if v.Buf.Settings["statusline"].(bool) {
114 for _, pl := range loadedPlugins {
115 _, err := Call(pl+".onViewOpen", v)
116 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
125 func (v *View) ToggleStatusLine() {
126 if v.Buf.Settings["statusline"].(bool) {
133 func (v *View) ToggleTabbar() {
136 // Include one line for the tab bar at the top
148 func (v *View) paste(clip string) {
149 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
151 if v.Cursor.HasSelection() {
152 v.Cursor.DeleteSelection()
153 v.Cursor.ResetSelection()
155 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
156 v.Buf.Insert(v.Cursor.Loc, clip)
157 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
159 messenger.Message("Pasted clipboard")
162 // ScrollUp scrolls the view up n lines (if possible)
163 func (v *View) ScrollUp(n int) {
164 // Try to scroll by n but if it would overflow, scroll by 1
165 if v.Topline-n >= 0 {
167 } else if v.Topline > 0 {
172 // ScrollDown scrolls the view down n lines (if possible)
173 func (v *View) ScrollDown(n int) {
174 // Try to scroll by n but if it would overflow, scroll by 1
175 if v.Topline+n <= v.Buf.NumLines-v.height {
177 } else if v.Topline < v.Buf.NumLines-v.height {
182 // CanClose returns whether or not the view can be closed
183 // If there are unsaved changes, the user will be asked if the view can be closed
184 // causing them to lose the unsaved changes
185 // The message is what to print after saying "You have unsaved changes. "
186 func (v *View) CanClose(msg string, responses ...rune) bool {
187 if v.Buf.IsModified {
188 char, canceled := messenger.LetterPrompt("You have unsaved changes. "+msg, responses...)
192 } else if char == 's' {
203 // OpenBuffer opens a new buffer in this view.
204 // This resets the topline, event handler and cursor.
205 func (v *View) OpenBuffer(buf *Buffer) {
209 v.Cursor = &buf.Cursor
212 v.Cursor.ResetSelection()
215 v.messages = make(map[string][]GutterMessage)
219 // Set mouseReleased to true because we assume the mouse is not being pressed when
220 // the editor is opened
221 v.mouseReleased = true
222 v.lastClickTime = time.Time{}
225 // CloseBuffer performs any closing functions on the buffer
226 func (v *View) CloseBuffer() {
232 // ReOpen reloads the current buffer
233 func (v *View) ReOpen() {
234 if v.CanClose("Continue? (y,n,s) ", 'y', 'n', 's') {
242 // HSplit opens a horizontal split with the given buffer
243 func (v *View) HSplit(buf *Buffer) bool {
244 v.splitNode.HSplit(buf)
245 tabs[v.TabNum].Resize()
249 // VSplit opens a vertical split with the given buffer
250 func (v *View) VSplit(buf *Buffer) bool {
251 v.splitNode.VSplit(buf)
252 tabs[v.TabNum].Resize()
256 // Relocate moves the view window so that the cursor is in view
257 // This is useful if the user has scrolled far away, and then starts typing
258 func (v *View) Relocate() bool {
261 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
262 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
263 v.Topline = cy - scrollmargin
265 } else if cy < v.Topline {
269 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
270 v.Topline = cy - v.height + 1 + scrollmargin
272 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
273 v.Topline = v.Buf.NumLines - v.height
277 cx := v.Cursor.GetVisualX()
282 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
283 v.leftCol = cx - v.width + v.lineNumOffset + 1
289 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
291 func (v *View) MoveToMouseClick(x, y int) {
292 if y-v.Topline > v.height-1 {
294 y = v.height + v.Topline - 1
296 if y >= v.Buf.NumLines {
297 y = v.Buf.NumLines - 1
306 x = v.Cursor.GetCharPosInLine(y, x)
307 if x > Count(v.Buf.Line(y)) {
308 x = Count(v.Buf.Line(y))
312 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
315 // HandleEvent handles an event passed by the main loop
316 func (v *View) HandleEvent(event tcell.Event) {
317 // This bool determines whether the view is relocated at the end of the function
318 // By default it's true because most events should cause a relocate
323 switch e := event.(type) {
324 case *tcell.EventResize:
326 tabs[v.TabNum].Resize()
327 case *tcell.EventKey:
328 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
329 // Insert a character
330 if v.Cursor.HasSelection() {
331 v.Cursor.DeleteSelection()
332 v.Cursor.ResetSelection()
334 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
337 for _, pl := range loadedPlugins {
338 _, err := Call(pl+".onRune", string(e.Rune()), v)
339 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
344 for key, actions := range bindings {
345 if e.Key() == key.keyCode {
346 if e.Key() == tcell.KeyRune {
347 if e.Rune() != key.r {
351 if e.Modifiers() == key.modifiers {
353 for _, action := range actions {
354 relocate = action(v, true) || relocate
360 case *tcell.EventPaste:
361 if !PreActionCall("Paste", v) {
365 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
367 if v.Cursor.HasSelection() {
368 v.Cursor.DeleteSelection()
369 v.Cursor.ResetSelection()
372 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
373 v.Buf.Insert(v.Cursor.Loc, clip)
374 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
376 messenger.Message("Pasted clipboard")
378 PostActionCall("Paste", v)
379 case *tcell.EventMouse:
381 x -= v.lineNumOffset - v.leftCol + v.x
383 // Don't relocate for mouse events
386 button := e.Buttons()
392 v.MoveToMouseClick(x, y)
393 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
396 v.lastClickTime = time.Now()
399 v.doubleClick = false
401 v.Cursor.SelectLine()
404 v.lastClickTime = time.Now()
407 v.tripleClick = false
409 v.Cursor.SelectWord()
412 v.doubleClick = false
413 v.tripleClick = false
414 v.lastClickTime = time.Now()
416 v.Cursor.OrigSelection[0] = v.Cursor.Loc
417 v.Cursor.CurSelection[0] = v.Cursor.Loc
418 v.Cursor.CurSelection[1] = v.Cursor.Loc
420 v.mouseReleased = false
421 } else if !v.mouseReleased {
422 v.MoveToMouseClick(x, y)
424 v.Cursor.AddLineToSelection()
425 } else if v.doubleClick {
426 v.Cursor.AddWordToSelection()
428 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
432 // Middle mouse button was clicked,
433 // We should paste primary
435 case tcell.ButtonNone:
436 // Mouse event with no click
437 if !v.mouseReleased {
438 // Mouse was just released
440 // Relocating here isn't really necessary because the cursor will
441 // be in the right place from the last mouse event
442 // However, if we are running in a terminal that doesn't support mouse motion
443 // events, this still allows the user to make selections, except only after they
446 if !v.doubleClick && !v.tripleClick {
447 v.MoveToMouseClick(x, y)
448 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
450 v.mouseReleased = true
454 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
455 v.ScrollUp(scrollspeed)
456 case tcell.WheelDown:
458 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
459 v.ScrollDown(scrollspeed)
466 if v.Buf.Settings["syntax"].(bool) {
471 // GutterMessage creates a message in this view's gutter
472 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
474 gutterMsg := GutterMessage{
479 for _, v := range v.messages {
480 for _, gmsg := range v {
481 if gmsg.lineNum == lineN {
486 messages := v.messages[section]
487 v.messages[section] = append(messages, gutterMsg)
490 // ClearGutterMessages clears all gutter messages from a given section
491 func (v *View) ClearGutterMessages(section string) {
492 v.messages[section] = []GutterMessage{}
495 // ClearAllGutterMessages clears all the gutter messages
496 func (v *View) ClearAllGutterMessages() {
497 for k := range v.messages {
498 v.messages[k] = []GutterMessage{}
502 // Opens the given help page in a new horizontal split
503 func (v *View) openHelp(helpPage string) {
505 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
506 helpBuffer.Name = "Help"
507 v.OpenBuffer(helpBuffer)
509 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
510 helpBuffer.Name = "Help"
512 CurView().Help = true
516 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
517 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
518 screen.SetContent(x, y, ch, combc, style)
522 // DisplayView renders the view to the screen
523 func (v *View) DisplayView() {
524 // The charNum we are currently displaying
525 // starts at the start of the viewport
526 charNum := Loc{0, v.Topline}
528 // Convert the length of buffer to a string, and get the length of the string
529 // We are going to have to offset by that amount
530 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
532 if v.Buf.Settings["ruler"] == true {
533 // + 1 for the little space after the line number
534 v.lineNumOffset = maxLineLength + 1
539 // We need to add to the line offset if there are gutter messages
540 var hasGutterMessages bool
541 for _, v := range v.messages {
543 hasGutterMessages = true
546 if hasGutterMessages {
551 // One space for the extra split divider
555 // These represent the current screen coordinates
556 screenX, screenY := 0, 0
558 highlightStyle := defStyle
560 // ViewLine is the current line from the top of the viewport
561 for viewLine := 0; viewLine < v.height; viewLine++ {
562 screenY = v.y + viewLine
565 // This is the current line number of the buffer that we are drawing
566 curLineN := viewLine + v.Topline
569 // Draw the split divider
570 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
574 // If the buffer is smaller than the view height we have to clear all this space
575 if curLineN >= v.Buf.NumLines {
576 for i := screenX; i < v.x+v.width; i++ {
577 v.drawCell(i, screenY, ' ', nil, defStyle)
582 line := v.Buf.Line(curLineN)
584 // If there are gutter messages we need to display the '>>' symbol here
585 if hasGutterMessages {
586 // msgOnLine stores whether or not there is a gutter message on this line in particular
588 for k := range v.messages {
589 for _, msg := range v.messages[k] {
590 if msg.lineNum == curLineN {
592 gutterStyle := defStyle
595 if style, ok := colorscheme["gutter-info"]; ok {
599 if style, ok := colorscheme["gutter-warning"]; ok {
603 if style, ok := colorscheme["gutter-error"]; ok {
607 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
609 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
611 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
612 messenger.Message(msg.msg)
613 messenger.gutterMessage = true
618 // If there is no message on this line we just display an empty offset
620 v.drawCell(screenX, screenY, ' ', nil, defStyle)
622 v.drawCell(screenX, screenY, ' ', nil, defStyle)
624 if v.Cursor.Y == curLineN && messenger.gutterMessage {
626 messenger.gutterMessage = false
631 if v.Buf.Settings["ruler"] == true {
632 // Write the line number
633 lineNumStyle := defStyle
634 if style, ok := colorscheme["line-number"]; ok {
637 if style, ok := colorscheme["current-line-number"]; ok {
638 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
643 lineNum := strconv.Itoa(curLineN + 1)
645 // Write the spaces before the line number if necessary
646 for i := 0; i < maxLineLength-len(lineNum); i++ {
647 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
650 // Write the actual line number
651 for _, ch := range lineNum {
652 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
656 // Write the extra space
657 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
661 // Now we actually draw the line
663 for _, ch := range line {
664 lineStyle := defStyle
666 if v.Buf.Settings["syntax"].(bool) {
667 // Syntax highlighting is enabled
668 highlightStyle = v.matches[viewLine][colN]
671 if v.Cursor.HasSelection() &&
672 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
673 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
674 // The current character is selected
675 lineStyle = defStyle.Reverse(true)
677 if style, ok := colorscheme["selection"]; ok {
681 lineStyle = highlightStyle
684 // We need to display the background of the linestyle with the correct color if cursorline is enabled
685 // and this is the current view and there is no selection on this line and the cursor is on this line
686 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
687 if style, ok := colorscheme["cursor-line"]; ok {
688 fg, _, _ := style.Decompose()
689 lineStyle = lineStyle.Background(fg)
694 // If the character we are displaying is a tab, we need to do a bunch of special things
696 // First the user may have configured an `indent-char` to be displayed to show that this
697 // is a tab character
698 lineIndentStyle := defStyle
699 if style, ok := colorscheme["indent-char"]; ok {
700 lineIndentStyle = style
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])) {
706 lineIndentStyle = defStyle.Reverse(true)
708 if style, ok := colorscheme["selection"]; ok {
709 lineIndentStyle = style
712 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
713 if style, ok := colorscheme["cursor-line"]; ok {
714 fg, _, _ := style.Decompose()
715 lineIndentStyle = lineIndentStyle.Background(fg)
718 // Here we get the indent char
719 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
720 if screenX-v.x-v.leftCol >= v.lineNumOffset {
721 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
723 // Now the tab has to be displayed as a bunch of spaces
724 tabSize := int(v.Buf.Settings["tabsize"].(float64))
725 for i := 0; i < tabSize-1; i++ {
727 if screenX-v.x-v.leftCol >= v.lineNumOffset {
728 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
731 } else if runewidth.RuneWidth(ch) > 1 {
732 if screenX-v.x-v.leftCol >= v.lineNumOffset {
733 v.drawCell(screenX, screenY, ch, nil, lineStyle)
735 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
737 if screenX-v.x-v.leftCol >= v.lineNumOffset {
738 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
742 if screenX-v.x-v.leftCol >= v.lineNumOffset {
743 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
746 charNum = charNum.Move(1, v.Buf)
750 // Here we are at a newline
752 // The newline may be selected, in which case we should draw the selection style
753 // with a space to represent it
754 if v.Cursor.HasSelection() &&
755 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
756 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
758 selectStyle := defStyle.Reverse(true)
760 if style, ok := colorscheme["selection"]; ok {
763 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
767 charNum = charNum.Move(1, v.Buf)
769 for i := 0; i < v.width; i++ {
770 lineStyle := defStyle
771 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
772 if style, ok := colorscheme["cursor-line"]; ok {
773 fg, _, _ := style.Decompose()
774 lineStyle = lineStyle.Background(fg)
777 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
778 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
784 // DisplayCursor draws the current buffer's cursor to the screen
785 func (v *View) DisplayCursor() {
786 // Don't draw the cursor if it is out of the viewport or if it has a selection
787 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
790 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
794 // Display renders the view, the cursor, and statusline
795 func (v *View) Display() {
797 if v.Num == tabs[curTab].curView {
800 _, screenH := screen.Size()
801 if v.Buf.Settings["statusline"].(bool) {
803 } else if (v.y + v.height) != screenH-1 {
804 for x := 0; x < v.width; x++ {
805 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))