]> git.lizzy.rs Git - micro.git/blob - cmd/micro/view.go
Clean up terminal emulator a bit
[micro.git] / cmd / micro / view.go
1 package main
2
3 import (
4         "fmt"
5         "os"
6         "reflect"
7         "strconv"
8         "strings"
9         "time"
10
11         "github.com/zyedidia/tcell"
12 )
13
14 // The ViewType defines what kind of view this is
15 type ViewType struct {
16         Kind     int
17         Readonly bool // The file cannot be edited
18         Scratch  bool // The file cannot be saved
19 }
20
21 var (
22         vtDefault = ViewType{0, false, false}
23         vtHelp    = ViewType{1, true, true}
24         vtLog     = ViewType{2, true, true}
25         vtScratch = ViewType{3, false, true}
26         vtRaw     = ViewType{4, true, true}
27         vtTerm    = ViewType{5, true, true}
28 )
29
30 // The View struct stores information about a view into a buffer.
31 // It stores information about the cursor, and the viewport
32 // that the user sees the buffer from.
33 type View struct {
34         // A pointer to the buffer's cursor for ease of access
35         Cursor *Cursor
36
37         // The topmost line, used for vertical scrolling
38         Topline int
39         // The leftmost column, used for horizontal scrolling
40         leftCol int
41
42         // Specifies whether or not this view holds a help buffer
43         Type ViewType
44
45         // Actual width and height
46         Width  int
47         Height int
48
49         LockWidth  bool
50         LockHeight bool
51
52         // Where this view is located
53         x, y int
54
55         // How much to offset because of line numbers
56         lineNumOffset int
57
58         // Holds the list of gutter messages
59         messages map[string][]GutterMessage
60
61         // This is the index of this view in the views array
62         Num int
63         // What tab is this view stored in
64         TabNum int
65
66         // The buffer
67         Buf *Buffer
68         // The statusline
69         sline *Statusline
70
71         // Since tcell doesn't differentiate between a mouse release event
72         // and a mouse move event with no keys pressed, we need to keep
73         // track of whether or not the mouse was pressed (or not released) last event to determine
74         // mouse release events
75         mouseReleased bool
76
77         // We need to keep track of insert key press toggle
78         isOverwriteMode bool
79         // This stores when the last click was
80         // This is useful for detecting double and triple clicks
81         lastClickTime time.Time
82         lastLoc       Loc
83
84         // lastCutTime stores when the last ctrl+k was issued.
85         // It is used for clearing the clipboard to replace it with fresh cut lines.
86         lastCutTime time.Time
87
88         // freshClip returns true if the clipboard has never been pasted.
89         freshClip bool
90
91         // Was the last mouse event actually a double click?
92         // Useful for detecting triple clicks -- if a double click is detected
93         // but the last mouse event was actually a double click, it's a triple click
94         doubleClick bool
95         // Same here, just to keep track for mouse move events
96         tripleClick bool
97
98         // The cellview used for displaying and syntax highlighting
99         cellview *CellView
100
101         splitNode *LeafNode
102
103         // The scrollbar
104         scrollbar *ScrollBar
105
106         // Virtual terminal
107         term *Terminal
108 }
109
110 // NewView returns a new fullscreen view
111 func NewView(buf *Buffer) *View {
112         screenW, screenH := screen.Size()
113         return NewViewWidthHeight(buf, screenW, screenH)
114 }
115
116 // NewViewWidthHeight returns a new view with the specified width and height
117 // Note that w and h are raw column and row values
118 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
119         v := new(View)
120
121         v.x, v.y = 0, 0
122
123         v.Width = w
124         v.Height = h
125         v.cellview = new(CellView)
126
127         v.ToggleTabbar()
128
129         v.OpenBuffer(buf)
130
131         v.messages = make(map[string][]GutterMessage)
132
133         v.sline = &Statusline{
134                 view: v,
135         }
136
137         v.scrollbar = &ScrollBar{
138                 view: v,
139         }
140
141         if v.Buf.Settings["statusline"].(bool) {
142                 v.Height--
143         }
144
145         v.term = new(Terminal)
146
147         for pl := range loadedPlugins {
148                 _, err := Call(pl+".onViewOpen", v)
149                 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
150                         TermMessage(err)
151                         continue
152                 }
153         }
154
155         return v
156 }
157
158 // ToggleStatusLine creates an extra row for the statusline if necessary
159 func (v *View) ToggleStatusLine() {
160         if v.Buf.Settings["statusline"].(bool) {
161                 v.Height--
162         } else {
163                 v.Height++
164         }
165 }
166
167 // StartTerminal execs a command in this view
168 func (v *View) StartTerminal(execCmd []string) error {
169         err := v.term.Start(execCmd, v)
170         if err == nil {
171                 v.term.Resize(v.Width, v.Height)
172                 v.Type = vtTerm
173         }
174         return err
175 }
176
177 // CloseTerminal shuts down the tty running in this view
178 // and returns it to the default view type
179 func (v *View) CloseTerminal() {
180         v.term.Stop()
181 }
182
183 // ToggleTabbar creates an extra row for the tabbar if necessary
184 func (v *View) ToggleTabbar() {
185         if len(tabs) > 1 {
186                 if v.y == 0 {
187                         // Include one line for the tab bar at the top
188                         v.Height--
189                         v.y = 1
190                 }
191         } else {
192                 if v.y == 1 {
193                         v.y = 0
194                         v.Height++
195                 }
196         }
197 }
198
199 func (v *View) paste(clip string) {
200         leadingWS := GetLeadingWhitespace(v.Buf.Line(v.Cursor.Y))
201
202         if v.Cursor.HasSelection() {
203                 v.Cursor.DeleteSelection()
204                 v.Cursor.ResetSelection()
205         }
206         clip = strings.Replace(clip, "\n", "\n"+leadingWS, -1)
207         v.Buf.Insert(v.Cursor.Loc, clip)
208         // v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
209         v.freshClip = false
210         messenger.Message("Pasted clipboard")
211 }
212
213 // ScrollUp scrolls the view up n lines (if possible)
214 func (v *View) ScrollUp(n int) {
215         // Try to scroll by n but if it would overflow, scroll by 1
216         if v.Topline-n >= 0 {
217                 v.Topline -= n
218         } else if v.Topline > 0 {
219                 v.Topline--
220         }
221 }
222
223 // ScrollDown scrolls the view down n lines (if possible)
224 func (v *View) ScrollDown(n int) {
225         // Try to scroll by n but if it would overflow, scroll by 1
226         if v.Topline+n <= v.Buf.NumLines {
227                 v.Topline += n
228         } else if v.Topline < v.Buf.NumLines-1 {
229                 v.Topline++
230         }
231 }
232
233 // CanClose returns whether or not the view can be closed
234 // If there are unsaved changes, the user will be asked if the view can be closed
235 // causing them to lose the unsaved changes
236 func (v *View) CanClose() bool {
237         if v.Type == vtDefault && v.Buf.Modified() {
238                 var choice bool
239                 var canceled bool
240                 if v.Buf.Settings["autosave"].(bool) {
241                         choice = true
242                 } else {
243                         choice, canceled = messenger.YesNoPrompt("Save changes to " + v.Buf.GetName() + " before closing? (y,n,esc) ")
244                 }
245                 if !canceled {
246                         //if char == 'y' {
247                         if choice {
248                                 v.Save(true)
249                         }
250                 } else {
251                         return false
252                 }
253         }
254         return true
255 }
256
257 // OpenBuffer opens a new buffer in this view.
258 // This resets the topline, event handler and cursor.
259 func (v *View) OpenBuffer(buf *Buffer) {
260         screen.Clear()
261         v.CloseBuffer()
262         v.Buf = buf
263         v.Cursor = &buf.Cursor
264         v.Topline = 0
265         v.leftCol = 0
266         v.Cursor.ResetSelection()
267         v.Relocate()
268         v.Center(false)
269         v.messages = make(map[string][]GutterMessage)
270
271         // Set mouseReleased to true because we assume the mouse is not being pressed when
272         // the editor is opened
273         v.mouseReleased = true
274         // Set isOverwriteMode to false, because we assume we are in the default mode when editor
275         // is opened
276         v.isOverwriteMode = false
277         v.lastClickTime = time.Time{}
278
279         GlobalPluginCall("onBufferOpen", v.Buf)
280 }
281
282 // Open opens the given file in the view
283 func (v *View) Open(filename string) {
284         filename = ReplaceHome(filename)
285         file, err := os.Open(filename)
286         fileInfo, _ := os.Stat(filename)
287
288         if err == nil && fileInfo.IsDir() {
289                 messenger.Error(filename, " is a directory")
290                 return
291         }
292
293         defer file.Close()
294
295         var buf *Buffer
296         if err != nil {
297                 messenger.Message(err.Error())
298                 // File does not exist -- create an empty buffer with that name
299                 buf = NewBufferFromString("", filename)
300         } else {
301                 buf = NewBuffer(file, FSize(file), filename)
302         }
303         v.OpenBuffer(buf)
304 }
305
306 // CloseBuffer performs any closing functions on the buffer
307 func (v *View) CloseBuffer() {
308         if v.Buf != nil {
309                 v.Buf.Serialize()
310         }
311 }
312
313 // ReOpen reloads the current buffer
314 func (v *View) ReOpen() {
315         if v.CanClose() {
316                 screen.Clear()
317                 v.Buf.ReOpen()
318                 v.Relocate()
319         }
320 }
321
322 // HSplit opens a horizontal split with the given buffer
323 func (v *View) HSplit(buf *Buffer) {
324         i := 0
325         if v.Buf.Settings["splitbottom"].(bool) {
326                 i = 1
327         }
328         v.splitNode.HSplit(buf, v.Num+i)
329 }
330
331 // VSplit opens a vertical split with the given buffer
332 func (v *View) VSplit(buf *Buffer) {
333         i := 0
334         if v.Buf.Settings["splitright"].(bool) {
335                 i = 1
336         }
337         v.splitNode.VSplit(buf, v.Num+i)
338 }
339
340 // HSplitIndex opens a horizontal split with the given buffer at the given index
341 func (v *View) HSplitIndex(buf *Buffer, splitIndex int) {
342         v.splitNode.HSplit(buf, splitIndex)
343 }
344
345 // VSplitIndex opens a vertical split with the given buffer at the given index
346 func (v *View) VSplitIndex(buf *Buffer, splitIndex int) {
347         v.splitNode.VSplit(buf, splitIndex)
348 }
349
350 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
351 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
352         if !v.Buf.Settings["softwrap"].(bool) {
353                 if vy >= v.Buf.NumLines {
354                         vy = v.Buf.NumLines - 1
355                 }
356                 vx = v.Cursor.GetCharPosInLine(vy, vx)
357                 return vx, vy
358         }
359
360         screenX, screenY := 0, v.Topline
361         for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
362                 line := v.Buf.Line(lineN)
363                 if lineN >= v.Buf.NumLines {
364                         return 0, v.Buf.NumLines - 1
365                 }
366
367                 colN := 0
368                 for _, ch := range line {
369                         if screenX >= v.Width-v.lineNumOffset {
370                                 screenX = 0
371                                 screenY++
372                         }
373
374                         if screenX == vx && screenY == vy {
375                                 return colN, lineN
376                         }
377
378                         if ch == '\t' {
379                                 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
380                         }
381
382                         screenX++
383                         colN++
384                 }
385                 if screenY == vy {
386                         return colN, lineN
387                 }
388                 screenX = 0
389                 screenY++
390         }
391
392         return 0, 0
393 }
394
395 // Bottomline returns the line number of the lowest line in the view
396 // You might think that this is obviously just v.Topline + v.Height
397 // but if softwrap is enabled things get complicated since one buffer
398 // line can take up multiple lines in the view
399 func (v *View) Bottomline() int {
400         if !v.Buf.Settings["softwrap"].(bool) {
401                 return v.Topline + v.Height
402         }
403
404         screenX, screenY := 0, 0
405         numLines := 0
406         for lineN := v.Topline; lineN < v.Topline+v.Height; lineN++ {
407                 line := v.Buf.Line(lineN)
408
409                 colN := 0
410                 for _, ch := range line {
411                         if screenX >= v.Width-v.lineNumOffset {
412                                 screenX = 0
413                                 screenY++
414                         }
415
416                         if ch == '\t' {
417                                 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
418                         }
419
420                         screenX++
421                         colN++
422                 }
423                 screenX = 0
424                 screenY++
425                 numLines++
426
427                 if screenY >= v.Height {
428                         break
429                 }
430         }
431         return numLines + v.Topline
432 }
433
434 // Relocate moves the view window so that the cursor is in view
435 // This is useful if the user has scrolled far away, and then starts typing
436 func (v *View) Relocate() bool {
437         height := v.Bottomline() - v.Topline
438         ret := false
439         cy := v.Cursor.Y
440         scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
441         if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
442                 v.Topline = cy - scrollmargin
443                 ret = true
444         } else if cy < v.Topline {
445                 v.Topline = cy
446                 ret = true
447         }
448         if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
449                 v.Topline = cy - height + 1 + scrollmargin
450                 ret = true
451         } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
452                 v.Topline = v.Buf.NumLines - height
453                 ret = true
454         }
455
456         if !v.Buf.Settings["softwrap"].(bool) {
457                 cx := v.Cursor.GetVisualX()
458                 if cx < v.leftCol {
459                         v.leftCol = cx
460                         ret = true
461                 }
462                 if cx+v.lineNumOffset+1 > v.leftCol+v.Width {
463                         v.leftCol = cx - v.Width + v.lineNumOffset + 1
464                         ret = true
465                 }
466         }
467         return ret
468 }
469
470 // GetMouseClickLocation gets the location in the buffer from a mouse click
471 // on the screen
472 func (v *View) GetMouseClickLocation(x, y int) (int, int) {
473         x -= v.lineNumOffset - v.leftCol + v.x
474         y += v.Topline - v.y
475
476         if y-v.Topline > v.Height-1 {
477                 v.ScrollDown(1)
478                 y = v.Height + v.Topline - 1
479         }
480         if y < 0 {
481                 y = 0
482         }
483         if x < 0 {
484                 x = 0
485         }
486
487         newX, newY := v.GetSoftWrapLocation(x, y)
488         if newX > Count(v.Buf.Line(newY)) {
489                 newX = Count(v.Buf.Line(newY))
490         }
491
492         return newX, newY
493 }
494
495 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
496 // by a mouse click
497 func (v *View) MoveToMouseClick(x, y int) {
498         if y-v.Topline > v.Height-1 {
499                 v.ScrollDown(1)
500                 y = v.Height + v.Topline - 1
501         }
502         if y < 0 {
503                 y = 0
504         }
505         if x < 0 {
506                 x = 0
507         }
508
509         x, y = v.GetSoftWrapLocation(x, y)
510         if x > Count(v.Buf.Line(y)) {
511                 x = Count(v.Buf.Line(y))
512         }
513         v.Cursor.X = x
514         v.Cursor.Y = y
515         v.Cursor.LastVisualX = v.Cursor.GetVisualX()
516 }
517
518 // Execute actions executes the supplied actions
519 func (v *View) ExecuteActions(actions []func(*View, bool) bool) bool {
520         relocate := false
521         readonlyBindingsList := []string{"Delete", "Insert", "Backspace", "Cut", "Play", "Paste", "Move", "Add", "DuplicateLine", "Macro"}
522         for _, action := range actions {
523                 readonlyBindingsResult := false
524                 funcName := ShortFuncName(action)
525                 if v.Type.Readonly == true {
526                         // check for readonly and if true only let key bindings get called if they do not change the contents.
527                         for _, readonlyBindings := range readonlyBindingsList {
528                                 if strings.Contains(funcName, readonlyBindings) {
529                                         readonlyBindingsResult = true
530                                 }
531                         }
532                 }
533                 if !readonlyBindingsResult {
534                         // call the key binding
535                         relocate = action(v, true) || relocate
536                         // Macro
537                         if funcName != "ToggleMacro" && funcName != "PlayMacro" {
538                                 if recordingMacro {
539                                         curMacro = append(curMacro, action)
540                                 }
541                         }
542                 }
543         }
544
545         return relocate
546 }
547
548 // SetCursor sets the view's and buffer's cursor
549 func (v *View) SetCursor(c *Cursor) bool {
550         if c == nil {
551                 return false
552         }
553         v.Cursor = c
554         v.Buf.curCursor = c.Num
555
556         return true
557 }
558
559 // HandleEvent handles an event passed by the main loop
560 func (v *View) HandleEvent(event tcell.Event) {
561         if v.Type == vtTerm {
562                 v.term.HandleEvent(event)
563                 return
564         }
565
566         if v.Type == vtRaw {
567                 v.Buf.Insert(v.Cursor.Loc, reflect.TypeOf(event).String()[7:])
568                 v.Buf.Insert(v.Cursor.Loc, fmt.Sprintf(": %q\n", event.EscSeq()))
569
570                 switch e := event.(type) {
571                 case *tcell.EventKey:
572                         if e.Key() == tcell.KeyCtrlQ {
573                                 v.Quit(true)
574                         }
575                 }
576
577                 return
578         }
579
580         // This bool determines whether the view is relocated at the end of the function
581         // By default it's true because most events should cause a relocate
582         relocate := true
583
584         v.Buf.CheckModTime()
585
586         switch e := event.(type) {
587         case *tcell.EventRaw:
588                 for key, actions := range bindings {
589                         if key.keyCode == -1 {
590                                 if e.EscSeq() == key.escape {
591                                         for _, c := range v.Buf.cursors {
592                                                 ok := v.SetCursor(c)
593                                                 if !ok {
594                                                         break
595                                                 }
596                                                 relocate = false
597                                                 relocate = v.ExecuteActions(actions) || relocate
598                                         }
599                                         v.SetCursor(&v.Buf.Cursor)
600                                         v.Buf.MergeCursors()
601                                         break
602                                 }
603                         }
604                 }
605         case *tcell.EventKey:
606                 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
607                 isBinding := false
608                 for key, actions := range bindings {
609                         if e.Key() == key.keyCode {
610                                 if e.Key() == tcell.KeyRune {
611                                         if e.Rune() != key.r {
612                                                 continue
613                                         }
614                                 }
615                                 if e.Modifiers() == key.modifiers {
616                                         for _, c := range v.Buf.cursors {
617                                                 ok := v.SetCursor(c)
618                                                 if !ok {
619                                                         break
620                                                 }
621                                                 relocate = false
622                                                 isBinding = true
623                                                 relocate = v.ExecuteActions(actions) || relocate
624                                         }
625                                         v.SetCursor(&v.Buf.Cursor)
626                                         v.Buf.MergeCursors()
627                                         break
628                                 }
629                         }
630                 }
631
632                 if !isBinding && e.Key() == tcell.KeyRune {
633                         // Check viewtype if readonly don't insert a rune (readonly help and log view etc.)
634                         if v.Type.Readonly == false {
635                                 for _, c := range v.Buf.cursors {
636                                         v.SetCursor(c)
637
638                                         // Insert a character
639                                         if v.Cursor.HasSelection() {
640                                                 v.Cursor.DeleteSelection()
641                                                 v.Cursor.ResetSelection()
642                                         }
643
644                                         if v.isOverwriteMode {
645                                                 next := v.Cursor.Loc
646                                                 next.X++
647                                                 v.Buf.Replace(v.Cursor.Loc, next, string(e.Rune()))
648                                         } else {
649                                                 v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
650                                         }
651
652                                         for pl := range loadedPlugins {
653                                                 _, err := Call(pl+".onRune", string(e.Rune()), v)
654                                                 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
655                                                         TermMessage(err)
656                                                 }
657                                         }
658
659                                         if recordingMacro {
660                                                 curMacro = append(curMacro, e.Rune())
661                                         }
662                                 }
663                                 v.SetCursor(&v.Buf.Cursor)
664                         }
665                 }
666         case *tcell.EventPaste:
667                 // Check viewtype if readonly don't paste (readonly help and log view etc.)
668                 if v.Type.Readonly == false {
669                         if !PreActionCall("Paste", v) {
670                                 break
671                         }
672
673                         for _, c := range v.Buf.cursors {
674                                 v.SetCursor(c)
675                                 v.paste(e.Text())
676                         }
677                         v.SetCursor(&v.Buf.Cursor)
678
679                         PostActionCall("Paste", v)
680                 }
681         case *tcell.EventMouse:
682                 // Don't relocate for mouse events
683                 relocate = false
684
685                 button := e.Buttons()
686
687                 for key, actions := range bindings {
688                         if button == key.buttons && e.Modifiers() == key.modifiers {
689                                 for _, c := range v.Buf.cursors {
690                                         ok := v.SetCursor(c)
691                                         if !ok {
692                                                 break
693                                         }
694                                         relocate = v.ExecuteActions(actions) || relocate
695                                 }
696                                 v.SetCursor(&v.Buf.Cursor)
697                                 v.Buf.MergeCursors()
698                         }
699                 }
700
701                 for key, actions := range mouseBindings {
702                         if button == key.buttons && e.Modifiers() == key.modifiers {
703                                 for _, action := range actions {
704                                         action(v, true, e)
705                                 }
706                         }
707                 }
708
709                 switch button {
710                 case tcell.ButtonNone:
711                         // Mouse event with no click
712                         if !v.mouseReleased {
713                                 // Mouse was just released
714
715                                 x, y := e.Position()
716                                 x -= v.lineNumOffset - v.leftCol + v.x
717                                 y += v.Topline - v.y
718
719                                 // Relocating here isn't really necessary because the cursor will
720                                 // be in the right place from the last mouse event
721                                 // However, if we are running in a terminal that doesn't support mouse motion
722                                 // events, this still allows the user to make selections, except only after they
723                                 // release the mouse
724
725                                 if !v.doubleClick && !v.tripleClick {
726                                         v.MoveToMouseClick(x, y)
727                                         v.Cursor.SetSelectionEnd(v.Cursor.Loc)
728                                         v.Cursor.CopySelection("primary")
729                                 }
730                                 v.mouseReleased = true
731                         }
732                 }
733         }
734
735         if relocate {
736                 v.Relocate()
737                 // We run relocate again because there's a bug with relocating with softwrap
738                 // when for example you jump to the bottom of the buffer and it tries to
739                 // calculate where to put the topline so that the bottom line is at the bottom
740                 // of the terminal and it runs into problems with visual lines vs real lines.
741                 // This is (hopefully) a temporary solution
742                 v.Relocate()
743         }
744 }
745
746 func (v *View) mainCursor() bool {
747         return v.Buf.curCursor == len(v.Buf.cursors)-1
748 }
749
750 // GutterMessage creates a message in this view's gutter
751 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
752         lineN--
753         gutterMsg := GutterMessage{
754                 lineNum: lineN,
755                 msg:     msg,
756                 kind:    kind,
757         }
758         for _, v := range v.messages {
759                 for _, gmsg := range v {
760                         if gmsg.lineNum == lineN {
761                                 return
762                         }
763                 }
764         }
765         messages := v.messages[section]
766         v.messages[section] = append(messages, gutterMsg)
767 }
768
769 // ClearGutterMessages clears all gutter messages from a given section
770 func (v *View) ClearGutterMessages(section string) {
771         v.messages[section] = []GutterMessage{}
772 }
773
774 // ClearAllGutterMessages clears all the gutter messages
775 func (v *View) ClearAllGutterMessages() {
776         for k := range v.messages {
777                 v.messages[k] = []GutterMessage{}
778         }
779 }
780
781 // Opens the given help page in a new horizontal split
782 func (v *View) openHelp(helpPage string) {
783         if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
784                 TermMessage("Unable to load help text", helpPage, "\n", err)
785         } else {
786                 helpBuffer := NewBufferFromString(string(data), helpPage+".md")
787                 helpBuffer.name = "Help"
788
789                 if v.Type == vtHelp {
790                         v.OpenBuffer(helpBuffer)
791                 } else {
792                         v.HSplit(helpBuffer)
793                         CurView().Type = vtHelp
794                 }
795         }
796 }
797
798 // DisplayView draws the view to the screen
799 func (v *View) DisplayView() {
800         if v.Type == vtTerm {
801                 v.term.Display()
802                 return
803         }
804
805         if v.Buf.Settings["softwrap"].(bool) && v.leftCol != 0 {
806                 v.leftCol = 0
807         }
808
809         if v.Type == vtLog || v.Type == vtRaw {
810                 // Log or raw views should always follow the cursor...
811                 v.Relocate()
812         }
813
814         // We need to know the string length of the largest line number
815         // so we can pad appropriately when displaying line numbers
816         maxLineNumLength := len(strconv.Itoa(v.Buf.NumLines))
817
818         if v.Buf.Settings["ruler"] == true {
819                 // + 1 for the little space after the line number
820                 v.lineNumOffset = maxLineNumLength + 1
821         } else {
822                 v.lineNumOffset = 0
823         }
824
825         // We need to add to the line offset if there are gutter messages
826         var hasGutterMessages bool
827         for _, v := range v.messages {
828                 if len(v) > 0 {
829                         hasGutterMessages = true
830                 }
831         }
832         if hasGutterMessages {
833                 v.lineNumOffset += 2
834         }
835
836         divider := 0
837         if v.x != 0 {
838                 // One space for the extra split divider
839                 v.lineNumOffset++
840                 divider = 1
841         }
842
843         xOffset := v.x + v.lineNumOffset
844         yOffset := v.y
845
846         height := v.Height
847         width := v.Width
848         left := v.leftCol
849         top := v.Topline
850
851         v.cellview.Draw(v.Buf, top, height, left, width-v.lineNumOffset)
852
853         screenX := v.x
854         realLineN := top - 1
855         visualLineN := 0
856         var line []*Char
857         for visualLineN, line = range v.cellview.lines {
858                 var firstChar *Char
859                 if len(line) > 0 {
860                         firstChar = line[0]
861                 }
862
863                 var softwrapped bool
864                 if firstChar != nil {
865                         if firstChar.realLoc.Y == realLineN {
866                                 softwrapped = true
867                         }
868                         realLineN = firstChar.realLoc.Y
869                 } else {
870                         realLineN++
871                 }
872
873                 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
874                 if colorcolumn != 0 && xOffset+colorcolumn-v.leftCol < v.Width {
875                         style := GetColor("color-column")
876                         fg, _, _ := style.Decompose()
877                         st := defStyle.Background(fg)
878                         screen.SetContent(xOffset+colorcolumn-v.leftCol, yOffset+visualLineN, ' ', nil, st)
879                 }
880
881                 screenX = v.x
882
883                 // If there are gutter messages we need to display the '>>' symbol here
884                 if hasGutterMessages {
885                         // msgOnLine stores whether or not there is a gutter message on this line in particular
886                         msgOnLine := false
887                         for k := range v.messages {
888                                 for _, msg := range v.messages[k] {
889                                         if msg.lineNum == realLineN {
890                                                 msgOnLine = true
891                                                 gutterStyle := defStyle
892                                                 switch msg.kind {
893                                                 case GutterInfo:
894                                                         if style, ok := colorscheme["gutter-info"]; ok {
895                                                                 gutterStyle = style
896                                                         }
897                                                 case GutterWarning:
898                                                         if style, ok := colorscheme["gutter-warning"]; ok {
899                                                                 gutterStyle = style
900                                                         }
901                                                 case GutterError:
902                                                         if style, ok := colorscheme["gutter-error"]; ok {
903                                                                 gutterStyle = style
904                                                         }
905                                                 }
906                                                 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
907                                                 screenX++
908                                                 screen.SetContent(screenX, yOffset+visualLineN, '>', nil, gutterStyle)
909                                                 screenX++
910                                                 if v.Cursor.Y == realLineN && !messenger.hasPrompt {
911                                                         messenger.Message(msg.msg)
912                                                         messenger.gutterMessage = true
913                                                 }
914                                         }
915                                 }
916                         }
917                         // If there is no message on this line we just display an empty offset
918                         if !msgOnLine {
919                                 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
920                                 screenX++
921                                 screen.SetContent(screenX, yOffset+visualLineN, ' ', nil, defStyle)
922                                 screenX++
923                                 if v.Cursor.Y == realLineN && messenger.gutterMessage {
924                                         messenger.Reset()
925                                         messenger.gutterMessage = false
926                                 }
927                         }
928                 }
929
930                 lineNumStyle := defStyle
931                 if v.Buf.Settings["ruler"] == true {
932                         // Write the line number
933                         if style, ok := colorscheme["line-number"]; ok {
934                                 lineNumStyle = style
935                         }
936                         if style, ok := colorscheme["current-line-number"]; ok {
937                                 if realLineN == v.Cursor.Y && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() {
938                                         lineNumStyle = style
939                                 }
940                         }
941
942                         lineNum := strconv.Itoa(realLineN + 1)
943
944                         // Write the spaces before the line number if necessary
945                         for i := 0; i < maxLineNumLength-len(lineNum); i++ {
946                                 screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
947                                 screenX++
948                         }
949                         if softwrapped && visualLineN != 0 {
950                                 // Pad without the line number because it was written on the visual line before
951                                 for range lineNum {
952                                         screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
953                                         screenX++
954                                 }
955                         } else {
956                                 // Write the actual line number
957                                 for _, ch := range lineNum {
958                                         screen.SetContent(screenX+divider, yOffset+visualLineN, ch, nil, lineNumStyle)
959                                         screenX++
960                                 }
961                         }
962
963                         // Write the extra space
964                         screen.SetContent(screenX+divider, yOffset+visualLineN, ' ', nil, lineNumStyle)
965                         screenX++
966                 }
967
968                 var lastChar *Char
969                 cursorSet := false
970                 for _, char := range line {
971                         if char != nil {
972                                 lineStyle := char.style
973
974                                 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
975                                 if colorcolumn != 0 && char.visualLoc.X == colorcolumn {
976                                         style := GetColor("color-column")
977                                         fg, _, _ := style.Decompose()
978                                         lineStyle = lineStyle.Background(fg)
979                                 }
980
981                                 charLoc := char.realLoc
982                                 for _, c := range v.Buf.cursors {
983                                         v.SetCursor(c)
984                                         if v.Cursor.HasSelection() &&
985                                                 (charLoc.GreaterEqual(v.Cursor.CurSelection[0]) && charLoc.LessThan(v.Cursor.CurSelection[1]) ||
986                                                         charLoc.LessThan(v.Cursor.CurSelection[0]) && charLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
987                                                 // The current character is selected
988                                                 lineStyle = defStyle.Reverse(true)
989
990                                                 if style, ok := colorscheme["selection"]; ok {
991                                                         lineStyle = style
992                                                 }
993                                         }
994                                 }
995                                 v.SetCursor(&v.Buf.Cursor)
996
997                                 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
998                                         !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
999                                         style := GetColor("cursor-line")
1000                                         fg, _, _ := style.Decompose()
1001                                         lineStyle = lineStyle.Background(fg)
1002                                 }
1003
1004                                 screen.SetContent(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, char.drawChar, nil, lineStyle)
1005
1006                                 for i, c := range v.Buf.cursors {
1007                                         v.SetCursor(c)
1008                                         if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
1009                                                 v.Cursor.Y == char.realLoc.Y && v.Cursor.X == char.realLoc.X && (!cursorSet || i != 0) {
1010                                                 ShowMultiCursor(xOffset+char.visualLoc.X, yOffset+char.visualLoc.Y, i)
1011                                                 cursorSet = true
1012                                         }
1013                                 }
1014                                 v.SetCursor(&v.Buf.Cursor)
1015
1016                                 lastChar = char
1017                         }
1018                 }
1019
1020                 lastX := 0
1021                 var realLoc Loc
1022                 var visualLoc Loc
1023                 var cx, cy int
1024                 if lastChar != nil {
1025                         lastX = xOffset + lastChar.visualLoc.X + lastChar.width
1026                         for i, c := range v.Buf.cursors {
1027                                 v.SetCursor(c)
1028                                 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
1029                                         v.Cursor.Y == lastChar.realLoc.Y && v.Cursor.X == lastChar.realLoc.X+1 {
1030                                         ShowMultiCursor(lastX, yOffset+lastChar.visualLoc.Y, i)
1031                                         cx, cy = lastX, yOffset+lastChar.visualLoc.Y
1032                                 }
1033                         }
1034                         v.SetCursor(&v.Buf.Cursor)
1035                         realLoc = Loc{lastChar.realLoc.X + 1, realLineN}
1036                         visualLoc = Loc{lastX - xOffset, lastChar.visualLoc.Y}
1037                 } else if len(line) == 0 {
1038                         for i, c := range v.Buf.cursors {
1039                                 v.SetCursor(c)
1040                                 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() &&
1041                                         v.Cursor.Y == realLineN {
1042                                         ShowMultiCursor(xOffset, yOffset+visualLineN, i)
1043                                         cx, cy = xOffset, yOffset+visualLineN
1044                                 }
1045                         }
1046                         v.SetCursor(&v.Buf.Cursor)
1047                         lastX = xOffset
1048                         realLoc = Loc{0, realLineN}
1049                         visualLoc = Loc{0, visualLineN}
1050                 }
1051
1052                 if v.Cursor.HasSelection() &&
1053                         (realLoc.GreaterEqual(v.Cursor.CurSelection[0]) && realLoc.LessThan(v.Cursor.CurSelection[1]) ||
1054                                 realLoc.LessThan(v.Cursor.CurSelection[0]) && realLoc.GreaterEqual(v.Cursor.CurSelection[1])) {
1055                         // The current character is selected
1056                         selectStyle := defStyle.Reverse(true)
1057
1058                         if style, ok := colorscheme["selection"]; ok {
1059                                 selectStyle = style
1060                         }
1061                         screen.SetContent(xOffset+visualLoc.X, yOffset+visualLoc.Y, ' ', nil, selectStyle)
1062                 }
1063
1064                 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num &&
1065                         !v.Cursor.HasSelection() && v.Cursor.Y == realLineN {
1066                         for i := lastX; i < xOffset+v.Width-v.lineNumOffset; i++ {
1067                                 style := GetColor("cursor-line")
1068                                 fg, _, _ := style.Decompose()
1069                                 style = style.Background(fg)
1070                                 if !(tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && i == cx && yOffset+visualLineN == cy) {
1071                                         screen.SetContent(i, yOffset+visualLineN, ' ', nil, style)
1072                                 }
1073                         }
1074                 }
1075         }
1076
1077         if divider != 0 {
1078                 dividerStyle := defStyle
1079                 if style, ok := colorscheme["divider"]; ok {
1080                         dividerStyle = style
1081                 }
1082                 for i := 0; i < v.Height; i++ {
1083                         screen.SetContent(v.x, yOffset+i, '|', nil, dividerStyle.Reverse(true))
1084                 }
1085         }
1086 }
1087
1088 // ShowMultiCursor will display a cursor at a location
1089 // If i == 0 then the terminal cursor will be used
1090 // Otherwise a fake cursor will be drawn at the position
1091 func ShowMultiCursor(x, y, i int) {
1092         if i == 0 {
1093                 screen.ShowCursor(x, y)
1094         } else {
1095                 r, _, _, _ := screen.GetContent(x, y)
1096                 screen.SetContent(x, y, r, nil, defStyle.Reverse(true))
1097         }
1098 }
1099
1100 // Display renders the view, the cursor, and statusline
1101 func (v *View) Display() {
1102         if globalSettings["termtitle"].(bool) {
1103                 screen.SetTitle("micro: " + v.Buf.GetName())
1104         }
1105         v.DisplayView()
1106         // Don't draw the cursor if it is out of the viewport or if it has a selection
1107         if v.Num == tabs[curTab].CurView && (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.Height-1 || v.Cursor.HasSelection()) {
1108                 screen.HideCursor()
1109         }
1110         _, screenH := screen.Size()
1111
1112         if v.Buf.Settings["scrollbar"].(bool) {
1113                 v.scrollbar.Display()
1114         }
1115
1116         if v.Buf.Settings["statusline"].(bool) {
1117                 v.sline.Display()
1118         } else if (v.y + v.Height) != screenH-1 {
1119                 for x := 0; x < v.Width; x++ {
1120                         screen.SetContent(v.x+x, v.y+v.Height, '-', nil, defStyle.Reverse(true))
1121                 }
1122         }
1123 }