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