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
97 // NewView returns a new fullscreen view
98 func NewView(buf *Buffer) *View {
99 screenW, screenH := screen.Size()
100 return NewViewWidthHeight(buf, screenW, screenH)
103 // NewViewWidthHeight returns a new view with the specified width and height
104 // Note that w and h are raw column and row values
105 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
112 v.cellview = new(CellView)
118 v.messages = make(map[string][]GutterMessage)
120 v.sline = Statusline{
124 if v.Buf.Settings["statusline"].(bool) {
128 for pl := range loadedPlugins {
129 _, err := Call(pl+".onViewOpen", v)
130 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
139 // ToggleStatusLine creates an extra row for the statusline if necessary
140 func (v *View) ToggleStatusLine() {
141 if v.Buf.Settings["statusline"].(bool) {
148 // ToggleTabbar creates an extra row for the tabbar if necessary
149 func (v *View) ToggleTabbar() {
152 // Include one line for the tab bar at the top
164 func (v *View) paste(clip string) {
165 leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
167 if v.Cursor.HasSelection() {
168 v.Cursor.DeleteSelection()
169 v.Cursor.ResetSelection()
171 clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
172 v.Buf.Insert(v.Cursor.Loc, clip)
173 // v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
175 messenger.Message("Pasted clipboard")
178 // ScrollUp scrolls the view up n lines (if possible)
179 func (v *View) ScrollUp(n int) {
180 // Try to scroll by n but if it would overflow, scroll by 1
181 if v.Topline-n >= 0 {
183 } else if v.Topline > 0 {
188 // ScrollDown scrolls the view down n lines (if possible)
189 func (v *View) ScrollDown(n int) {
190 // Try to scroll by n but if it would overflow, scroll by 1
191 if v.Topline+n <= v.Buf.NumLines {
193 } else if v.Topline < v.Buf.NumLines-1 {
198 // CanClose returns whether or not the view can be closed
199 // If there are unsaved changes, the user will be asked if the view can be closed
200 // causing them to lose the unsaved changes
201 func (v *View) CanClose() bool {
202 if v.Type == vtDefault && v.Buf.Modified() {
205 if v.Buf.Settings["autosave"].(bool) {
208 choice, canceled = messenger.YesNoPrompt("Save changes to " + v.Buf.GetName() + " before closing? (y,n,esc) ")
222 // OpenBuffer opens a new buffer in this view.
223 // This resets the topline, event handler and cursor.
224 func (v *View) OpenBuffer(buf *Buffer) {
228 v.Cursor = &buf.Cursor
231 v.Cursor.ResetSelection()
234 v.messages = make(map[string][]GutterMessage)
236 // Set mouseReleased to true because we assume the mouse is not being pressed when
237 // the editor is opened
238 v.mouseReleased = true
239 v.lastClickTime = time.Time{}
242 // Open opens the given file in the view
243 func (v *View) Open(filename string) {
244 filename = ReplaceHome(filename)
245 file, err := os.Open(filename)
246 fileInfo, _ := os.Stat(filename)
248 if err == nil && fileInfo.IsDir() {
249 messenger.Error(filename, " is a directory")
257 messenger.Message(err.Error())
258 // File does not exist -- create an empty buffer with that name
259 buf = NewBufferFromString("", filename)
261 buf = NewBuffer(file, FSize(file), filename)
266 // CloseBuffer performs any closing functions on the buffer
267 func (v *View) CloseBuffer() {
273 // ReOpen reloads the current buffer
274 func (v *View) ReOpen() {
282 // HSplit opens a horizontal split with the given buffer
283 func (v *View) HSplit(buf *Buffer) {
285 if v.Buf.Settings["splitBottom"].(bool) {
288 v.splitNode.HSplit(buf, v.Num+i)
291 // VSplit opens a vertical split with the given buffer
292 func (v *View) VSplit(buf *Buffer) {
294 if v.Buf.Settings["splitRight"].(bool) {
297 v.splitNode.VSplit(buf, v.Num+i)
300 // HSplitIndex opens a horizontal split with the given buffer at the given index
301 func (v *View) HSplitIndex(buf *Buffer, splitIndex int) {
302 v.splitNode.HSplit(buf, splitIndex)
305 // VSplitIndex opens a vertical split with the given buffer at the given index
306 func (v *View) VSplitIndex(buf *Buffer, splitIndex int) {
307 v.splitNode.VSplit(buf, splitIndex)
310 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
311 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
312 if !v.Buf.Settings["softwrap"].(bool) {
313 if vy >= v.Buf.NumLines {
314 vy = v.Buf.NumLines - 1
316 vx = v.Cursor.GetCharPosInLine(vy, vx)
320 screenX, screenY := 0, v.Topline
321 for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
322 line := v.Buf.Line(lineN)
323 if lineN >= v.Buf.NumLines {
324 return 0, v.Buf.NumLines - 1
328 for _, ch := range line {
329 if screenX >= v.Width-v.lineNumOffset {
334 if screenX == vx && screenY == vy {
339 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
355 func (v *View) Bottomline() int {
356 if !v.Buf.Settings["softwrap"].(bool) {
357 return v.Topline + v.Height
360 screenX, screenY := 0, 0
362 for lineN := v.Topline; lineN < v.Topline+v.Height; lineN++ {
363 line := v.Buf.Line(lineN)
366 for _, ch := range line {
367 if screenX >= v.Width-v.lineNumOffset {
373 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
383 if screenY >= v.Height {
387 return numLines + v.Topline
390 // Relocate moves the view window so that the cursor is in view
391 // This is useful if the user has scrolled far away, and then starts typing
392 func (v *View) Relocate() bool {
393 height := v.Bottomline() - v.Topline
396 scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
397 if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
398 v.Topline = cy - scrollmargin
400 } else if cy < v.Topline {
404 if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
405 v.Topline = cy - height + 1 + scrollmargin
407 } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
408 v.Topline = v.Buf.NumLines - height
412 if !v.Buf.Settings["softwrap"].(bool) {
413 cx := v.Cursor.GetVisualX()
418 if cx+v.lineNumOffset+1 > v.leftCol+v.Width {
419 v.leftCol = cx - v.Width + v.lineNumOffset + 1
426 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
428 func (v *View) MoveToMouseClick(x, y int) {
429 if y-v.Topline > v.Height-1 {
431 y = v.Height + v.Topline - 1
440 x, y = v.GetSoftWrapLocation(x, y)
441 // x = v.Cursor.GetCharPosInLine(y, x)
442 if x > Count(v.Buf.Line(y)) {
443 x = Count(v.Buf.Line(y))
447 v.Cursor.LastVisualX = v.Cursor.GetVisualX()
450 // Execute actions executes the supplied actions
451 func (v *View) ExecuteActions(actions []func(*View, bool) bool) bool {
453 readonlyBindingsList := []string{"Delete", "Insert", "Backspace", "Cut", "Play", "Paste", "Move", "Add", "DuplicateLine", "Macro"}
454 for _, action := range actions {
455 readonlyBindingsResult := false
456 funcName := ShortFuncName(action)
457 if v.Type.readonly == true {
458 // check for readonly and if true only let key bindings get called if they do not change the contents.
459 for _, readonlyBindings := range readonlyBindingsList {
460 if strings.Contains(funcName, readonlyBindings) {
461 readonlyBindingsResult = true
465 if !readonlyBindingsResult {
466 // call the key binding
467 relocate = action(v, true) || relocate
469 if funcName != "ToggleMacro" && funcName != "PlayMacro" {
471 curMacro = append(curMacro, action)
480 // SetCursor sets the view's and buffer's cursor
481 func (v *View) SetCursor(c *Cursor) bool {
486 v.Buf.curCursor = c.Num
491 // HandleEvent handles an event passed by the main loop
492 func (v *View) HandleEvent(event tcell.Event) {
493 // This bool determines whether the view is relocated at the end of the function
494 // By default it's true because most events should cause a relocate
499 switch e := event.(type) {
500 case *tcell.EventRaw:
501 for key, actions := range bindings {
502 if key.keyCode == -1 {
503 if e.EscapeCode() == key.escape {
504 for _, c := range v.Buf.cursors {
510 relocate = v.ExecuteActions(actions) || relocate
512 v.SetCursor(&v.Buf.Cursor)
518 case *tcell.EventKey:
519 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
521 for key, actions := range bindings {
522 if e.Key() == key.keyCode {
523 if e.Key() == tcell.KeyRune {
524 if e.Rune() != key.r {
528 if e.Modifiers() == key.modifiers {
529 for _, c := range v.Buf.cursors {
536 relocate = v.ExecuteActions(actions) || relocate
538 v.SetCursor(&v.Buf.Cursor)
544 if !isBinding && e.Key() == tcell.KeyRune {
545 // Check viewtype if readonly don't insert a rune (readonly help and log view etc.)
546 if v.Type.readonly == false {
547 for _, c := range v.Buf.cursors {
550 // Insert a character
551 if v.Cursor.HasSelection() {
552 v.Cursor.DeleteSelection()
553 v.Cursor.ResetSelection()
555 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
557 for pl := range loadedPlugins {
558 _, err := Call(pl+".onRune", string(e.Rune()), v)
559 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
565 curMacro = append(curMacro, e.Rune())
568 v.SetCursor(&v.Buf.Cursor)
571 case *tcell.EventPaste:
572 // Check viewtype if readonly don't paste (readonly help and log view etc.)
573 if v.Type.readonly == false {
574 if !PreActionCall("Paste", v) {
578 for _, c := range v.Buf.cursors {
582 v.SetCursor(&v.Buf.Cursor)
584 PostActionCall("Paste", v)
586 case *tcell.EventMouse:
587 // Don't relocate for mouse events
590 button := e.Buttons()
592 for key, actions := range bindings {
593 if button == key.buttons && e.Modifiers() == key.modifiers {
594 for _, c := range v.Buf.cursors {
599 relocate = v.ExecuteActions(actions) || relocate
601 v.SetCursor(&v.Buf.Cursor)
606 for key, actions := range mouseBindings {
607 if button == key.buttons && e.Modifiers() == key.modifiers {
608 for _, action := range actions {
615 case tcell.ButtonNone:
616 // Mouse event with no click
617 if !v.mouseReleased {
618 // Mouse was just released
621 x -= v.lineNumOffset - v.leftCol + v.x
624 // Relocating here isn't really necessary because the cursor will
625 // be in the right place from the last mouse event
626 // However, if we are running in a terminal that doesn't support mouse motion
627 // events, this still allows the user to make selections, except only after they
630 if !v.doubleClick && !v.tripleClick {
631 v.MoveToMouseClick(x, y)
632 v.Cursor.SetSelectionEnd(v.Cursor.Loc)
633 v.Cursor.CopySelection("primary")
635 v.mouseReleased = true
642 // We run relocate again because there's a bug with relocating with softwrap
643 // when for example you jump to the bottom of the buffer and it tries to
644 // calculate where to put the topline so that the bottom line is at the bottom
645 // of the terminal and it runs into problems with visual lines vs real lines.
646 // This is (hopefully) a temporary solution
651 func (v *View) mainCursor() bool {
652 return v.Buf.curCursor == len(v.Buf.cursors)-1
655 // GutterMessage creates a message in this view's gutter
656 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
658 gutterMsg := GutterMessage{
663 for _, v := range v.messages {
664 for _, gmsg := range v {
665 if gmsg.lineNum == lineN {
670 messages := v.messages[section]
671 v.messages[section] = append(messages, gutterMsg)
674 // ClearGutterMessages clears all gutter messages from a given section
675 func (v *View) ClearGutterMessages(section string) {
676 v.messages[section] = []GutterMessage{}
679 // ClearAllGutterMessages clears all the gutter messages
680 func (v *View) ClearAllGutterMessages() {
681 for k := range v.messages {
682 v.messages[k] = []GutterMessage{}
686 // Opens the given help page in a new horizontal split
687 func (v *View) openHelp(helpPage string) {
688 if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
689 TermMessage("Unable to load help text", helpPage, "\n", err)
691 helpBuffer := NewBufferFromString(string(data), helpPage+".md")
692 helpBuffer.name = "Help"
694 if v.Type == vtHelp {
695 v.OpenBuffer(helpBuffer)
698 CurView().Type = vtHelp
703 // DisplayView draws the view to the screen
704 func (v *View) DisplayView() {
705 if v.Buf.Settings["softwrap"].(bool) && v.leftCol != 0 {
710 // Log views should always follow the cursor...
714 // We need to know the string length of the largest line number
715 // so we can pad appropriately when displaying line numbers
716 maxLineNumLength := len(strconv.Itoa(v.Buf.NumLines))
718 if v.Buf.Settings["ruler"] == true {
719 // + 1 for the little space after the line number
720 v.lineNumOffset = maxLineNumLength + 1
725 // We need to add to the line offset if there are gutter messages
726 var hasGutterMessages bool
727 for _, v := range v.messages {
729 hasGutterMessages = true
732 if hasGutterMessages {
738 // One space for the extra split divider
743 xOffset := v.x + v.lineNumOffset
751 v.cellview.Draw(v.Buf, top, height, left, width-v.lineNumOffset)
757 for visualLineN, line = range v.cellview.lines {
764 if firstChar != nil {
765 if firstChar.realLoc.Y == realLineN {
768 realLineN = firstChar.realLoc.Y
773 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
774 if colorcolumn != 0 {
775 style := GetColor("color-column")
776 fg, _, _ := style.Decompose()
777 st := defStyle.Background(fg)
778 screen.SetContent(xOffset+colorcolumn, yOffset+visualLineN, ' ', nil, st)
783 // If there are gutter messages we need to display the '>>' symbol here
784 if hasGutterMessages {
785 // msgOnLine stores whether or not there is a gutter message on this line in particular
787 for k := range v.messages {
788 for _, msg := range v.messages[k] {
789 if msg.lineNum == realLineN {
791 gutterStyle := defStyle
794 if style, ok := colorscheme["gutter-info"]; ok {
798 if style, ok := colorscheme["gutter-warning"]; ok {
802 if style, ok := colorscheme["gutter-error"]; ok {
806 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
808 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
810 if v.Cursor.Y == realLineN && !messenger.hasPrompt {
811 messenger.Message(msg.msg)
812 messenger.gutterMessage = true
817 // If there is no message on this line we just display an empty offset
819 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
821 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
823 if v.Cursor.Y == realLineN && messenger.gutterMessage {
825 messenger.gutterMessage = false
830 lineNumStyle := defStyle
831 if v.Buf.Settings["ruler"] == true {
832 // Write the line number
833 if style, ok := colorscheme["line-number"]; ok {
836 if style, ok := colorscheme["current-line-number"]; ok {
837 if realLineN == v.Cursor.Y && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() {
842 lineNum := strconv.Itoa(realLineN + 1)
844 // Write the spaces before the line number if necessary
845 for i := 0; i < maxLineNumLength-len(lineNum); i++ {
846 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
849 if softwrapped && visualLineN != 0 {
850 // Pad without the line number because it was written on the visual line before
852 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
856 // Write the actual line number
857 for _, ch := range lineNum {
858 screen.SetContent(screenX+divider, yOffset+visualLineN, ch, nil, lineNumStyle)
863 // Write the extra space
864 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
870 for _, char := range line {
872 lineStyle := char.style
874 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
875 if colorcolumn != 0 && char.visualLoc.X == colorcolumn {
876 style := GetColor("color-column")
877 fg, _, _ := style.Decompose()
878 lineStyle = lineStyle.Background(fg)
881 charLoc := char.realLoc
882 for _, c := range v.Buf.cursors {
884 if v.Cursor.HasSelection() &&
885 (charLoc.GreaterEqual(v.Cursor.CurSelection[0]) && charLoc.LessThan(v.Cursor.CurSelection[1]) ||
886 charLoc.LessThan(v.Cursor.CurSelection[0]) && charLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
887 // The current character is selected
888 lineStyle = defStyle.Reverse(true)
890 if style, ok := colorscheme["selection"]; ok {
895 v.SetCursor(&v.Buf.Cursor)
897 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
898 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
899 style := GetColor("cursor-line")
900 fg, _, _ := style.Decompose()
901 lineStyle = lineStyle.Background(fg)
904 screen.SetContent(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, char.drawChar, nil, lineStyle)
906 for i, c := range v.Buf.cursors {
908 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
909 v.Cursor.Y == char.realLoc.Y && v.Cursor.X == char.realLoc.X && (!cursorSet || i != 0) {
910 ShowMultiCursor(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, i)
914 v.SetCursor(&v.Buf.Cursor)
925 lastX = xOffset + lastChar.visualLoc.X + lastChar.width
926 for i, c := range v.Buf.cursors {
928 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
929 v.Cursor.Y == lastChar.realLoc.Y && v.Cursor.X == lastChar.realLoc.X+1 {
930 ShowMultiCursor(lastX, yOffset+lastChar.visualLoc.Y, i)
931 cx, cy = lastX, yOffset+lastChar.visualLoc.Y
934 v.SetCursor(&v.Buf.Cursor)
935 realLoc = Loc{lastChar.realLoc.X + 1, realLineN}
936 visualLoc = Loc{lastX - xOffset, lastChar.visualLoc.Y}
937 } else if len(line) == 0 {
938 for i, c := range v.Buf.cursors {
940 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
941 v.Cursor.Y == realLineN {
942 ShowMultiCursor(xOffset, yOffset+visualLineN, i)
943 cx, cy = xOffset, yOffset+visualLineN
946 v.SetCursor(&v.Buf.Cursor)
948 realLoc = Loc{0, realLineN}
949 visualLoc = Loc{0, visualLineN}
952 if v.Cursor.HasSelection() &&
953 (realLoc.GreaterEqual(v.Cursor.CurSelection[0]) && realLoc.LessThan(v.Cursor.CurSelection[1]) ||
954 realLoc.LessThan(v.Cursor.CurSelection[0]) && realLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
955 // The current character is selected
956 selectStyle := defStyle.Reverse(true)
958 if style, ok := colorscheme["selection"]; ok {
961 screen.SetContent(xOffset+visualLoc.X, yOffset+visualLoc.Y, ' ', nil, selectStyle)
964 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
965 !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
966 for i := lastX; i < xOffset+v.Width-v.lineNumOffset; i++ {
967 style := GetColor("cursor-line")
968 fg, _, _ := style.Decompose()
969 style = style.Background(fg)
970 if !(tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && i == cx && yOffset+visualLineN == cy) {
971 screen.SetContent(i, yOffset+visualLineN, ' ', nil, style)
978 dividerStyle := defStyle
979 if style, ok := colorscheme["divider"]; ok {
982 for i := 0; i < v.Height; i++ {
983 screen.SetContent(v.x, yOffset+i, '|', nil, dividerStyle.Reverse(true))
988 // ShowMultiCursor will display a cursor at a location
989 // If i == 0 then the terminal cursor will be used
990 // Otherwise a fake cursor will be drawn at the position
991 func ShowMultiCursor(x, y, i int) {
993 screen.ShowCursor(x, y)
995 r, _, _, _ := screen.GetContent(x, y)
996 screen.SetContent(x, y, r, nil, defStyle.Reverse(true))
1000 // Display renders the view, the cursor, and statusline
1001 func (v *View) Display() {
1002 if globalSettings["termtitle"].(bool) {
1003 screen.SetTitle("micro: " + v.Buf.GetName())
1006 // Don't draw the cursor if it is out of the viewport or if it has a selection
1007 if v.Num == tabs[curTab].CurView && (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.Height-1 || v.Cursor.HasSelection()) {
1010 _, screenH := screen.Size()
1011 if v.Buf.Settings["statusline"].(bool) {
1013 } else if (v.y + v.Height) != screenH-1 {
1014 for x := 0; x < v.Width; x++ {
1015 screen.SetContent(v.x+x, v.y+v.Height, '-', nil, defStyle.Reverse(true))