9 "github.com/mitchellh/go-homedir"
10 "github.com/zyedidia/tcell"
13 type ViewType struct {
15 readonly bool // The file cannot be edited
16 scratch bool // The file cannot be saved
20 vtDefault = ViewType{0, false, false}
21 vtHelp = ViewType{1, true, true}
22 vtLog = ViewType{2, true, true}
23 vtScratch = ViewType{3, false, true}
26 // The View struct stores information about a view into a buffer.
27 // It stores information about the cursor, and the viewport
28 // that the user sees the buffer from.
30 // A pointer to the buffer's cursor for ease of access
33 // The topmost line, used for vertical scrolling
35 // The leftmost column, used for horizontal scrolling
38 // Specifies whether or not this view holds a help buffer
41 // Actual width and height
48 // Where this view is located
51 // How much to offset because of line numbers
54 // Holds the list of gutter messages
55 messages map[string][]GutterMessage
57 // This is the index of this view in the views array
59 // What tab is this view stored in
67 // Since tcell doesn't differentiate between a mouse release event
68 // and a mouse move event with no keys pressed, we need to keep
69 // track of whether or not the mouse was pressed (or not released) last event to determine
70 // mouse release events
73 // This stores when the last click was
74 // This is useful for detecting double and triple clicks
75 lastClickTime time.Time
77 // lastCutTime stores when the last ctrl+k was issued.
78 // It is used for clearing the clipboard to replace it with fresh cut lines.
81 // freshClip returns true if the clipboard has never been pasted.
84 // Was the last mouse event actually a double click?
85 // Useful for detecting triple clicks -- if a double click is detected
86 // but the last mouse event was actually a double click, it's a triple click
88 // Same here, just to keep track for mouse move events
96 // NewView returns a new fullscreen view
97 func NewView(buf *Buffer) *View {
98 screenW, screenH := screen.Size()
99 return NewViewWidthHeight(buf, screenW, screenH)
102 // NewViewWidthHeight returns a new view with the specified width and height
103 // Note that w and h are raw column and row values
104 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
111 v.cellview = new(CellView)
117 v.messages = make(map[string][]GutterMessage)
119 v.sline = Statusline{
123 if v.Buf.Settings["statusline"].(bool) {
127 for pl := range loadedPlugins {
128 _, err := Call(pl+".onViewOpen", v)
129 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
138 // ToggleStatusLine creates an extra row for the statusline if necessary
139 func (v *View) ToggleStatusLine() {
140 if v.Buf.Settings["statusline"].(bool) {
147 // ToggleTabbar creates an extra row for the tabbar if necessary
148 func (v *View) ToggleTabbar() {
151 // Include one line for the tab bar at the top
163 func (v *View) paste(clip string) {
164 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
166 if v.Cursor.HasSelection() {
167 v.Cursor.DeleteSelection()
168 v.Cursor.ResetSelection()
170 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
171 v.Buf.Insert(v.Cursor.Loc, clip)
172 // v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
174 messenger.Message("Pasted clipboard")
177 // ScrollUp scrolls the view up n lines (if possible)
178 func (v *View) ScrollUp(n int) {
179 // Try to scroll by n but if it would overflow, scroll by 1
180 if v.Topline-n >= 0 {
182 } else if v.Topline > 0 {
187 // ScrollDown scrolls the view down n lines (if possible)
188 func (v *View) ScrollDown(n int) {
189 // Try to scroll by n but if it would overflow, scroll by 1
190 if v.Topline+n <= v.Buf.NumLines {
192 } else if v.Topline < v.Buf.NumLines-1 {
197 // CanClose returns whether or not the view can be closed
198 // If there are unsaved changes, the user will be asked if the view can be closed
199 // causing them to lose the unsaved changes
200 func (v *View) CanClose() bool {
201 if v.Type == vtDefault && v.Buf.IsModified {
204 if v.Buf.Settings["autosave"].(bool) {
207 choice, canceled = messenger.YesNoPrompt("Save changes to " + v.Buf.GetName() + " before closing? (y,n,esc) ")
224 // OpenBuffer opens a new buffer in this view.
225 // This resets the topline, event handler and cursor.
226 func (v *View) OpenBuffer(buf *Buffer) {
230 v.Cursor = &buf.Cursor
233 v.Cursor.ResetSelection()
236 v.messages = make(map[string][]GutterMessage)
238 // Set mouseReleased to true because we assume the mouse is not being pressed when
239 // the editor is opened
240 v.mouseReleased = true
241 v.lastClickTime = time.Time{}
244 // Open opens the given file in the view
245 func (v *View) Open(filename string) {
246 home, _ := homedir.Dir()
247 filename = strings.Replace(filename, "~", home, 1)
248 file, err := os.Open(filename)
249 fileInfo, _ := os.Stat(filename)
251 if err == nil && fileInfo.IsDir() {
252 messenger.Error(filename, " is a directory")
260 messenger.Message(err.Error())
261 // File does not exist -- create an empty buffer with that name
262 buf = NewBufferFromString("", filename)
264 buf = NewBuffer(file, FSize(file), filename)
269 // CloseBuffer performs any closing functions on the buffer
270 func (v *View) CloseBuffer() {
276 // ReOpen reloads the current buffer
277 func (v *View) ReOpen() {
285 // HSplit opens a horizontal split with the given buffer
286 func (v *View) HSplit(buf *Buffer) {
288 if v.Buf.Settings["splitBottom"].(bool) {
291 v.splitNode.HSplit(buf, v.Num+i)
294 // VSplit opens a vertical split with the given buffer
295 func (v *View) VSplit(buf *Buffer) {
297 if v.Buf.Settings["splitRight"].(bool) {
300 v.splitNode.VSplit(buf, v.Num+i)
303 // HSplitIndex opens a horizontal split with the given buffer at the given index
304 func (v *View) HSplitIndex(buf *Buffer, splitIndex int) {
305 v.splitNode.HSplit(buf, splitIndex)
308 // VSplitIndex opens a vertical split with the given buffer at the given index
309 func (v *View) VSplitIndex(buf *Buffer, splitIndex int) {
310 v.splitNode.VSplit(buf, splitIndex)
313 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
314 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
315 if !v.Buf.Settings["softwrap"].(bool) {
316 if vy >= v.Buf.NumLines {
317 vy = v.Buf.NumLines - 1
319 vx = v.Cursor.GetCharPosInLine(vy, vx)
323 screenX, screenY := 0, v.Topline
324 for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
325 line := v.Buf.Line(lineN)
326 if lineN >= v.Buf.NumLines {
327 return 0, v.Buf.NumLines - 1
331 for _, ch := range line {
332 if screenX >= v.Width-v.lineNumOffset {
337 if screenX == vx && screenY == vy {
342 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
358 func (v *View) Bottomline() int {
359 if !v.Buf.Settings["softwrap"].(bool) {
360 return v.Topline + v.Height
363 screenX, screenY := 0, 0
365 for lineN := v.Topline; lineN < v.Topline+v.Height; lineN++ {
366 line := v.Buf.Line(lineN)
369 for _, ch := range line {
370 if screenX >= v.Width-v.lineNumOffset {
376 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
386 if screenY >= v.Height {
390 return numLines + v.Topline
393 // Relocate moves the view window so that the cursor is in view
394 // This is useful if the user has scrolled far away, and then starts typing
395 func (v *View) Relocate() bool {
396 height := v.Bottomline() - v.Topline
399 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
400 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
401 v.Topline = cy - scrollmargin
403 } else if cy < v.Topline {
407 if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
408 v.Topline = cy - height + 1 + scrollmargin
410 } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
411 v.Topline = v.Buf.NumLines - height
415 if !v.Buf.Settings["softwrap"].(bool) {
416 cx := v.Cursor.GetVisualX()
421 if cx+v.lineNumOffset+1 > v.leftCol+v.Width {
422 v.leftCol = cx - v.Width + v.lineNumOffset + 1
429 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
431 func (v *View) MoveToMouseClick(x, y int) {
432 if y-v.Topline > v.Height-1 {
434 y = v.Height + v.Topline - 1
443 x, y = v.GetSoftWrapLocation(x, y)
444 // x = v.Cursor.GetCharPosInLine(y, x)
445 if x > Count(v.Buf.Line(y)) {
446 x = Count(v.Buf.Line(y))
450 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
453 func (v *View) ExecuteActions(actions []func(*View, bool) bool) bool {
455 readonlyBindingsList := []string{"Delete", "Insert", "Backspace", "Cut", "Play", "Paste", "Move", "Add", "DuplicateLine", "Macro"}
456 for _, action := range actions {
457 readonlyBindingsResult := false
458 funcName := ShortFuncName(action)
459 if v.Type.readonly == true {
460 // check for readonly and if true only let key bindings get called if they do not change the contents.
461 for _, readonlyBindings := range readonlyBindingsList {
462 if strings.Contains(funcName, readonlyBindings) {
463 readonlyBindingsResult = true
467 if !readonlyBindingsResult {
468 // call the key binding
469 relocate = action(v, true) || relocate
471 if funcName != "ToggleMacro" && funcName != "PlayMacro" {
473 curMacro = append(curMacro, action)
482 func (v *View) SetCursor(c *Cursor) {
484 v.Buf.curCursor = c.Num
487 // HandleEvent handles an event passed by the main loop
488 func (v *View) HandleEvent(event tcell.Event) {
489 // This bool determines whether the view is relocated at the end of the function
490 // By default it's true because most events should cause a relocate
495 switch e := event.(type) {
496 case *tcell.EventKey:
497 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
499 for key, actions := range bindings {
500 if e.Key() == key.keyCode {
501 if e.Key() == tcell.KeyRune {
502 if e.Rune() != key.r {
506 if e.Modifiers() == key.modifiers {
507 for _, c := range v.Buf.cursors {
511 relocate = v.ExecuteActions(actions) || relocate
513 v.SetCursor(&v.Buf.Cursor)
519 if !isBinding && e.Key() == tcell.KeyRune {
520 // Check viewtype if readonly don't insert a rune (readonly help and log view etc.)
521 if v.Type.readonly == false {
522 for _, c := range v.Buf.cursors {
525 // Insert a character
526 if v.Cursor.HasSelection() {
527 v.Cursor.DeleteSelection()
528 v.Cursor.ResetSelection()
530 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
532 for pl := range loadedPlugins {
533 _, err := Call(pl+".onRune", string(e.Rune()), v)
534 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
540 curMacro = append(curMacro, e.Rune())
543 v.SetCursor(&v.Buf.Cursor)
546 case *tcell.EventPaste:
547 // Check viewtype if readonly don't paste (readonly help and log view etc.)
548 if v.Type.readonly == false {
549 if !PreActionCall("Paste", v) {
553 for _, c := range v.Buf.cursors {
558 v.SetCursor(&v.Buf.Cursor)
560 PostActionCall("Paste", v)
562 case *tcell.EventMouse:
563 // Don't relocate for mouse events
566 button := e.Buttons()
568 for key, actions := range bindings {
569 if button == key.buttons && e.Modifiers() == key.modifiers {
570 for _, c := range v.Buf.cursors {
572 relocate = v.ExecuteActions(actions) || relocate
574 v.SetCursor(&v.Buf.Cursor)
579 for key, actions := range mouseBindings {
580 if button == key.buttons && e.Modifiers() == key.modifiers {
581 for _, action := range actions {
588 case tcell.ButtonNone:
589 // Mouse event with no click
590 if !v.mouseReleased {
591 // Mouse was just released
594 x -= v.lineNumOffset - v.leftCol + v.x
597 // Relocating here isn't really necessary because the cursor will
598 // be in the right place from the last mouse event
599 // However, if we are running in a terminal that doesn't support mouse motion
600 // events, this still allows the user to make selections, except only after they
603 if !v.doubleClick && !v.tripleClick {
604 v.MoveToMouseClick(x, y)
605 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
606 v.Cursor.CopySelection("primary")
608 v.mouseReleased = true
615 // We run relocate again because there's a bug with relocating with softwrap
616 // when for example you jump to the bottom of the buffer and it tries to
617 // calculate where to put the topline so that the bottom line is at the bottom
618 // of the terminal and it runs into problems with visual lines vs real lines.
619 // This is (hopefully) a temporary solution
624 func (v *View) mainCursor() bool {
625 return v.Buf.curCursor == len(v.Buf.cursors)-1
628 // GutterMessage creates a message in this view's gutter
629 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
631 gutterMsg := GutterMessage{
636 for _, v := range v.messages {
637 for _, gmsg := range v {
638 if gmsg.lineNum == lineN {
643 messages := v.messages[section]
644 v.messages[section] = append(messages, gutterMsg)
647 // ClearGutterMessages clears all gutter messages from a given section
648 func (v *View) ClearGutterMessages(section string) {
649 v.messages[section] = []GutterMessage{}
652 // ClearAllGutterMessages clears all the gutter messages
653 func (v *View) ClearAllGutterMessages() {
654 for k := range v.messages {
655 v.messages[k] = []GutterMessage{}
659 // Opens the given help page in a new horizontal split
660 func (v *View) openHelp(helpPage string) {
661 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
662 TermMessage("Unable to load help text", helpPage, "\n", err)
664 helpBuffer := NewBufferFromString(string(data), helpPage+".md")
665 helpBuffer.name = "Help"
667 if v.Type == vtHelp {
668 v.OpenBuffer(helpBuffer)
671 CurView().Type = vtHelp
676 func (v *View) DisplayView() {
677 if v.Buf.Settings["softwrap"].(bool) && v.leftCol != 0 {
682 // Log views should always follow the cursor...
686 // We need to know the string length of the largest line number
687 // so we can pad appropriately when displaying line numbers
688 maxLineNumLength := len(strconv.Itoa(v.Buf.NumLines))
690 if v.Buf.Settings["ruler"] == true {
691 // + 1 for the little space after the line number
692 v.lineNumOffset = maxLineNumLength + 1
697 // We need to add to the line offset if there are gutter messages
698 var hasGutterMessages bool
699 for _, v := range v.messages {
701 hasGutterMessages = true
704 if hasGutterMessages {
710 // One space for the extra split divider
715 xOffset := v.x + v.lineNumOffset
723 v.cellview.Draw(v.Buf, top, height, left, width-v.lineNumOffset)
729 for visualLineN, line = range v.cellview.lines {
736 if firstChar != nil {
737 if firstChar.realLoc.Y == realLineN {
740 realLineN = firstChar.realLoc.Y
745 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
746 if colorcolumn != 0 {
747 style := GetColor("color-column")
748 fg, _, _ := style.Decompose()
749 st := defStyle.Background(fg)
750 screen.SetContent(xOffset+colorcolumn, yOffset+visualLineN, ' ', nil, st)
755 // If there are gutter messages we need to display the '>>' symbol here
756 if hasGutterMessages {
757 // msgOnLine stores whether or not there is a gutter message on this line in particular
759 for k := range v.messages {
760 for _, msg := range v.messages[k] {
761 if msg.lineNum == realLineN {
763 gutterStyle := defStyle
766 if style, ok := colorscheme["gutter-info"]; ok {
770 if style, ok := colorscheme["gutter-warning"]; ok {
774 if style, ok := colorscheme["gutter-error"]; ok {
778 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
780 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
782 if v.Cursor.Y == realLineN && !messenger.hasPrompt {
783 messenger.Message(msg.msg)
784 messenger.gutterMessage = true
789 // If there is no message on this line we just display an empty offset
791 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
793 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
795 if v.Cursor.Y == realLineN && messenger.gutterMessage {
797 messenger.gutterMessage = false
802 lineNumStyle := defStyle
803 if v.Buf.Settings["ruler"] == true {
804 // Write the line number
805 if style, ok := colorscheme["line-number"]; ok {
808 if style, ok := colorscheme["current-line-number"]; ok {
809 if realLineN == v.Cursor.Y && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() {
814 lineNum := strconv.Itoa(realLineN + 1)
816 // Write the spaces before the line number if necessary
817 for i := 0; i < maxLineNumLength-len(lineNum); i++ {
818 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
821 if softwrapped && visualLineN != 0 {
822 // Pad without the line number because it was written on the visual line before
824 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
828 // Write the actual line number
829 for _, ch := range lineNum {
830 screen.SetContent(screenX+divider, yOffset+visualLineN, ch, nil, lineNumStyle)
835 // Write the extra space
836 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
842 for _, char := range line {
844 lineStyle := char.style
846 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
847 if colorcolumn != 0 && char.visualLoc.X == colorcolumn {
848 style := GetColor("color-column")
849 fg, _, _ := style.Decompose()
850 lineStyle = lineStyle.Background(fg)
853 charLoc := char.realLoc
854 for _, c := range v.Buf.cursors {
856 if v.Cursor.HasSelection() &&
857 (charLoc.GreaterEqual(v.Cursor.CurSelection[0]) && charLoc.LessThan(v.Cursor.CurSelection[1]) ||
858 charLoc.LessThan(v.Cursor.CurSelection[0]) && charLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
859 // The current character is selected
860 lineStyle = defStyle.Reverse(true)
862 if style, ok := colorscheme["selection"]; ok {
867 v.SetCursor(&v.Buf.Cursor)
869 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
870 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
871 style := GetColor("cursor-line")
872 fg, _, _ := style.Decompose()
873 lineStyle = lineStyle.Background(fg)
876 screen.SetContent(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, char.drawChar, nil, lineStyle)
878 for i, c := range v.Buf.cursors {
880 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
881 v.Cursor.Y == char.realLoc.Y && v.Cursor.X == char.realLoc.X && (!cursorSet || i != 0) {
882 ShowMultiCursor(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, i)
886 v.SetCursor(&v.Buf.Cursor)
897 lastX = xOffset + lastChar.visualLoc.X + lastChar.width
898 for i, c := range v.Buf.cursors {
900 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
901 v.Cursor.Y == lastChar.realLoc.Y && v.Cursor.X == lastChar.realLoc.X+1 {
902 ShowMultiCursor(lastX, yOffset+lastChar.visualLoc.Y, i)
903 cx, cy = lastX, yOffset+lastChar.visualLoc.Y
906 v.SetCursor(&v.Buf.Cursor)
907 realLoc = Loc{lastChar.realLoc.X + 1, realLineN}
908 visualLoc = Loc{lastX - xOffset, lastChar.visualLoc.Y}
909 } else if len(line) == 0 {
910 for i, c := range v.Buf.cursors {
912 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
913 v.Cursor.Y == realLineN {
914 ShowMultiCursor(xOffset, yOffset+visualLineN, i)
915 cx, cy = xOffset, yOffset+visualLineN
918 v.SetCursor(&v.Buf.Cursor)
920 realLoc = Loc{0, realLineN}
921 visualLoc = Loc{0, visualLineN}
924 if v.Cursor.HasSelection() &&
925 (realLoc.GreaterEqual(v.Cursor.CurSelection[0]) && realLoc.LessThan(v.Cursor.CurSelection[1]) ||
926 realLoc.LessThan(v.Cursor.CurSelection[0]) && realLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
927 // The current character is selected
928 selectStyle := defStyle.Reverse(true)
930 if style, ok := colorscheme["selection"]; ok {
933 screen.SetContent(xOffset+visualLoc.X, yOffset+visualLoc.Y, ' ', nil, selectStyle)
936 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
937 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
938 for i := lastX; i < xOffset+v.Width-v.lineNumOffset; i++ {
939 style := GetColor("cursor-line")
940 fg, _, _ := style.Decompose()
941 style = style.Background(fg)
942 if !(tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && i == cx && yOffset+visualLineN == cy) {
943 screen.SetContent(i, yOffset+visualLineN, ' ', nil, style)
950 dividerStyle := defStyle
951 if style, ok := colorscheme["divider"]; ok {
954 for i := 0; i < v.Height; i++ {
955 screen.SetContent(v.x, yOffset+i, '|', nil, dividerStyle.Reverse(true))
960 // ShowMultiCursor will display a cursor at a location
961 // If i == 0 then the terminal cursor will be used
962 // Otherwise a fake cursor will be drawn at the position
963 func ShowMultiCursor(x, y, i int) {
965 screen.ShowCursor(x, y)
967 r, _, _, _ := screen.GetContent(x, y)
968 screen.SetContent(x, y, r, nil, defStyle.Reverse(true))
972 // Display renders the view, the cursor, and statusline
973 func (v *View) Display() {
974 if globalSettings["termtitle"].(bool) {
975 screen.SetTitle("micro: " + v.Buf.GetName())
978 // Don't draw the cursor if it is out of the viewport or if it has a selection
979 if v.Num == tabs[curTab].CurView && (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.Height-1 || v.Cursor.HasSelection()) {
982 _, screenH := screen.Size()
983 if v.Buf.Settings["statusline"].(bool) {
985 } else if (v.y + v.Height) != screenH-1 {
986 for x := 0; x < v.Width; x++ {
987 screen.SetContent(v.x+x, v.y+v.Height, '-', nil, defStyle.Reverse(true))