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-1)
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 // ScrollUp scrolls the view up n lines (if possible)
149 func (v *View) ScrollUp(n int) {
150 // Try to scroll by n but if it would overflow, scroll by 1
151 if v.Topline-n >= 0 {
153 } else if v.Topline > 0 {
158 // ScrollDown scrolls the view down n lines (if possible)
159 func (v *View) ScrollDown(n int) {
160 // Try to scroll by n but if it would overflow, scroll by 1
161 if v.Topline+n <= v.Buf.NumLines-v.height {
163 } else if v.Topline < v.Buf.NumLines-v.height {
168 // CanClose returns whether or not the view can be closed
169 // If there are unsaved changes, the user will be asked if the view can be closed
170 // causing them to lose the unsaved changes
171 // The message is what to print after saying "You have unsaved changes. "
172 func (v *View) CanClose(msg string) bool {
173 if v.Buf.IsModified {
174 quit, canceled := messenger.Prompt("You have unsaved changes. "+msg, "Unsaved", NoCompletion)
176 if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
178 } else if strings.ToLower(quit) == "save" || strings.ToLower(quit) == "s" {
189 // OpenBuffer opens a new buffer in this view.
190 // This resets the topline, event handler and cursor.
191 func (v *View) OpenBuffer(buf *Buffer) {
195 v.Cursor = &buf.Cursor
198 v.Cursor.ResetSelection()
201 v.messages = make(map[string][]GutterMessage)
205 // Set mouseReleased to true because we assume the mouse is not being pressed when
206 // the editor is opened
207 v.mouseReleased = true
208 v.lastClickTime = time.Time{}
211 // CloseBuffer performs any closing functions on the buffer
212 func (v *View) CloseBuffer() {
218 // ReOpen reloads the current buffer
219 func (v *View) ReOpen() {
220 if v.CanClose("Continue? (yes, no, save) ") {
228 // HSplit opens a horizontal split with the given buffer
229 func (v *View) HSplit(buf *Buffer) bool {
230 v.splitNode.HSplit(buf)
231 tabs[v.TabNum].Resize()
235 // VSplit opens a vertical split with the given buffer
236 func (v *View) VSplit(buf *Buffer) bool {
237 v.splitNode.VSplit(buf)
238 tabs[v.TabNum].Resize()
242 // Relocate moves the view window so that the cursor is in view
243 // This is useful if the user has scrolled far away, and then starts typing
244 func (v *View) Relocate() bool {
247 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
248 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
249 v.Topline = cy - scrollmargin
251 } else if cy < v.Topline {
255 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
256 v.Topline = cy - v.height + 1 + scrollmargin
258 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
259 v.Topline = v.Buf.NumLines - v.height
263 cx := v.Cursor.GetVisualX()
268 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
269 v.leftCol = cx - v.width + v.lineNumOffset + 1
275 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
277 func (v *View) MoveToMouseClick(x, y int) {
278 if y-v.Topline > v.height-1 {
280 y = v.height + v.Topline - 1
282 if y >= v.Buf.NumLines {
283 y = v.Buf.NumLines - 1
292 x = v.Cursor.GetCharPosInLine(y, x)
293 if x > Count(v.Buf.Line(y)) {
294 x = Count(v.Buf.Line(y))
298 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
301 // HandleEvent handles an event passed by the main loop
302 func (v *View) HandleEvent(event tcell.Event) {
303 // This bool determines whether the view is relocated at the end of the function
304 // By default it's true because most events should cause a relocate
309 switch e := event.(type) {
310 case *tcell.EventResize:
312 tabs[v.TabNum].Resize()
313 case *tcell.EventKey:
314 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
315 // Insert a character
316 if v.Cursor.HasSelection() {
317 v.Cursor.DeleteSelection()
318 v.Cursor.ResetSelection()
320 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
323 for _, pl := range loadedPlugins {
324 _, err := Call(pl+".onRune", string(e.Rune()), v)
325 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
330 for key, actions := range bindings {
331 if e.Key() == key.keyCode {
332 if e.Key() == tcell.KeyRune {
333 if e.Rune() != key.r {
337 if e.Modifiers() == key.modifiers {
339 for _, action := range actions {
340 relocate = action(v, true) || relocate
346 case *tcell.EventPaste:
347 relocate = v.Paste(true)
348 case *tcell.EventMouse:
350 x -= v.lineNumOffset - v.leftCol + v.x
352 // Don't relocate for mouse events
355 button := e.Buttons()
361 v.MoveToMouseClick(x, y)
362 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
365 v.lastClickTime = time.Now()
368 v.doubleClick = false
370 v.Cursor.SelectLine()
373 v.lastClickTime = time.Now()
376 v.tripleClick = false
378 v.Cursor.SelectWord()
381 v.doubleClick = false
382 v.tripleClick = false
383 v.lastClickTime = time.Now()
385 v.Cursor.OrigSelection[0] = v.Cursor.Loc
386 v.Cursor.CurSelection[0] = v.Cursor.Loc
387 v.Cursor.CurSelection[1] = v.Cursor.Loc
389 v.mouseReleased = false
390 } else if !v.mouseReleased {
391 v.MoveToMouseClick(x, y)
393 v.Cursor.AddLineToSelection()
394 } else if v.doubleClick {
395 v.Cursor.AddWordToSelection()
397 v.Cursor.CurSelection[1] = v.Cursor.Loc
400 case tcell.ButtonNone:
401 // Mouse event with no click
402 if !v.mouseReleased {
403 // Mouse was just released
405 // Relocating here isn't really necessary because the cursor will
406 // be in the right place from the last mouse event
407 // However, if we are running in a terminal that doesn't support mouse motion
408 // events, this still allows the user to make selections, except only after they
411 if !v.doubleClick && !v.tripleClick {
412 v.MoveToMouseClick(x, y)
413 v.Cursor.CurSelection[1] = v.Cursor.Loc
415 v.mouseReleased = true
419 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
420 v.ScrollUp(scrollspeed)
421 case tcell.WheelDown:
423 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
424 v.ScrollDown(scrollspeed)
431 if v.Buf.Settings["syntax"].(bool) {
436 // GutterMessage creates a message in this view's gutter
437 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
439 gutterMsg := GutterMessage{
444 for _, v := range v.messages {
445 for _, gmsg := range v {
446 if gmsg.lineNum == lineN {
451 messages := v.messages[section]
452 v.messages[section] = append(messages, gutterMsg)
455 // ClearGutterMessages clears all gutter messages from a given section
456 func (v *View) ClearGutterMessages(section string) {
457 v.messages[section] = []GutterMessage{}
460 // ClearAllGutterMessages clears all the gutter messages
461 func (v *View) ClearAllGutterMessages() {
462 for k := range v.messages {
463 v.messages[k] = []GutterMessage{}
467 // Opens the given help page in a new horizontal split
468 func (v *View) openHelp(helpPage string) {
470 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
471 helpBuffer.Name = "Help"
472 v.OpenBuffer(helpBuffer)
474 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
475 helpBuffer.Name = "Help"
477 CurView().Help = true
481 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
482 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
483 screen.SetContent(x, y, ch, combc, style)
487 // DisplayView renders the view to the screen
488 func (v *View) DisplayView() {
489 // The charNum we are currently displaying
490 // starts at the start of the viewport
491 charNum := Loc{0, v.Topline}
493 // Convert the length of buffer to a string, and get the length of the string
494 // We are going to have to offset by that amount
495 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
497 if v.Buf.Settings["ruler"] == true {
498 // + 1 for the little space after the line number
499 v.lineNumOffset = maxLineLength + 1
504 // We need to add to the line offset if there are gutter messages
505 var hasGutterMessages bool
506 for _, v := range v.messages {
508 hasGutterMessages = true
511 if hasGutterMessages {
516 // One space for the extra split divider
520 // These represent the current screen coordinates
521 screenX, screenY := 0, 0
523 highlightStyle := defStyle
525 // ViewLine is the current line from the top of the viewport
526 for viewLine := 0; viewLine < v.height; viewLine++ {
527 screenY = v.y + viewLine
530 // This is the current line number of the buffer that we are drawing
531 curLineN := viewLine + v.Topline
534 // Draw the split divider
535 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
539 // If the buffer is smaller than the view height we have to clear all this space
540 if curLineN >= v.Buf.NumLines {
541 for i := screenX; i < v.x+v.width; i++ {
542 v.drawCell(i, screenY, ' ', nil, defStyle)
547 line := v.Buf.Line(curLineN)
549 // If there are gutter messages we need to display the '>>' symbol here
550 if hasGutterMessages {
551 // msgOnLine stores whether or not there is a gutter message on this line in particular
553 for k := range v.messages {
554 for _, msg := range v.messages[k] {
555 if msg.lineNum == curLineN {
557 gutterStyle := defStyle
560 if style, ok := colorscheme["gutter-info"]; ok {
564 if style, ok := colorscheme["gutter-warning"]; ok {
568 if style, ok := colorscheme["gutter-error"]; ok {
572 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
574 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
576 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
577 messenger.Message(msg.msg)
578 messenger.gutterMessage = true
583 // If there is no message on this line we just display an empty offset
585 v.drawCell(screenX, screenY, ' ', nil, defStyle)
587 v.drawCell(screenX, screenY, ' ', nil, defStyle)
589 if v.Cursor.Y == curLineN && messenger.gutterMessage {
591 messenger.gutterMessage = false
596 if v.Buf.Settings["ruler"] == true {
597 // Write the line number
598 lineNumStyle := defStyle
599 if style, ok := colorscheme["line-number"]; ok {
602 if style, ok := colorscheme["current-line-number"]; ok {
603 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
608 lineNum := strconv.Itoa(curLineN + 1)
610 // Write the spaces before the line number if necessary
611 for i := 0; i < maxLineLength-len(lineNum); i++ {
612 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
615 // Write the actual line number
616 for _, ch := range lineNum {
617 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
621 // Write the extra space
622 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
626 // Now we actually draw the line
628 for _, ch := range line {
629 lineStyle := defStyle
631 if v.Buf.Settings["syntax"].(bool) {
632 // Syntax highlighting is enabled
633 highlightStyle = v.matches[viewLine][colN]
636 if v.Cursor.HasSelection() &&
637 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
638 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
639 // The current character is selected
640 lineStyle = defStyle.Reverse(true)
642 if style, ok := colorscheme["selection"]; ok {
646 lineStyle = highlightStyle
649 // We need to display the background of the linestyle with the correct color if cursorline is enabled
650 // and this is the current view and there is no selection on this line and the cursor is on this line
651 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
652 if style, ok := colorscheme["cursor-line"]; ok {
653 fg, _, _ := style.Decompose()
654 lineStyle = lineStyle.Background(fg)
659 // If the character we are displaying is a tab, we need to do a bunch of special things
661 // First the user may have configured an `indent-char` to be displayed to show that this
662 // is a tab character
663 lineIndentStyle := defStyle
664 if style, ok := colorscheme["indent-char"]; ok {
665 lineIndentStyle = style
667 if v.Cursor.HasSelection() &&
668 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
669 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
671 lineIndentStyle = defStyle.Reverse(true)
673 if style, ok := colorscheme["selection"]; ok {
674 lineIndentStyle = style
677 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
678 if style, ok := colorscheme["cursor-line"]; ok {
679 fg, _, _ := style.Decompose()
680 lineIndentStyle = lineIndentStyle.Background(fg)
683 // Here we get the indent char
684 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
685 if screenX-v.x-v.leftCol >= v.lineNumOffset {
686 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
688 // Now the tab has to be displayed as a bunch of spaces
689 tabSize := int(v.Buf.Settings["tabsize"].(float64))
690 for i := 0; i < tabSize-1; i++ {
692 if screenX-v.x-v.leftCol >= v.lineNumOffset {
693 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
696 } else if runewidth.RuneWidth(ch) > 1 {
697 if screenX-v.x-v.leftCol >= v.lineNumOffset {
698 v.drawCell(screenX, screenY, ch, nil, lineStyle)
700 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
702 if screenX-v.x-v.leftCol >= v.lineNumOffset {
703 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
707 if screenX-v.x-v.leftCol >= v.lineNumOffset {
708 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
711 charNum = charNum.Move(1, v.Buf)
715 // Here we are at a newline
717 // The newline may be selected, in which case we should draw the selection style
718 // with a space to represent it
719 if v.Cursor.HasSelection() &&
720 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
721 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
723 selectStyle := defStyle.Reverse(true)
725 if style, ok := colorscheme["selection"]; ok {
728 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
732 charNum = charNum.Move(1, v.Buf)
734 for i := 0; i < v.width; i++ {
735 lineStyle := defStyle
736 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
737 if style, ok := colorscheme["cursor-line"]; ok {
738 fg, _, _ := style.Decompose()
739 lineStyle = lineStyle.Background(fg)
742 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
743 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
749 // DisplayCursor draws the current buffer's cursor to the screen
750 func (v *View) DisplayCursor() {
751 // Don't draw the cursor if it is out of the viewport or if it has a selection
752 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
755 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
759 // Display renders the view, the cursor, and statusline
760 func (v *View) Display() {
762 if v.Num == tabs[curTab].curView {
765 _, screenH := screen.Size()
766 if v.Buf.Settings["statusline"].(bool) {
768 } else if (v.y + v.height) != screenH-1 {
769 for x := 0; x < v.width; x++ {
770 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))