]> git.lizzy.rs Git - micro.git/blob - cmd/micro/view.go
Merge pull request #507 from NicolaiSoeborg/master
[micro.git] / cmd / micro / view.go
1 package main
2
3 import (
4         "os"
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 := os.Open(filename)
246         defer file.Close()
247
248         var buf *Buffer
249         if err != nil {
250                 messenger.Message(err.Error())
251                 // File does not exist -- create an empty buffer with that name
252                 buf = NewBuffer(strings.NewReader(""), filename)
253         } else {
254                 buf = NewBuffer(file, filename)
255         }
256         v.OpenBuffer(buf)
257 }
258
259 // CloseBuffer performs any closing functions on the buffer
260 func (v *View) CloseBuffer() {
261         if v.Buf != nil {
262                 v.Buf.Serialize()
263         }
264 }
265
266 // ReOpen reloads the current buffer
267 func (v *View) ReOpen() {
268         if v.CanClose() {
269                 screen.Clear()
270                 v.Buf.ReOpen()
271                 v.Relocate()
272                 v.matches = Match(v)
273         }
274 }
275
276 // HSplit opens a horizontal split with the given buffer
277 func (v *View) HSplit(buf *Buffer) {
278         i := 0
279         if v.Buf.Settings["splitBottom"].(bool) {
280                 i = 1
281         }
282         v.splitNode.HSplit(buf, v.Num+i)
283 }
284
285 // VSplit opens a vertical split with the given buffer
286 func (v *View) VSplit(buf *Buffer) {
287         i := 0
288         if v.Buf.Settings["splitRight"].(bool) {
289                 i = 1
290         }
291         v.splitNode.VSplit(buf, v.Num+i)
292 }
293
294 // HSplitIndex opens a horizontal split with the given buffer at the given index
295 func (v *View) HSplitIndex(buf *Buffer, splitIndex int) {
296         v.splitNode.HSplit(buf, splitIndex)
297 }
298
299 // VSplitIndex opens a vertical split with the given buffer at the given index
300 func (v *View) VSplitIndex(buf *Buffer, splitIndex int) {
301         v.splitNode.VSplit(buf, splitIndex)
302 }
303
304 // GetSoftWrapLocation gets the location of a visual click on the screen and converts it to col,line
305 func (v *View) GetSoftWrapLocation(vx, vy int) (int, int) {
306         if !v.Buf.Settings["softwrap"].(bool) {
307                 vx = v.Cursor.GetCharPosInLine(vy, vx)
308                 return vx, vy
309         }
310
311         screenX, screenY := 0, v.Topline
312         for lineN := v.Topline; lineN < v.Bottomline(); lineN++ {
313                 line := v.Buf.Line(lineN)
314
315                 colN := 0
316                 for _, ch := range line {
317                         if screenX >= v.Width-v.lineNumOffset {
318                                 screenX = 0
319                                 screenY++
320                         }
321
322                         if screenX == vx && screenY == vy {
323                                 return colN, lineN
324                         }
325
326                         if ch == '\t' {
327                                 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
328                         }
329
330                         screenX++
331                         colN++
332                 }
333                 if screenY == vy {
334                         return colN, lineN
335                 }
336                 screenX = 0
337                 screenY++
338         }
339
340         return 0, 0
341 }
342
343 func (v *View) Bottomline() int {
344         if !v.Buf.Settings["softwrap"].(bool) {
345                 return v.Topline + v.Height
346         }
347
348         screenX, screenY := 0, 0
349         numLines := 0
350         for lineN := v.Topline; lineN < v.Topline+v.Height; lineN++ {
351                 line := v.Buf.Line(lineN)
352
353                 colN := 0
354                 for _, ch := range line {
355                         if screenX >= v.Width-v.lineNumOffset {
356                                 screenX = 0
357                                 screenY++
358                         }
359
360                         if ch == '\t' {
361                                 screenX += int(v.Buf.Settings["tabsize"].(float64)) - 1
362                         }
363
364                         screenX++
365                         colN++
366                 }
367                 screenX = 0
368                 screenY++
369                 numLines++
370
371                 if screenY >= v.Height {
372                         break
373                 }
374         }
375         return numLines + v.Topline
376 }
377
378 // Relocate moves the view window so that the cursor is in view
379 // This is useful if the user has scrolled far away, and then starts typing
380 func (v *View) Relocate() bool {
381         height := v.Bottomline() - v.Topline
382         ret := false
383         cy := v.Cursor.Y
384         scrollmargin := int(v.Buf.Settings["scrollmargin"].(float64))
385         if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
386                 v.Topline = cy - scrollmargin
387                 ret = true
388         } else if cy < v.Topline {
389                 v.Topline = cy
390                 ret = true
391         }
392         if cy > v.Topline+height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
393                 v.Topline = cy - height + 1 + scrollmargin
394                 ret = true
395         } else if cy >= v.Buf.NumLines-scrollmargin && cy > height {
396                 v.Topline = v.Buf.NumLines - height
397                 ret = true
398         }
399
400         if !v.Buf.Settings["softwrap"].(bool) {
401                 cx := v.Cursor.GetVisualX()
402                 if cx < v.leftCol {
403                         v.leftCol = cx
404                         ret = true
405                 }
406                 if cx+v.lineNumOffset+1 > v.leftCol+v.Width {
407                         v.leftCol = cx - v.Width + v.lineNumOffset + 1
408                         ret = true
409                 }
410         }
411         return ret
412 }
413
414 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
415 // by a mouse click
416 func (v *View) MoveToMouseClick(x, y int) {
417         if y-v.Topline > v.Height-1 {
418                 v.ScrollDown(1)
419                 y = v.Height + v.Topline - 1
420         }
421         if y < 0 {
422                 y = 0
423         }
424         if x < 0 {
425                 x = 0
426         }
427
428         x, y = v.GetSoftWrapLocation(x, y)
429         // x = v.Cursor.GetCharPosInLine(y, x)
430         if y > v.Buf.NumLines {
431                 y = v.Buf.NumLines - 1
432         }
433         if x > Count(v.Buf.Line(y)) {
434                 x = Count(v.Buf.Line(y))
435         }
436         v.Cursor.X = x
437         v.Cursor.Y = y
438         v.Cursor.LastVisualX = v.Cursor.GetVisualX()
439 }
440
441 // HandleEvent handles an event passed by the main loop
442 func (v *View) HandleEvent(event tcell.Event) {
443         // This bool determines whether the view is relocated at the end of the function
444         // By default it's true because most events should cause a relocate
445         relocate := true
446
447         v.Buf.CheckModTime()
448
449         switch e := event.(type) {
450         case *tcell.EventResize:
451                 // Window resized
452                 tabs[v.TabNum].Resize()
453         case *tcell.EventKey:
454                 // Check first if input is a key binding, if it is we 'eat' the input and don't insert a rune
455                 isBinding := false
456                 if e.Key() != tcell.KeyRune || e.Modifiers() != 0 {
457                         for key, actions := range bindings {
458                                 if e.Key() == key.keyCode {
459                                         if e.Key() == tcell.KeyRune {
460                                                 if e.Rune() != key.r {
461                                                         continue
462                                                 }
463                                         }
464                                         if e.Modifiers() == key.modifiers {
465                                                 relocate = false
466                                                 isBinding = true
467                                                 for _, action := range actions {
468                                                         relocate = action(v, true) || relocate
469                                                         funcName := FuncName(action)
470                                                         if funcName != "main.(*View).ToggleMacro" && funcName != "main.(*View).PlayMacro" {
471                                                                 if recordingMacro {
472                                                                         curMacro = append(curMacro, action)
473                                                                 }
474                                                         }
475                                                 }
476                                                 break
477                                         }
478                                 }
479                         }
480                 }
481                 if !isBinding && e.Key() == tcell.KeyRune {
482                         // Insert a character
483                         if v.Cursor.HasSelection() {
484                                 v.Cursor.DeleteSelection()
485                                 v.Cursor.ResetSelection()
486                         }
487                         v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
488                         v.Cursor.Right()
489
490                         for pl := range loadedPlugins {
491                                 _, err := Call(pl+".onRune", string(e.Rune()), v)
492                                 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
493                                         TermMessage(err)
494                                 }
495                         }
496
497                         if recordingMacro {
498                                 curMacro = append(curMacro, e.Rune())
499                         }
500                 }
501         case *tcell.EventPaste:
502                 if !PreActionCall("Paste", v) {
503                         break
504                 }
505
506                 v.paste(e.Text())
507
508                 PostActionCall("Paste", v)
509         case *tcell.EventMouse:
510                 x, y := e.Position()
511                 x -= v.lineNumOffset - v.leftCol + v.x
512                 y += v.Topline - v.y
513                 // Don't relocate for mouse events
514                 relocate = false
515
516                 button := e.Buttons()
517
518                 switch button {
519                 case tcell.Button1:
520                         // Left click
521                         if v.mouseReleased {
522                                 v.MoveToMouseClick(x, y)
523                                 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
524                                         if v.doubleClick {
525                                                 // Triple click
526                                                 v.lastClickTime = time.Now()
527
528                                                 v.tripleClick = true
529                                                 v.doubleClick = false
530
531                                                 v.Cursor.SelectLine()
532                                         } else {
533                                                 // Double click
534                                                 v.lastClickTime = time.Now()
535
536                                                 v.doubleClick = true
537                                                 v.tripleClick = false
538
539                                                 v.Cursor.SelectWord()
540                                         }
541                                 } else {
542                                         v.doubleClick = false
543                                         v.tripleClick = false
544                                         v.lastClickTime = time.Now()
545
546                                         v.Cursor.OrigSelection[0] = v.Cursor.Loc
547                                         v.Cursor.CurSelection[0] = v.Cursor.Loc
548                                         v.Cursor.CurSelection[1] = v.Cursor.Loc
549                                 }
550                                 v.mouseReleased = false
551                         } else if !v.mouseReleased {
552                                 v.MoveToMouseClick(x, y)
553                                 if v.tripleClick {
554                                         v.Cursor.AddLineToSelection()
555                                 } else if v.doubleClick {
556                                         v.Cursor.AddWordToSelection()
557                                 } else {
558                                         v.Cursor.SetSelectionEnd(v.Cursor.Loc)
559                                 }
560                         }
561                 case tcell.Button2:
562                         // Middle mouse button was clicked,
563                         // We should paste primary
564                         v.PastePrimary(true)
565                 case tcell.ButtonNone:
566                         // Mouse event with no click
567                         if !v.mouseReleased {
568                                 // Mouse was just released
569
570                                 // Relocating here isn't really necessary because the cursor will
571                                 // be in the right place from the last mouse event
572                                 // However, if we are running in a terminal that doesn't support mouse motion
573                                 // events, this still allows the user to make selections, except only after they
574                                 // release the mouse
575
576                                 if !v.doubleClick && !v.tripleClick {
577                                         v.MoveToMouseClick(x, y)
578                                         v.Cursor.SetSelectionEnd(v.Cursor.Loc)
579                                 }
580                                 v.mouseReleased = true
581                         }
582                 case tcell.WheelUp:
583                         // Scroll up
584                         scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
585                         v.ScrollUp(scrollspeed)
586                 case tcell.WheelDown:
587                         // Scroll down
588                         scrollspeed := int(v.Buf.Settings["scrollspeed"].(float64))
589                         v.ScrollDown(scrollspeed)
590                 }
591         }
592
593         if relocate {
594                 v.Relocate()
595         }
596 }
597
598 // GutterMessage creates a message in this view's gutter
599 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
600         lineN--
601         gutterMsg := GutterMessage{
602                 lineNum: lineN,
603                 msg:     msg,
604                 kind:    kind,
605         }
606         for _, v := range v.messages {
607                 for _, gmsg := range v {
608                         if gmsg.lineNum == lineN {
609                                 return
610                         }
611                 }
612         }
613         messages := v.messages[section]
614         v.messages[section] = append(messages, gutterMsg)
615 }
616
617 // ClearGutterMessages clears all gutter messages from a given section
618 func (v *View) ClearGutterMessages(section string) {
619         v.messages[section] = []GutterMessage{}
620 }
621
622 // ClearAllGutterMessages clears all the gutter messages
623 func (v *View) ClearAllGutterMessages() {
624         for k := range v.messages {
625                 v.messages[k] = []GutterMessage{}
626         }
627 }
628
629 // Opens the given help page in a new horizontal split
630 func (v *View) openHelp(helpPage string) {
631         if data, err := FindRuntimeFile(RTHelp, helpPage).Data(); err != nil {
632                 TermMessage("Unable to load help text", helpPage, "\n", err)
633         } else {
634                 helpBuffer := NewBuffer(strings.NewReader(string(data)), helpPage+".md")
635                 helpBuffer.name = "Help"
636
637                 if v.Type == vtHelp {
638                         v.OpenBuffer(helpBuffer)
639                 } else {
640                         v.HSplit(helpBuffer)
641                         CurView().Type = vtHelp
642                 }
643         }
644 }
645
646 func (v *View) drawCell(x, y int, ch rune, combc []rune, style tcell.Style) {
647         if x >= v.x && x < v.x+v.Width && y >= v.y && y < v.y+v.Height {
648                 screen.SetContent(x, y, ch, combc, style)
649         }
650 }
651
652 // DisplayView renders the view to the screen
653 func (v *View) DisplayView() {
654         if v.Type == vtLog {
655                 // Log views should always follow the cursor...
656                 v.Relocate()
657         }
658
659         if v.Buf.Settings["syntax"].(bool) {
660                 v.matches = Match(v)
661         }
662
663         // The charNum we are currently displaying
664         // starts at the start of the viewport
665         charNum := Loc{0, v.Topline}
666
667         // Convert the length of buffer to a string, and get the length of the string
668         // We are going to have to offset by that amount
669         maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
670
671         if v.Buf.Settings["ruler"] == true {
672                 // + 1 for the little space after the line number
673                 v.lineNumOffset = maxLineLength + 1
674         } else {
675                 v.lineNumOffset = 0
676         }
677
678         // We need to add to the line offset if there are gutter messages
679         var hasGutterMessages bool
680         for _, v := range v.messages {
681                 if len(v) > 0 {
682                         hasGutterMessages = true
683                 }
684         }
685         if hasGutterMessages {
686                 v.lineNumOffset += 2
687         }
688
689         if v.x != 0 {
690                 // One space for the extra split divider
691                 v.lineNumOffset++
692         }
693
694         // These represent the current screen coordinates
695         screenX, screenY := v.x, v.y-1
696
697         highlightStyle := defStyle
698         curLineN := 0
699
700         // ViewLine is the current line from the top of the viewport
701         for viewLine := 0; viewLine < v.Height; viewLine++ {
702                 screenY++
703                 screenX = v.x
704
705                 // This is the current line number of the buffer that we are drawing
706                 curLineN = viewLine + v.Topline
707
708                 if screenY-v.y >= v.Height {
709                         break
710                 }
711
712                 if v.x != 0 {
713                         // Draw the split divider
714                         v.drawCell(screenX, screenY, '|', nil, defStyle.Reverse(true))
715                         screenX++
716                 }
717
718                 // If the buffer is smaller than the view height we have to clear all this space
719                 if curLineN >= v.Buf.NumLines {
720                         for i := screenX; i < v.x+v.Width; i++ {
721                                 v.drawCell(i, screenY, ' ', nil, defStyle)
722                         }
723
724                         continue
725                 }
726                 line := v.Buf.Line(curLineN)
727
728                 // If there are gutter messages we need to display the '>>' symbol here
729                 if hasGutterMessages {
730                         // msgOnLine stores whether or not there is a gutter message on this line in particular
731                         msgOnLine := false
732                         for k := range v.messages {
733                                 for _, msg := range v.messages[k] {
734                                         if msg.lineNum == curLineN {
735                                                 msgOnLine = true
736                                                 gutterStyle := defStyle
737                                                 switch msg.kind {
738                                                 case GutterInfo:
739                                                         if style, ok := colorscheme["gutter-info"]; ok {
740                                                                 gutterStyle = style
741                                                         }
742                                                 case GutterWarning:
743                                                         if style, ok := colorscheme["gutter-warning"]; ok {
744                                                                 gutterStyle = style
745                                                         }
746                                                 case GutterError:
747                                                         if style, ok := colorscheme["gutter-error"]; ok {
748                                                                 gutterStyle = style
749                                                         }
750                                                 }
751                                                 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
752                                                 screenX++
753                                                 v.drawCell(screenX, screenY, '>', nil, gutterStyle)
754                                                 screenX++
755                                                 if v.Cursor.Y == curLineN && !messenger.hasPrompt {
756                                                         messenger.Message(msg.msg)
757                                                         messenger.gutterMessage = true
758                                                 }
759                                         }
760                                 }
761                         }
762                         // If there is no message on this line we just display an empty offset
763                         if !msgOnLine {
764                                 v.drawCell(screenX, screenY, ' ', nil, defStyle)
765                                 screenX++
766                                 v.drawCell(screenX, screenY, ' ', nil, defStyle)
767                                 screenX++
768                                 if v.Cursor.Y == curLineN && messenger.gutterMessage {
769                                         messenger.Reset()
770                                         messenger.gutterMessage = false
771                                 }
772                         }
773                 }
774
775                 lineNumStyle := defStyle
776                 if v.Buf.Settings["ruler"] == true {
777                         // Write the line number
778                         if style, ok := colorscheme["line-number"]; ok {
779                                 lineNumStyle = style
780                         }
781                         if style, ok := colorscheme["current-line-number"]; ok {
782                                 if curLineN == v.Cursor.Y && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() {
783                                         lineNumStyle = style
784                                 }
785                         }
786
787                         lineNum := strconv.Itoa(curLineN + 1)
788
789                         // Write the spaces before the line number if necessary
790                         for i := 0; i < maxLineLength-len(lineNum); i++ {
791                                 v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
792                                 screenX++
793                         }
794                         // Write the actual line number
795                         for _, ch := range lineNum {
796                                 v.drawCell(screenX, screenY, ch, nil, lineNumStyle)
797                                 screenX++
798                         }
799
800                         // Write the extra space
801                         v.drawCell(screenX, screenY, ' ', nil, lineNumStyle)
802                         screenX++
803                 }
804
805                 // Now we actually draw the line
806                 colN := 0
807                 strWidth := 0
808                 tabSize := int(v.Buf.Settings["tabsize"].(float64))
809                 for _, ch := range line {
810                         if v.Buf.Settings["softwrap"].(bool) {
811                                 if screenX-v.x >= v.Width {
812                                         screenY++
813                                         for i := 0; i < v.lineNumOffset; i++ {
814                                                 screen.SetContent(v.x+i, screenY, ' ', nil, lineNumStyle)
815                                         }
816                                         screenX = v.x + v.lineNumOffset
817                                 }
818                         }
819
820                         if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN && colN == v.Cursor.X {
821                                 v.DisplayCursor(screenX-v.leftCol, screenY)
822                         }
823
824                         lineStyle := defStyle
825
826                         if v.Buf.Settings["syntax"].(bool) {
827                                 // Syntax highlighting is enabled
828                                 highlightStyle = v.matches[viewLine][colN]
829                         }
830
831                         if v.Cursor.HasSelection() &&
832                                 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
833                                         charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
834                                 // The current character is selected
835                                 lineStyle = defStyle.Reverse(true)
836
837                                 if style, ok := colorscheme["selection"]; ok {
838                                         lineStyle = style
839                                 }
840                         } else {
841                                 lineStyle = highlightStyle
842                         }
843
844                         // We need to display the background of the linestyle with the correct color if cursorline is enabled
845                         // and this is the current view and there is no selection on this line and the cursor is on this line
846                         if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
847                                 if style, ok := colorscheme["cursor-line"]; ok {
848                                         fg, _, _ := style.Decompose()
849                                         lineStyle = lineStyle.Background(fg)
850                                 }
851                         }
852
853                         if ch == '\t' {
854                                 // If the character we are displaying is a tab, we need to do a bunch of special things
855
856                                 // First the user may have configured an `indent-char` to be displayed to show that this
857                                 // is a tab character
858                                 lineIndentStyle := defStyle
859                                 if style, ok := colorscheme["indent-char"]; ok && v.Buf.Settings["indentchar"].(string) != " " {
860                                         lineIndentStyle = style
861                                 }
862                                 if v.Cursor.HasSelection() &&
863                                         (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
864                                                 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
865
866                                         lineIndentStyle = defStyle.Reverse(true)
867
868                                         if style, ok := colorscheme["selection"]; ok {
869                                                 lineIndentStyle = style
870                                         }
871                                 }
872                                 if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
873                                         if style, ok := colorscheme["cursor-line"]; ok {
874                                                 fg, _, _ := style.Decompose()
875                                                 lineIndentStyle = lineIndentStyle.Background(fg)
876                                         }
877                                 }
878                                 // Here we get the indent char
879                                 indentChar := []rune(v.Buf.Settings["indentchar"].(string))
880                                 if screenX-v.x-v.leftCol >= v.lineNumOffset {
881                                         v.drawCell(screenX-v.leftCol, screenY, indentChar[0], nil, lineIndentStyle)
882                                 }
883                                 // Now the tab has to be displayed as a bunch of spaces
884                                 visLoc := strWidth
885                                 remainder := tabSize - (visLoc % tabSize)
886                                 for i := 0; i < remainder-1; i++ {
887                                         screenX++
888                                         if screenX-v.x-v.leftCol >= v.lineNumOffset {
889                                                 v.drawCell(screenX-v.leftCol, screenY, ' ', nil, lineStyle)
890                                         }
891                                 }
892                                 strWidth += remainder
893                         } else if runewidth.RuneWidth(ch) > 1 {
894                                 if screenX-v.x-v.leftCol >= v.lineNumOffset {
895                                         v.drawCell(screenX, screenY, ch, nil, lineStyle)
896                                 }
897                                 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
898                                         screenX++
899                                         if screenX-v.x-v.leftCol >= v.lineNumOffset {
900                                                 v.drawCell(screenX-v.leftCol, screenY, '<', nil, lineStyle)
901                                         }
902                                 }
903                                 strWidth += StringWidth(string(ch), tabSize)
904                         } else {
905                                 if screenX-v.x-v.leftCol >= v.lineNumOffset {
906                                         v.drawCell(screenX-v.leftCol, screenY, ch, nil, lineStyle)
907                                 }
908                                 strWidth += StringWidth(string(ch), tabSize)
909                         }
910                         charNum = charNum.Move(1, v.Buf)
911                         screenX++
912                         colN++
913                 }
914                 // Here we are at a newline
915
916                 if tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN && colN == v.Cursor.X {
917                         v.DisplayCursor(screenX-v.leftCol, screenY)
918                 }
919
920                 // The newline may be selected, in which case we should draw the selection style
921                 // with a space to represent it
922                 if v.Cursor.HasSelection() &&
923                         (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
924                                 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
925
926                         selectStyle := defStyle.Reverse(true)
927
928                         if style, ok := colorscheme["selection"]; ok {
929                                 selectStyle = style
930                         }
931                         v.drawCell(screenX, screenY, ' ', nil, selectStyle)
932                         screenX++
933                 }
934
935                 charNum = charNum.Move(1, v.Buf)
936
937                 for i := 0; i < v.Width; i++ {
938                         lineStyle := defStyle
939                         if v.Buf.Settings["cursorline"].(bool) && tabs[curTab].CurView == v.Num && !v.Cursor.HasSelection() && v.Cursor.Y == curLineN {
940                                 if style, ok := colorscheme["cursor-line"]; ok {
941                                         fg, _, _ := style.Decompose()
942                                         lineStyle = lineStyle.Background(fg)
943                                 }
944                         }
945                         if screenX-v.x-v.leftCol+i >= v.lineNumOffset {
946                                 colorcolumn := int(v.Buf.Settings["colorcolumn"].(float64))
947                                 if colorcolumn != 0 && screenX-v.lineNumOffset+i == colorcolumn-1 {
948                                         if style, ok := colorscheme["color-column"]; ok {
949                                                 fg, _, _ := style.Decompose()
950                                                 lineStyle = lineStyle.Background(fg)
951                                         }
952                                 }
953                                 v.drawCell(screenX-v.leftCol+i, screenY, ' ', nil, lineStyle)
954                         }
955                 }
956         }
957 }
958
959 // DisplayCursor draws the current buffer's cursor to the screen
960 func (v *View) DisplayCursor(x, y int) {
961         // screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, y)
962         screen.ShowCursor(x, y)
963 }
964
965 // Display renders the view, the cursor, and statusline
966 func (v *View) Display() {
967         v.DisplayView()
968         // Don't draw the cursor if it is out of the viewport or if it has a selection
969         if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.Height-1) || v.Cursor.HasSelection() {
970                 screen.HideCursor()
971         }
972         _, screenH := screen.Size()
973         if v.Buf.Settings["statusline"].(bool) {
974                 v.sline.Display()
975         } else if (v.y + v.Height) != screenH-1 {
976                 for x := 0; x < v.Width; x++ {
977                         screen.SetContent(v.x+x, v.y+v.Height, '-', nil, defStyle.Reverse(true))
978                 }
979         }
980 }