9 "github.com/zyedidia/tcell"
12 // The ViewType defines what kind of view this is
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
78 // lastCutTime stores when the last ctrl+k was issued.
79 // It is used for clearing the clipboard to replace it with fresh cut lines.
82 // freshClip returns true if the clipboard has never been pasted.
85 // Was the last mouse event actually a double click?
86 // Useful for detecting triple clicks -- if a double click is detected
87 // but the last mouse event was actually a double click, it's a triple click
89 // Same here, just to keep track for mouse move events
99 // NewView returns a new fullscreen view
100 func NewView(buf *Buffer) *View {
101 screenW, screenH := screen.Size()
102 return NewViewWidthHeight(buf, screenW, screenH)
105 // NewViewWidthHeight returns a new view with the specified width and height
106 // Note that w and h are raw column and row values
107 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
114 v.cellview = new(CellView)
120 v.messages = make(map[string][]GutterMessage)
122 v.sline = &Statusline{
126 v.scrollbar = &ScrollBar{
130 if v.Buf.Settings["statusline"].(bool) {
134 for pl := range loadedPlugins {
135 _, err := Call(pl+".onViewOpen", v)
136 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
145 // ToggleStatusLine creates an extra row for the statusline if necessary
146 func (v *View) ToggleStatusLine() {
147 if v.Buf.Settings["statusline"].(bool) {
154 // ToggleTabbar creates an extra row for the tabbar if necessary
155 func (v *View) ToggleTabbar() {
158 // Include one line for the tab bar at the top
170 func (v *View) paste(clip string) {
171 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
173 if v.Cursor.HasSelection() {
174 v.Cursor.DeleteSelection()
175 v.Cursor.ResetSelection()
177 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
178 v.Buf.Insert(v.Cursor.Loc, clip)
179 // v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
181 messenger.Message("Pasted clipboard")
184 // ScrollUp scrolls the view up n lines (if possible)
185 func (v *View) ScrollUp(n int) {
186 // Try to scroll by n but if it would overflow, scroll by 1
187 if v.Topline-n >= 0 {
189 } else if v.Topline > 0 {
194 // ScrollDown scrolls the view down n lines (if possible)
195 func (v *View) ScrollDown(n int) {
196 // Try to scroll by n but if it would overflow, scroll by 1
197 if v.Topline+n <= v.Buf.NumLines {
199 } else if v.Topline < v.Buf.NumLines-1 {
204 // CanClose returns whether or not the view can be closed
205 // If there are unsaved changes, the user will be asked if the view can be closed
206 // causing them to lose the unsaved changes
207 func (v *View) CanClose() bool {
208 if v.Type == vtDefault && v.Buf.Modified() {
211 if v.Buf.Settings["autosave"].(bool) {
214 choice, canceled = messenger.YesNoPrompt("Save changes to " + v.Buf.GetName() + " before closing? (y,n,esc) ")
228 // OpenBuffer opens a new buffer in this view.
229 // This resets the topline, event handler and cursor.
230 func (v *View) OpenBuffer(buf *Buffer) {
234 v.Cursor = &buf.Cursor
237 v.Cursor.ResetSelection()
240 v.messages = make(map[string][]GutterMessage)
242 // Set mouseReleased to true because we assume the mouse is not being pressed when
243 // the editor is opened
244 v.mouseReleased = true
245 v.lastClickTime = time.Time{}
248 // Open opens the given file in the view
249 func (v *View) Open(filename string) {
250 filename = ReplaceHome(filename)
251 file, err := os.Open(filename)
252 fileInfo, _ := os.Stat(filename)
254 if err == nil && fileInfo.IsDir() {
255 messenger.Error(filename, " is a directory")
263 messenger.Message(err.Error())
264 // File does not exist -- create an empty buffer with that name
265 buf = NewBufferFromString("", filename)
267 buf = NewBuffer(file, FSize(file), filename)
272 // CloseBuffer performs any closing functions on the buffer
273 func (v *View) CloseBuffer() {
279 // ReOpen reloads the current buffer
280 func (v *View) ReOpen() {
288 // HSplit opens a horizontal split with the given buffer
289 func (v *View) HSplit(buf *Buffer) {
291 if v.Buf.Settings["splitbottom"].(bool) {
294 v.splitNode.HSplit(buf, v.Num+i)
297 // VSplit opens a vertical split with the given buffer
298 func (v *View) VSplit(buf *Buffer) {
300 if v.Buf.Settings["splitright"].(bool) {
303 v.splitNode.VSplit(buf, v.Num+i)
306 // HSplitIndex opens a horizontal split with the given buffer at the given index
307 func (v *View) HSplitIndex(buf *Buffer, splitIndex int) {
308 v.splitNode.HSplit(buf, splitIndex)
311 // VSplitIndex opens a vertical split with the given buffer at the given index
312 func (v *View) VSplitIndex(buf *Buffer, splitIndex int) {
313 v.splitNode.VSplit(buf, splitIndex)
316 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
317 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
318 if !v.Buf.Settings["softwrap"].(bool) {
319 if vy >= v.Buf.NumLines {
320 vy = v.Buf.NumLines - 1
322 vx = v.Cursor.GetCharPosInLine(vy, vx)
326 screenX, screenY := 0, v.Topline
327 for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
328 line := v.Buf.Line(lineN)
329 if lineN >= v.Buf.NumLines {
330 return 0, v.Buf.NumLines - 1
334 for _, ch := range line {
335 if screenX >= v.Width-v.lineNumOffset {
340 if screenX == vx && screenY == vy {
345 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
361 func (v *View) Bottomline() int {
362 if !v.Buf.Settings["softwrap"].(bool) {
363 return v.Topline + v.Height
366 screenX, screenY := 0, 0
368 for lineN := v.Topline; lineN < v.Topline+v.Height; lineN++ {
369 line := v.Buf.Line(lineN)
372 for _, ch := range line {
373 if screenX >= v.Width-v.lineNumOffset {
379 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
389 if screenY >= v.Height {
393 return numLines + v.Topline
396 // Relocate moves the view window so that the cursor is in view
397 // This is useful if the user has scrolled far away, and then starts typing
398 func (v *View) Relocate() bool {
399 height := v.Bottomline() - v.Topline
402 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
403 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
404 v.Topline = cy - scrollmargin
406 } else if cy < v.Topline {
410 if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
411 v.Topline = cy - height + 1 + scrollmargin
413 } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
414 v.Topline = v.Buf.NumLines - height
418 if !v.Buf.Settings["softwrap"].(bool) {
419 cx := v.Cursor.GetVisualX()
424 if cx+v.lineNumOffset+1 > v.leftCol+v.Width {
425 v.leftCol = cx - v.Width + v.lineNumOffset + 1
432 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
434 func (v *View) MoveToMouseClick(x, y int) {
435 if y-v.Topline > v.Height-1 {
437 y = v.Height + v.Topline - 1
446 x, y = v.GetSoftWrapLocation(x, y)
447 // x = v.Cursor.GetCharPosInLine(y, x)
448 if x > Count(v.Buf.Line(y)) {
449 x = Count(v.Buf.Line(y))
453 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
456 // Execute actions executes the supplied actions
457 func (v *View) ExecuteActions(actions []func(*View, bool) bool) bool {
459 readonlyBindingsList := []string{"Delete", "Insert", "Backspace", "Cut", "Play", "Paste", "Move", "Add", "DuplicateLine", "Macro"}
460 for _, action := range actions {
461 readonlyBindingsResult := false
462 funcName := ShortFuncName(action)
463 if v.Type.readonly == true {
464 // check for readonly and if true only let key bindings get called if they do not change the contents.
465 for _, readonlyBindings := range readonlyBindingsList {
466 if strings.Contains(funcName, readonlyBindings) {
467 readonlyBindingsResult = true
471 if !readonlyBindingsResult {
472 // call the key binding
473 relocate = action(v, true) || relocate
475 if funcName != "ToggleMacro" && funcName != "PlayMacro" {
477 curMacro = append(curMacro, action)
486 // SetCursor sets the view's and buffer's cursor
487 func (v *View) SetCursor(c *Cursor) bool {
492 v.Buf.curCursor = c.Num
497 // HandleEvent handles an event passed by the main loop
498 func (v *View) HandleEvent(event tcell.Event) {
499 // This bool determines whether the view is relocated at the end of the function
500 // By default it's true because most events should cause a relocate
505 switch e := event.(type) {
506 case *tcell.EventRaw:
507 for key, actions := range bindings {
508 if key.keyCode == -1 {
509 if e.EscapeCode() == key.escape {
510 for _, c := range v.Buf.cursors {
516 relocate = v.ExecuteActions(actions) || relocate
518 v.SetCursor(&v.Buf.Cursor)
524 case *tcell.EventKey:
525 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
527 for key, actions := range bindings {
528 if e.Key() == key.keyCode {
529 if e.Key() == tcell.KeyRune {
530 if e.Rune() != key.r {
534 if e.Modifiers() == key.modifiers {
535 for _, c := range v.Buf.cursors {
542 relocate = v.ExecuteActions(actions) || relocate
544 v.SetCursor(&v.Buf.Cursor)
550 if !isBinding && e.Key() == tcell.KeyRune {
551 // Check viewtype if readonly don't insert a rune (readonly help and log view etc.)
552 if v.Type.readonly == false {
553 for _, c := range v.Buf.cursors {
556 // Insert a character
557 if v.Cursor.HasSelection() {
558 v.Cursor.DeleteSelection()
559 v.Cursor.ResetSelection()
561 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
563 for pl := range loadedPlugins {
564 _, err := Call(pl+".onRune", string(e.Rune()), v)
565 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
571 curMacro = append(curMacro, e.Rune())
574 v.SetCursor(&v.Buf.Cursor)
577 case *tcell.EventPaste:
578 // Check viewtype if readonly don't paste (readonly help and log view etc.)
579 if v.Type.readonly == false {
580 if !PreActionCall("Paste", v) {
584 for _, c := range v.Buf.cursors {
588 v.SetCursor(&v.Buf.Cursor)
590 PostActionCall("Paste", v)
592 case *tcell.EventMouse:
593 // Don't relocate for mouse events
596 button := e.Buttons()
598 for key, actions := range bindings {
599 if button == key.buttons && e.Modifiers() == key.modifiers {
600 for _, c := range v.Buf.cursors {
605 relocate = v.ExecuteActions(actions) || relocate
607 v.SetCursor(&v.Buf.Cursor)
612 for key, actions := range mouseBindings {
613 if button == key.buttons && e.Modifiers() == key.modifiers {
614 for _, action := range actions {
621 case tcell.ButtonNone:
622 // Mouse event with no click
623 if !v.mouseReleased {
624 // Mouse was just released
627 x -= v.lineNumOffset - v.leftCol + v.x
630 // Relocating here isn't really necessary because the cursor will
631 // be in the right place from the last mouse event
632 // However, if we are running in a terminal that doesn't support mouse motion
633 // events, this still allows the user to make selections, except only after they
636 if !v.doubleClick && !v.tripleClick {
637 v.MoveToMouseClick(x, y)
638 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
639 v.Cursor.CopySelection("primary")
641 v.mouseReleased = true
648 // We run relocate again because there's a bug with relocating with softwrap
649 // when for example you jump to the bottom of the buffer and it tries to
650 // calculate where to put the topline so that the bottom line is at the bottom
651 // of the terminal and it runs into problems with visual lines vs real lines.
652 // This is (hopefully) a temporary solution
657 func (v *View) mainCursor() bool {
658 return v.Buf.curCursor == len(v.Buf.cursors)-1
661 // GutterMessage creates a message in this view's gutter
662 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
664 gutterMsg := GutterMessage{
669 for _, v := range v.messages {
670 for _, gmsg := range v {
671 if gmsg.lineNum == lineN {
676 messages := v.messages[section]
677 v.messages[section] = append(messages, gutterMsg)
680 // ClearGutterMessages clears all gutter messages from a given section
681 func (v *View) ClearGutterMessages(section string) {
682 v.messages[section] = []GutterMessage{}
685 // ClearAllGutterMessages clears all the gutter messages
686 func (v *View) ClearAllGutterMessages() {
687 for k := range v.messages {
688 v.messages[k] = []GutterMessage{}
692 // Opens the given help page in a new horizontal split
693 func (v *View) openHelp(helpPage string) {
694 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
695 TermMessage("Unable to load help text", helpPage, "\n", err)
697 helpBuffer := NewBufferFromString(string(data), helpPage+".md")
698 helpBuffer.name = "Help"
700 if v.Type == vtHelp {
701 v.OpenBuffer(helpBuffer)
704 CurView().Type = vtHelp
709 // DisplayView draws the view to the screen
710 func (v *View) DisplayView() {
711 if v.Buf.Settings["softwrap"].(bool) && v.leftCol != 0 {
716 // Log views should always follow the cursor...
720 // We need to know the string length of the largest line number
721 // so we can pad appropriately when displaying line numbers
722 maxLineNumLength := len(strconv.Itoa(v.Buf.NumLines))
724 if v.Buf.Settings["ruler"] == true {
725 // + 1 for the little space after the line number
726 v.lineNumOffset = maxLineNumLength + 1
731 // We need to add to the line offset if there are gutter messages
732 var hasGutterMessages bool
733 for _, v := range v.messages {
735 hasGutterMessages = true
738 if hasGutterMessages {
744 // One space for the extra split divider
749 xOffset := v.x + v.lineNumOffset
757 v.cellview.Draw(v.Buf, top, height, left, width-v.lineNumOffset)
763 for visualLineN, line = range v.cellview.lines {
770 if firstChar != nil {
771 if firstChar.realLoc.Y == realLineN {
774 realLineN = firstChar.realLoc.Y
779 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
780 if colorcolumn != 0 {
781 style := GetColor("color-column")
782 fg, _, _ := style.Decompose()
783 st := defStyle.Background(fg)
784 screen.SetContent(xOffset+colorcolumn, yOffset+visualLineN, ' ', nil, st)
789 // If there are gutter messages we need to display the '>>' symbol here
790 if hasGutterMessages {
791 // msgOnLine stores whether or not there is a gutter message on this line in particular
793 for k := range v.messages {
794 for _, msg := range v.messages[k] {
795 if msg.lineNum == realLineN {
797 gutterStyle := defStyle
800 if style, ok := colorscheme["gutter-info"]; ok {
804 if style, ok := colorscheme["gutter-warning"]; ok {
808 if style, ok := colorscheme["gutter-error"]; ok {
812 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
814 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
816 if v.Cursor.Y == realLineN && !messenger.hasPrompt {
817 messenger.Message(msg.msg)
818 messenger.gutterMessage = true
823 // If there is no message on this line we just display an empty offset
825 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
827 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
829 if v.Cursor.Y == realLineN && messenger.gutterMessage {
831 messenger.gutterMessage = false
836 lineNumStyle := defStyle
837 if v.Buf.Settings["ruler"] == true {
838 // Write the line number
839 if style, ok := colorscheme["line-number"]; ok {
842 if style, ok := colorscheme["current-line-number"]; ok {
843 if realLineN == v.Cursor.Y && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() {
848 lineNum := strconv.Itoa(realLineN + 1)
850 // Write the spaces before the line number if necessary
851 for i := 0; i < maxLineNumLength-len(lineNum); i++ {
852 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
855 if softwrapped && visualLineN != 0 {
856 // Pad without the line number because it was written on the visual line before
858 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
862 // Write the actual line number
863 for _, ch := range lineNum {
864 screen.SetContent(screenX+divider, yOffset+visualLineN, ch, nil, lineNumStyle)
869 // Write the extra space
870 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
876 for _, char := range line {
878 lineStyle := char.style
880 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
881 if colorcolumn != 0 && char.visualLoc.X == colorcolumn {
882 style := GetColor("color-column")
883 fg, _, _ := style.Decompose()
884 lineStyle = lineStyle.Background(fg)
887 charLoc := char.realLoc
888 for _, c := range v.Buf.cursors {
890 if v.Cursor.HasSelection() &&
891 (charLoc.GreaterEqual(v.Cursor.CurSelection[0]) && charLoc.LessThan(v.Cursor.CurSelection[1]) ||
892 charLoc.LessThan(v.Cursor.CurSelection[0]) && charLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
893 // The current character is selected
894 lineStyle = defStyle.Reverse(true)
896 if style, ok := colorscheme["selection"]; ok {
901 v.SetCursor(&v.Buf.Cursor)
903 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
904 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
905 style := GetColor("cursor-line")
906 fg, _, _ := style.Decompose()
907 lineStyle = lineStyle.Background(fg)
910 screen.SetContent(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, char.drawChar, nil, lineStyle)
912 for i, c := range v.Buf.cursors {
914 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
915 v.Cursor.Y == char.realLoc.Y && v.Cursor.X == char.realLoc.X && (!cursorSet || i != 0) {
916 ShowMultiCursor(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, i)
920 v.SetCursor(&v.Buf.Cursor)
931 lastX = xOffset + lastChar.visualLoc.X + lastChar.width
932 for i, c := range v.Buf.cursors {
934 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
935 v.Cursor.Y == lastChar.realLoc.Y && v.Cursor.X == lastChar.realLoc.X+1 {
936 ShowMultiCursor(lastX, yOffset+lastChar.visualLoc.Y, i)
937 cx, cy = lastX, yOffset+lastChar.visualLoc.Y
940 v.SetCursor(&v.Buf.Cursor)
941 realLoc = Loc{lastChar.realLoc.X + 1, realLineN}
942 visualLoc = Loc{lastX - xOffset, lastChar.visualLoc.Y}
943 } else if len(line) == 0 {
944 for i, c := range v.Buf.cursors {
946 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
947 v.Cursor.Y == realLineN {
948 ShowMultiCursor(xOffset, yOffset+visualLineN, i)
949 cx, cy = xOffset, yOffset+visualLineN
952 v.SetCursor(&v.Buf.Cursor)
954 realLoc = Loc{0, realLineN}
955 visualLoc = Loc{0, visualLineN}
958 if v.Cursor.HasSelection() &&
959 (realLoc.GreaterEqual(v.Cursor.CurSelection[0]) && realLoc.LessThan(v.Cursor.CurSelection[1]) ||
960 realLoc.LessThan(v.Cursor.CurSelection[0]) && realLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
961 // The current character is selected
962 selectStyle := defStyle.Reverse(true)
964 if style, ok := colorscheme["selection"]; ok {
967 screen.SetContent(xOffset+visualLoc.X, yOffset+visualLoc.Y, ' ', nil, selectStyle)
970 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
971 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
972 for i := lastX; i < xOffset+v.Width-v.lineNumOffset; i++ {
973 style := GetColor("cursor-line")
974 fg, _, _ := style.Decompose()
975 style = style.Background(fg)
976 if !(tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && i == cx && yOffset+visualLineN == cy) {
977 screen.SetContent(i, yOffset+visualLineN, ' ', nil, style)
984 dividerStyle := defStyle
985 if style, ok := colorscheme["divider"]; ok {
988 for i := 0; i < v.Height; i++ {
989 screen.SetContent(v.x, yOffset+i, '|', nil, dividerStyle.Reverse(true))
994 // ShowMultiCursor will display a cursor at a location
995 // If i == 0 then the terminal cursor will be used
996 // Otherwise a fake cursor will be drawn at the position
997 func ShowMultiCursor(x, y, i int) {
999 screen.ShowCursor(x, y)
1001 r, _, _, _ := screen.GetContent(x, y)
1002 screen.SetContent(x, y, r, nil, defStyle.Reverse(true))
1006 // Display renders the view, the cursor, and statusline
1007 func (v *View) Display() {
1008 if globalSettings["termtitle"].(bool) {
1009 screen.SetTitle("micro: " + v.Buf.GetName())
1012 // Don't draw the cursor if it is out of the viewport or if it has a selection
1013 if v.Num == tabs[curTab].CurView && (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.Height-1 || v.Cursor.HasSelection()) {
1016 _, screenH := screen.Size()
1018 if v.Buf.Settings["scrollbar"].(bool) {
1019 v.scrollbar.Display()
1022 if v.Buf.Settings["statusline"].(bool) {
1024 } else if (v.y + v.Height) != screenH-1 {
1025 for x := 0; x < v.Width; x++ {
1026 screen.SetContent(v.x+x, v.y+v.Height, '-', nil, defStyle.Reverse(true))