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