9 "github.com/mitchellh/go-homedir"
10 "github.com/zyedidia/tcell"
13 type ViewType struct {
14 readonly bool // The file cannot be edited
15 scratch bool // The file cannot be saved
19 vtDefault = ViewType{false, false}
20 vtHelp = ViewType{true, true}
21 vtLog = ViewType{true, true}
22 vtScratch = ViewType{false, true}
25 type scrollInfo struct {
31 // The View struct stores information about a view into a buffer.
32 // It stores information about the cursor, and the viewport
33 // that the user sees the buffer from.
35 // A pointer to the buffer's cursor for ease of access
38 // The topmost line, used for vertical scrolling
40 // The leftmost column, used for horizontal scrolling
42 hScrollInfo []*scrollInfo
44 // Specifies whether or not this view holds a help buffer
47 // Actual width and height
54 // Where this view is located
57 // How much to offset because of line numbers
60 // Holds the list of gutter messages
61 messages map[string][]GutterMessage
63 // This is the index of this view in the views array
65 // What tab is this view stored in
73 // Since tcell doesn't differentiate between a mouse release event
74 // and a mouse move event with no keys pressed, we need to keep
75 // track of whether or not the mouse was pressed (or not released) last event to determine
76 // mouse release events
79 // This stores when the last click was
80 // This is useful for detecting double and triple clicks
81 lastClickTime time.Time
83 // lastCutTime stores when the last ctrl+k was issued.
84 // It is used for clearing the clipboard to replace it with fresh cut lines.
87 // freshClip returns true if the clipboard has never been pasted.
90 // Was the last mouse event actually a double click?
91 // Useful for detecting triple clicks -- if a double click is detected
92 // but the last mouse event was actually a double click, it's a triple click
94 // Same here, just to keep track for mouse move events
102 // NewView returns a new fullscreen view
103 func NewView(buf *Buffer) *View {
104 screenW, screenH := screen.Size()
105 return NewViewWidthHeight(buf, screenW, screenH)
108 // NewViewWidthHeight returns a new view with the specified width and height
109 // Note that w and h are raw column and row values
110 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
117 v.cellview = new(CellView)
123 v.messages = make(map[string][]GutterMessage)
125 v.sline = Statusline{
129 if v.Buf.Settings["statusline"].(bool) {
133 for pl := range loadedPlugins {
134 _, err := Call(pl+".onViewOpen", v)
135 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
144 // ToggleStatusLine creates an extra row for the statusline if necessary
145 func (v *View) ToggleStatusLine() {
146 if v.Buf.Settings["statusline"].(bool) {
153 // ToggleTabbar creates an extra row for the tabbar if necessary
154 func (v *View) ToggleTabbar() {
157 // Include one line for the tab bar at the top
169 func (v *View) calcHScrollInfo() {
170 v.hScrollInfo = make([]*scrollInfo, v.Height)
171 for i := v.Topline; i < v.Topline+v.Height; i++ {
172 if i >= v.Buf.NumLines {
176 left, offset, style := visualToCharPos(v.leftCol, i, v.Buf.Line(i), v.Buf, int(v.Buf.Settings["tabsize"].(float64)))
177 v.hScrollInfo[i-v.Topline] = &scrollInfo{left, offset, style}
181 func (v *View) SetLeftCol(n int) {
186 func (v *View) paste(clip string) {
187 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
189 if v.Cursor.HasSelection() {
190 v.Cursor.DeleteSelection()
191 v.Cursor.ResetSelection()
193 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
194 v.Buf.Insert(v.Cursor.Loc, clip)
195 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
197 messenger.Message("Pasted clipboard")
200 // ScrollUp scrolls the view up n lines (if possible)
201 func (v *View) ScrollUp(n int) {
202 // Try to scroll by n but if it would overflow, scroll by 1
203 if v.Topline-n >= 0 {
205 } else if v.Topline > 0 {
210 // ScrollDown scrolls the view down n lines (if possible)
211 func (v *View) ScrollDown(n int) {
212 // Try to scroll by n but if it would overflow, scroll by 1
213 if v.Topline+n <= v.Buf.NumLines {
215 } else if v.Topline < v.Buf.NumLines-1 {
220 // CanClose returns whether or not the view can be closed
221 // If there are unsaved changes, the user will be asked if the view can be closed
222 // causing them to lose the unsaved changes
223 func (v *View) CanClose() bool {
224 if v.Type == vtDefault && v.Buf.IsModified {
227 if v.Buf.Settings["autosave"].(bool) {
230 char, canceled = messenger.LetterPrompt("Save changes to "+v.Buf.GetName()+" before closing? (y,n,esc) ", 'y', 'n')
236 } else if char == 'n' {
246 // OpenBuffer opens a new buffer in this view.
247 // This resets the topline, event handler and cursor.
248 func (v *View) OpenBuffer(buf *Buffer) {
252 v.Cursor = &buf.Cursor
256 v.Cursor.ResetSelection()
259 v.messages = make(map[string][]GutterMessage)
261 // Set mouseReleased to true because we assume the mouse is not being pressed when
262 // the editor is opened
263 v.mouseReleased = true
264 v.lastClickTime = time.Time{}
267 // Open opens the given file in the view
268 func (v *View) Open(filename string) {
269 home, _ := homedir.Dir()
270 filename = strings.Replace(filename, "~", home, 1)
271 file, err := os.Open(filename)
276 messenger.Message(err.Error())
277 // File does not exist -- create an empty buffer with that name
278 buf = NewBuffer(strings.NewReader(""), filename)
280 buf = NewBuffer(file, filename)
285 // CloseBuffer performs any closing functions on the buffer
286 func (v *View) CloseBuffer() {
292 // ReOpen reloads the current buffer
293 func (v *View) ReOpen() {
301 // HSplit opens a horizontal split with the given buffer
302 func (v *View) HSplit(buf *Buffer) {
304 if v.Buf.Settings["splitBottom"].(bool) {
307 v.splitNode.HSplit(buf, v.Num+i)
310 // VSplit opens a vertical split with the given buffer
311 func (v *View) VSplit(buf *Buffer) {
313 if v.Buf.Settings["splitRight"].(bool) {
316 v.splitNode.VSplit(buf, v.Num+i)
319 // HSplitIndex opens a horizontal split with the given buffer at the given index
320 func (v *View) HSplitIndex(buf *Buffer, splitIndex int) {
321 v.splitNode.HSplit(buf, splitIndex)
324 // VSplitIndex opens a vertical split with the given buffer at the given index
325 func (v *View) VSplitIndex(buf *Buffer, splitIndex int) {
326 v.splitNode.VSplit(buf, splitIndex)
329 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
330 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
331 if !v.Buf.Settings["softwrap"].(bool) {
332 if vy >= v.Buf.NumLines {
333 vy = v.Buf.NumLines - 1
335 vx = v.Cursor.GetCharPosInLine(vy, vx)
339 screenX, screenY := 0, v.Topline
340 for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
341 line := v.Buf.Line(lineN)
342 if lineN >= v.Buf.NumLines {
343 return 0, v.Buf.NumLines - 1
347 for _, ch := range line {
348 if screenX >= v.Width-v.lineNumOffset {
353 if screenX == vx && screenY == vy {
358 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
374 func (v *View) Bottomline() int {
375 if !v.Buf.Settings["softwrap"].(bool) {
376 return v.Topline + v.Height
379 screenX, screenY := 0, 0
381 for lineN := v.Topline; lineN < v.Topline+v.Height; lineN++ {
382 line := v.Buf.Line(lineN)
385 for _, ch := range line {
386 if screenX >= v.Width-v.lineNumOffset {
392 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
402 if screenY >= v.Height {
406 return numLines + v.Topline
409 // Relocate moves the view window so that the cursor is in view
410 // This is useful if the user has scrolled far away, and then starts typing
411 func (v *View) Relocate() bool {
412 height := v.Bottomline() - v.Topline
415 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
416 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
417 v.Topline = cy - scrollmargin
419 } else if cy < v.Topline {
423 if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
424 v.Topline = cy - height + 1 + scrollmargin
426 } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
427 v.Topline = v.Buf.NumLines - height
431 if !v.Buf.Settings["softwrap"].(bool) {
432 cx := v.Cursor.GetVisualX()
438 if cx+v.lineNumOffset+1 > v.leftCol+v.Width {
439 // v.leftCol = cx - v.Width + v.lineNumOffset + 1
440 v.SetLeftCol(cx - v.Width + v.lineNumOffset + 1)
447 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
449 func (v *View) MoveToMouseClick(x, y int) {
450 if y-v.Topline > v.Height-1 {
452 y = v.Height + v.Topline - 1
461 x, y = v.GetSoftWrapLocation(x, y)
462 // x = v.Cursor.GetCharPosInLine(y, x)
463 if x > Count(v.Buf.Line(y)) {
464 x = Count(v.Buf.Line(y))
468 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
471 // HandleEvent handles an event passed by the main loop
472 func (v *View) HandleEvent(event tcell.Event) {
473 // This bool determines whether the view is relocated at the end of the function
474 // By default it's true because most events should cause a relocate
479 switch e := event.(type) {
480 case *tcell.EventKey:
481 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
483 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
484 for key, actions := range bindings {
485 if e.Key() == key.keyCode {
486 if e.Key() == tcell.KeyRune {
487 if e.Rune() != key.r {
491 if e.Modifiers() == key.modifiers {
494 for _, action := range actions {
495 relocate = action(v, true) || relocate
496 funcName := FuncName(action)
497 if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
499 curMacro = append(curMacro, action)
508 if !isBinding && e.Key() == tcell.KeyRune {
509 // Insert a character
510 if v.Cursor.HasSelection() {
511 v.Cursor.DeleteSelection()
512 v.Cursor.ResetSelection()
514 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
517 for pl := range loadedPlugins {
518 _, err := Call(pl+".onRune", string(e.Rune()), v)
519 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
525 curMacro = append(curMacro, e.Rune())
528 case *tcell.EventPaste:
529 if !PreActionCall("Paste", v) {
535 PostActionCall("Paste", v)
536 case *tcell.EventMouse:
538 x -= v.lineNumOffset - v.leftCol + v.x
540 // Don't relocate for mouse events
543 button := e.Buttons()
549 v.MoveToMouseClick(x, y)
550 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
553 v.lastClickTime = time.Now()
556 v.doubleClick = false
558 v.Cursor.SelectLine()
559 v.Cursor.CopySelection("primary")
562 v.lastClickTime = time.Now()
565 v.tripleClick = false
567 v.Cursor.SelectWord()
568 v.Cursor.CopySelection("primary")
571 v.doubleClick = false
572 v.tripleClick = false
573 v.lastClickTime = time.Now()
575 v.Cursor.OrigSelection[0] = v.Cursor.Loc
576 v.Cursor.CurSelection[0] = v.Cursor.Loc
577 v.Cursor.CurSelection[1] = v.Cursor.Loc
579 v.mouseReleased = false
580 } else if !v.mouseReleased {
581 v.MoveToMouseClick(x, y)
583 v.Cursor.AddLineToSelection()
584 } else if v.doubleClick {
585 v.Cursor.AddWordToSelection()
587 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
588 v.Cursor.CopySelection("primary")
592 // Middle mouse button was clicked,
593 // We should paste primary
595 case tcell.ButtonNone:
596 // Mouse event with no click
597 if !v.mouseReleased {
598 // Mouse was just released
600 // Relocating here isn't really necessary because the cursor will
601 // be in the right place from the last mouse event
602 // However, if we are running in a terminal that doesn't support mouse motion
603 // events, this still allows the user to make selections, except only after they
606 if !v.doubleClick && !v.tripleClick {
607 v.MoveToMouseClick(x, y)
608 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
609 v.Cursor.CopySelection("primary")
611 v.mouseReleased = true
615 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
616 v.ScrollUp(scrollspeed)
617 case tcell.WheelDown:
619 scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
620 v.ScrollDown(scrollspeed)
629 // GutterMessage creates a message in this view's gutter
630 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
632 gutterMsg := GutterMessage{
637 for _, v := range v.messages {
638 for _, gmsg := range v {
639 if gmsg.lineNum == lineN {
644 messages := v.messages[section]
645 v.messages[section] = append(messages, gutterMsg)
648 // ClearGutterMessages clears all gutter messages from a given section
649 func (v *View) ClearGutterMessages(section string) {
650 v.messages[section] = []GutterMessage{}
653 // ClearAllGutterMessages clears all the gutter messages
654 func (v *View) ClearAllGutterMessages() {
655 for k := range v.messages {
656 v.messages[k] = []GutterMessage{}
660 // Opens the given help page in a new horizontal split
661 func (v *View) openHelp(helpPage string) {
662 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
663 TermMessage("Unable to load help text", helpPage, "\n", err)
665 helpBuffer := NewBuffer(strings.NewReader(string(data)), helpPage+".md")
666 helpBuffer.name = "Help"
668 if v.Type == vtHelp {
669 v.OpenBuffer(helpBuffer)
672 CurView().Type = vtHelp
677 func (v *View) DisplayView() {
679 // Log views should always follow the cursor...
683 // We need to know the string length of the largest line number
684 // so we can pad appropriately when displaying line numbers
685 maxLineNumLength := len(strconv.Itoa(v.Buf.NumLines))
687 if v.Buf.Settings["ruler"] == true {
688 // + 1 for the little space after the line number
689 v.lineNumOffset = maxLineNumLength + 1
694 // We need to add to the line offset if there are gutter messages
695 var hasGutterMessages bool
696 for _, v := range v.messages {
698 hasGutterMessages = true
701 if hasGutterMessages {
706 // One space for the extra split divider
710 xOffset := v.x + v.lineNumOffset
718 v.cellview.Draw(v.Buf, v.hScrollInfo, top, height, left, width-v.lineNumOffset)
724 for visualLineN, line = range v.cellview.lines {
731 if firstChar != nil {
732 if firstChar.realLoc.Y == realLineN {
735 realLineN = firstChar.realLoc.Y
743 // Draw the split divider
744 screen.SetContent(screenX, yOffset+visualLineN, '|', nil, defStyle.Reverse(true))
748 // If there are gutter messages we need to display the '>>' symbol here
749 if hasGutterMessages {
750 // msgOnLine stores whether or not there is a gutter message on this line in particular
752 for k := range v.messages {
753 for _, msg := range v.messages[k] {
754 if msg.lineNum == realLineN {
756 gutterStyle := defStyle
759 if style, ok := colorscheme["gutter-info"]; ok {
763 if style, ok := colorscheme["gutter-warning"]; ok {
767 if style, ok := colorscheme["gutter-error"]; ok {
771 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
773 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
775 if v.Cursor.Y == realLineN && !messenger.hasPrompt {
776 messenger.Message(msg.msg)
777 messenger.gutterMessage = true
782 // If there is no message on this line we just display an empty offset
784 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
786 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
788 if v.Cursor.Y == realLineN && messenger.gutterMessage {
790 messenger.gutterMessage = false
795 lineNumStyle := defStyle
796 if v.Buf.Settings["ruler"] == true {
797 // Write the line number
798 if style, ok := colorscheme["line-number"]; ok {
801 if style, ok := colorscheme["current-line-number"]; ok {
802 if realLineN == v.Cursor.Y && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() {
807 lineNum := strconv.Itoa(realLineN + 1)
809 // Write the spaces before the line number if necessary
810 for i := 0; i < maxLineNumLength-len(lineNum); i++ {
811 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, lineNumStyle)
814 if softwrapped && visualLineN != 0 {
815 // Pad without the line number because it was written on the visual line before
817 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, lineNumStyle)
821 // Write the actual line number
822 for _, ch := range lineNum {
823 screen.SetContent(screenX, yOffset+visualLineN, ch, nil, lineNumStyle)
828 // Write the extra space
829 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, lineNumStyle)
835 for _, char := range line {
837 lineStyle := char.style
839 charLoc := char.realLoc
840 if v.Cursor.HasSelection() &&
841 (charLoc.GreaterEqual(v.Cursor.CurSelection[0]) && charLoc.LessThan(v.Cursor.CurSelection[1]) ||
842 charLoc.LessThan(v.Cursor.CurSelection[0]) && charLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
843 // The current character is selected
844 lineStyle = defStyle.Reverse(true)
846 if style, ok := colorscheme["selection"]; ok {
851 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
852 v.Cursor.Y == char.realLoc.Y && v.Cursor.X == char.realLoc.X && !cursorSet {
853 screen.ShowCursor(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y)
857 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
858 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
859 style := GetColor("cursor-line")
860 fg, _, _ := style.Decompose()
861 lineStyle = lineStyle.Background(fg)
864 screen.SetContent(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, char.drawChar, nil, lineStyle)
874 lastX = xOffset + lastChar.visualLoc.X + lastChar.width
875 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
876 v.Cursor.Y == lastChar.realLoc.Y && v.Cursor.X == lastChar.realLoc.X+1 {
877 screen.ShowCursor(lastX, yOffset+lastChar.visualLoc.Y)
879 realLoc = Loc{lastChar.realLoc.X, realLineN}
880 visualLoc = Loc{lastX - xOffset, lastChar.visualLoc.Y}
881 } else if len(line) == 0 {
882 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
883 v.Cursor.Y == realLineN {
884 screen.ShowCursor(xOffset, yOffset+visualLineN)
887 realLoc = Loc{0, realLineN}
888 visualLoc = Loc{0, visualLineN}
891 if v.Cursor.HasSelection() &&
892 (realLoc.GreaterEqual(v.Cursor.CurSelection[0]) && realLoc.LessThan(v.Cursor.CurSelection[1]) ||
893 realLoc.LessThan(v.Cursor.CurSelection[0]) && realLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
894 // The current character is selected
895 selectStyle := defStyle.Reverse(true)
897 if style, ok := colorscheme["selection"]; ok {
900 screen.SetContent(xOffset+visualLoc.X, yOffset+visualLoc.Y, ' ', nil, selectStyle)
903 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
904 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
905 for i := lastX; i < xOffset+v.Width; i++ {
906 style := GetColor("cursor-line")
907 fg, _, _ := style.Decompose()
908 style = style.Background(fg)
909 screen.SetContent(i, yOffset+visualLineN, ' ', nil, style)
914 if v.x != 0 && visualLineN < v.Height {
915 for i := visualLineN + 1; i < v.Height; i++ {
916 screen.SetContent(v.x, yOffset+i, '|', nil, defStyle.Reverse(true))
921 // DisplayCursor draws the current buffer's cursor to the screen
922 func (v *View) DisplayCursor(x, y int) {
923 // screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, y)
924 screen.ShowCursor(x, y)
927 // Display renders the view, the cursor, and statusline
928 func (v *View) Display() {
930 // Don't draw the cursor if it is out of the viewport or if it has a selection
931 if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.Height-1) || v.Cursor.HasSelection() {
934 _, screenH := screen.Size()
935 if v.Buf.Settings["statusline"].(bool) {
937 } else if (v.y + v.Height) != screenH-1 {
938 for x := 0; x < v.Width; x++ {
939 screen.SetContent(v.x+x, v.y+v.Height, '-', nil, defStyle.Reverse(true))