9 "github.com/mattn/go-runewidth"
10 "github.com/zyedidia/clipboard"
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 // The message is what to print after saying "You have unsaved changes. "
188 func (v *View) CanClose(msg string, responses ...rune) bool {
189 if v.Buf.IsModified {
190 char, canceled := messenger.LetterPrompt("You have unsaved changes. "+msg, responses...)
194 } else if char == 's' {
205 // OpenBuffer opens a new buffer in this view.
206 // This resets the topline, event handler and cursor.
207 func (v *View) OpenBuffer(buf *Buffer) {
211 v.Cursor = &buf.Cursor
214 v.Cursor.ResetSelection()
217 v.messages = make(map[string][]GutterMessage)
221 // Set mouseReleased to true because we assume the mouse is not being pressed when
222 // the editor is opened
223 v.mouseReleased = true
224 v.lastClickTime = time.Time{}
227 // CloseBuffer performs any closing functions on the buffer
228 func (v *View) CloseBuffer() {
234 // ReOpen reloads the current buffer
235 func (v *View) ReOpen() {
236 if v.CanClose("Continue? (y,n,s) ", 'y', 'n', 's') {
244 // HSplit opens a horizontal split with the given buffer
245 func (v *View) HSplit(buf *Buffer) bool {
246 v.splitNode.HSplit(buf)
247 tabs[v.TabNum].Resize()
251 // VSplit opens a vertical split with the given buffer
252 func (v *View) VSplit(buf *Buffer) bool {
253 v.splitNode.VSplit(buf)
254 tabs[v.TabNum].Resize()
258 // Relocate moves the view window so that the cursor is in view
259 // This is useful if the user has scrolled far away, and then starts typing
260 func (v *View) Relocate() bool {
263 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
264 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
265 v.Topline = cy - scrollmargin
267 } else if cy < v.Topline {
271 if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
272 v.Topline = cy - v.height + 1 + scrollmargin
274 } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
275 v.Topline = v.Buf.NumLines - v.height
279 cx := v.Cursor.GetVisualX()
284 if cx+v.lineNumOffset+1 > v.leftCol+v.width {
285 v.leftCol = cx - v.width + v.lineNumOffset + 1
291 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
293 func (v *View) MoveToMouseClick(x, y int) {
294 if y-v.Topline > v.height-1 {
296 y = v.height + v.Topline - 1
298 if y >= v.Buf.NumLines {
299 y = v.Buf.NumLines - 1
308 x = v.Cursor.GetCharPosInLine(y, x)
309 if x > Count(v.Buf.Line(y)) {
310 x = Count(v.Buf.Line(y))
314 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
317 // HandleEvent handles an event passed by the main loop
318 func (v *View) HandleEvent(event tcell.Event) {
319 // This bool determines whether the view is relocated at the end of the function
320 // By default it's true because most events should cause a relocate
325 switch e := event.(type) {
326 case *tcell.EventResize:
328 tabs[v.TabNum].Resize()
329 case *tcell.EventKey:
330 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
331 // Insert a character
332 if v.Cursor.HasSelection() {
333 v.Cursor.DeleteSelection()
334 v.Cursor.ResetSelection()
336 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
339 for _, pl := range loadedPlugins {
340 _, err := Call(pl+".onRune", string(e.Rune()), v)
341 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
346 for key, actions := range bindings {
347 if e.Key() == key.keyCode {
348 if e.Key() == tcell.KeyRune {
349 if e.Rune() != key.r {
353 if e.Modifiers() == key.modifiers {
355 for _, action := range actions {
356 relocate = action(v, true) || relocate
362 case *tcell.EventPaste:
363 if !PreActionCall("Paste", v) {
367 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
369 if v.Cursor.HasSelection() {
370 v.Cursor.DeleteSelection()
371 v.Cursor.ResetSelection()
374 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
375 v.Buf.Insert(v.Cursor.Loc, clip)
376 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
378 messenger.Message("Pasted clipboard")
380 PostActionCall("Paste", v)
381 case *tcell.EventMouse:
383 x -= v.lineNumOffset - v.leftCol + v.x
385 // Don't relocate for mouse events
388 button := e.Buttons()
394 v.MoveToMouseClick(x, y)
395 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
398 v.lastClickTime = time.Now()
401 v.doubleClick = false
403 v.Cursor.SelectLine()
406 v.lastClickTime = time.Now()
409 v.tripleClick = false
411 v.Cursor.SelectWord()
414 v.doubleClick = false
415 v.tripleClick = false
416 v.lastClickTime = time.Now()
418 v.Cursor.OrigSelection[0] = v.Cursor.Loc
419 v.Cursor.CurSelection[0] = v.Cursor.Loc
420 v.Cursor.CurSelection[1] = v.Cursor.Loc
422 v.mouseReleased = false
423 } else if !v.mouseReleased {
424 v.MoveToMouseClick(x, y)
426 v.Cursor.AddLineToSelection()
427 } else if v.doubleClick {
428 v.Cursor.AddWordToSelection()
430 v.Cursor.CurSelection[1] = v.Cursor.Loc
434 // Middle mouse button was clicked,
435 // We should paste primary
437 case tcell.ButtonNone:
438 // Mouse event with no click
439 if !v.mouseReleased {
440 // Mouse was just released
442 // Relocating here isn't really necessary because the cursor will
443 // be in the right place from the last mouse event
444 // However, if we are running in a terminal that doesn't support mouse motion
445 // events, this still allows the user to make selections, except only after they
448 if !v.doubleClick && !v.tripleClick {
449 v.MoveToMouseClick(x, y)
450 v.Cursor.CurSelection[1] = v.Cursor.Loc
452 if runtime.GOOS != "windows" && runtime.GOOS != "darwin" {
453 clipboard.WriteAll(v.Cursor.GetSelection(), "primary")
456 v.mouseReleased = true
460 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
461 v.ScrollUp(scrollspeed)
462 case tcell.WheelDown:
464 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
465 v.ScrollDown(scrollspeed)
472 if v.Buf.Settings["syntax"].(bool) {
477 // GutterMessage creates a message in this view's gutter
478 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
480 gutterMsg := GutterMessage{
485 for _, v := range v.messages {
486 for _, gmsg := range v {
487 if gmsg.lineNum == lineN {
492 messages := v.messages[section]
493 v.messages[section] = append(messages, gutterMsg)
496 // ClearGutterMessages clears all gutter messages from a given section
497 func (v *View) ClearGutterMessages(section string) {
498 v.messages[section] = []GutterMessage{}
501 // ClearAllGutterMessages clears all the gutter messages
502 func (v *View) ClearAllGutterMessages() {
503 for k := range v.messages {
504 v.messages[k] = []GutterMessage{}
508 // Opens the given help page in a new horizontal split
509 func (v *View) openHelp(helpPage string) {
511 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
512 helpBuffer.Name = "Help"
513 v.OpenBuffer(helpBuffer)
515 helpBuffer := NewBuffer([]byte(helpPages[helpPage]), helpPage+".md")
516 helpBuffer.Name = "Help"
518 CurView().Help = true
522 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
523 if x >= v.x && x < v.x+v.width && y >= v.y && y < v.y+v.height {
524 screen.SetContent(x, y, ch, combc, style)
528 // DisplayView renders the view to the screen
529 func (v *View) DisplayView() {
530 // The charNum we are currently displaying
531 // starts at the start of the viewport
532 charNum := Loc{0, v.Topline}
534 // Convert the length of buffer to a string, and get the length of the string
535 // We are going to have to offset by that amount
536 maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
538 if v.Buf.Settings["ruler"] == true {
539 // + 1 for the little space after the line number
540 v.lineNumOffset = maxLineLength + 1
545 // We need to add to the line offset if there are gutter messages
546 var hasGutterMessages bool
547 for _, v := range v.messages {
549 hasGutterMessages = true
552 if hasGutterMessages {
557 // One space for the extra split divider
561 // These represent the current screen coordinates
562 screenX, screenY := 0, 0
564 highlightStyle := defStyle
566 // ViewLine is the current line from the top of the viewport
567 for viewLine := 0; viewLine < v.height; viewLine++ {
568 screenY = v.y + viewLine
571 // This is the current line number of the buffer that we are drawing
572 curLineN := viewLine + v.Topline
575 // Draw the split divider
576 v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
580 // If the buffer is smaller than the view height we have to clear all this space
581 if curLineN >= v.Buf.NumLines {
582 for i := screenX; i < v.x+v.width; i++ {
583 v.drawCell(i, screenY, ' ', nil, defStyle)
588 line := v.Buf.Line(curLineN)
590 // If there are gutter messages we need to display the '>>' symbol here
591 if hasGutterMessages {
592 // msgOnLine stores whether or not there is a gutter message on this line in particular
594 for k := range v.messages {
595 for _, msg := range v.messages[k] {
596 if msg.lineNum == curLineN {
598 gutterStyle := defStyle
601 if style, ok := colorscheme["gutter-info"]; ok {
605 if style, ok := colorscheme["gutter-warning"]; ok {
609 if style, ok := colorscheme["gutter-error"]; ok {
613 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
615 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
617 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
618 messenger.Message(msg.msg)
619 messenger.gutterMessage = true
624 // If there is no message on this line we just display an empty offset
626 v.drawCell(screenX, screenY, ' ', nil, defStyle)
628 v.drawCell(screenX, screenY, ' ', nil, defStyle)
630 if v.Cursor.Y == curLineN && messenger.gutterMessage {
632 messenger.gutterMessage = false
637 if v.Buf.Settings["ruler"] == true {
638 // Write the line number
639 lineNumStyle := defStyle
640 if style, ok := colorscheme["line-number"]; ok {
643 if style, ok := colorscheme["current-line-number"]; ok {
644 if curLineN == v.Cursor.Y && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() {
649 lineNum := strconv.Itoa(curLineN + 1)
651 // Write the spaces before the line number if necessary
652 for i := 0; i < maxLineLength-len(lineNum); i++ {
653 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
656 // Write the actual line number
657 for _, ch := range lineNum {
658 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
662 // Write the extra space
663 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
667 // Now we actually draw the line
669 for _, ch := range line {
670 lineStyle := defStyle
672 if v.Buf.Settings["syntax"].(bool) {
673 // Syntax highlighting is enabled
674 highlightStyle = v.matches[viewLine][colN]
677 if v.Cursor.HasSelection() &&
678 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
679 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
680 // The current character is selected
681 lineStyle = defStyle.Reverse(true)
683 if style, ok := colorscheme["selection"]; ok {
687 lineStyle = highlightStyle
690 // We need to display the background of the linestyle with the correct color if cursorline is enabled
691 // and this is the current view and there is no selection on this line and the cursor is on this line
692 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
693 if style, ok := colorscheme["cursor-line"]; ok {
694 fg, _, _ := style.Decompose()
695 lineStyle = lineStyle.Background(fg)
700 // If the character we are displaying is a tab, we need to do a bunch of special things
702 // First the user may have configured an `indent-char` to be displayed to show that this
703 // is a tab character
704 lineIndentStyle := defStyle
705 if style, ok := colorscheme["indent-char"]; ok {
706 lineIndentStyle = style
708 if v.Cursor.HasSelection() &&
709 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
710 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
712 lineIndentStyle = defStyle.Reverse(true)
714 if style, ok := colorscheme["selection"]; ok {
715 lineIndentStyle = style
718 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
719 if style, ok := colorscheme["cursor-line"]; ok {
720 fg, _, _ := style.Decompose()
721 lineIndentStyle = lineIndentStyle.Background(fg)
724 // Here we get the indent char
725 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
726 if screenX-v.x-v.leftCol >= v.lineNumOffset {
727 v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
729 // Now the tab has to be displayed as a bunch of spaces
730 tabSize := int(v.Buf.Settings["tabsize"].(float64))
731 for i := 0; i < tabSize-1; i++ {
733 if screenX-v.x-v.leftCol >= v.lineNumOffset {
734 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
737 } else if runewidth.RuneWidth(ch) > 1 {
738 if screenX-v.x-v.leftCol >= v.lineNumOffset {
739 v.drawCell(screenX, screenY, ch, nil, lineStyle)
741 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
743 if screenX-v.x-v.leftCol >= v.lineNumOffset {
744 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
748 if screenX-v.x-v.leftCol >= v.lineNumOffset {
749 v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
752 charNum = charNum.Move(1, v.Buf)
756 // Here we are at a newline
758 // The newline may be selected, in which case we should draw the selection style
759 // with a space to represent it
760 if v.Cursor.HasSelection() &&
761 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
762 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
764 selectStyle := defStyle.Reverse(true)
766 if style, ok := colorscheme["selection"]; ok {
769 v.drawCell(screenX, screenY, ' ', nil, selectStyle)
773 charNum = charNum.Move(1, v.Buf)
775 for i := 0; i < v.width; i++ {
776 lineStyle := defStyle
777 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].curView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
778 if style, ok := colorscheme["cursor-line"]; ok {
779 fg, _, _ := style.Decompose()
780 lineStyle = lineStyle.Background(fg)
783 if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
784 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
790 // DisplayCursor draws the current buffer's cursor to the screen
791 func (v *View) DisplayCursor() {
792 // Don't draw the cursor if it is out of the viewport or if it has a selection
793 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
796 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
800 // Display renders the view, the cursor, and statusline
801 func (v *View) Display() {
803 if v.Num == tabs[curTab].curView {
806 _, screenH := screen.Size()
807 if v.Buf.Settings["statusline"].(bool) {
809 } else if (v.y + v.height) != screenH-1 {
810 for x := 0; x < v.width; x++ {
811 screen.SetContent(v.x+x, v.y+v.height, '-', nil, defStyle.Reverse(true))