]> git.lizzy.rs Git - micro.git/blob - cmd/micro/view.go
Also allow ModShift to be on for windows terminals
[micro.git] / cmd / micro / view.go
1 package main
2
3 import (
4         "reflect"
5         "runtime"
6         "strconv"
7         "strings"
8         "time"
9
10         "github.com/mattn/go-runewidth"
11         "github.com/zyedidia/tcell"
12 )
13
14 // The View struct stores information about a view into a buffer.
15 // It stores information about the cursor, and the viewport
16 // that the user sees the buffer from.
17 type View struct {
18         // A pointer to the buffer's cursor for ease of access
19         Cursor *Cursor
20
21         // The topmost line, used for vertical scrolling
22         Topline int
23         // The leftmost column, used for horizontal scrolling
24         leftCol int
25
26         // Percentage of the terminal window that this view takes up (from 0 to 100)
27         widthPercent  int
28         heightPercent int
29
30         // Actual with and height
31         width  int
32         height int
33
34         // Where this view is located
35         x, y int
36
37         // How much to offset because of line numbers
38         lineNumOffset int
39
40         // Holds the list of gutter messages
41         messages map[string][]GutterMessage
42
43         // Is the help text opened in this view
44         helpOpen bool
45
46         // This is the index of this view in the views array
47         Num int
48         // What tab is this view stored in
49         TabNum int
50
51         // Is this view modifiable?
52         Modifiable bool
53
54         // The buffer
55         Buf *Buffer
56         // This is the buffer that was last opened
57         // This is used to open help, and then go back to the previously opened buffer
58         lastBuffer *Buffer
59         // The statusline
60         sline Statusline
61
62         // Since tcell doesn't differentiate between a mouse release event
63         // and a mouse move event with no keys pressed, we need to keep
64         // track of whether or not the mouse was pressed (or not released) last event to determine
65         // mouse release events
66         mouseReleased bool
67
68         // This stores when the last click was
69         // This is useful for detecting double and triple clicks
70         lastClickTime time.Time
71
72         // lastCutTime stores when the last ctrl+k was issued.
73         // It is used for clearing the clipboard to replace it with fresh cut lines.
74         lastCutTime time.Time
75
76         // freshClip returns true if the clipboard has never been pasted.
77         freshClip bool
78
79         // Was the last mouse event actually a double click?
80         // Useful for detecting triple clicks -- if a double click is detected
81         // but the last mouse event was actually a double click, it's a triple click
82         doubleClick bool
83         // Same here, just to keep track for mouse move events
84         tripleClick bool
85
86         // Syntax highlighting matches
87         matches SyntaxMatches
88         // The matches from the last frame
89         lastMatches SyntaxMatches
90 }
91
92 // NewView returns a new fullscreen view
93 func NewView(buf *Buffer) *View {
94         return NewViewWidthHeight(buf, 100, 100)
95 }
96
97 // NewViewWidthHeight returns a new view with the specified width and height percentages
98 // Note that w and h are percentages not actual values
99 func NewViewWidthHeight(buf *Buffer, w, h int) *View {
100         v := new(View)
101
102         v.x, v.y = 0, 0
103
104         v.widthPercent = w
105         v.heightPercent = h
106         v.Resize(screen.Size())
107
108         v.OpenBuffer(buf)
109
110         v.messages = make(map[string][]GutterMessage)
111
112         v.sline = Statusline{
113                 view: v,
114         }
115
116         return v
117 }
118
119 // Resize recalculates the actual width and height of the view from the width and height
120 // percentages
121 // This is usually called when the window is resized, or when a split has been added and
122 // the percentages have changed
123 func (v *View) Resize(w, h int) {
124         // Always include 1 line for the command line at the bottom
125         h--
126         if len(tabs) > 1 {
127                 // Include one line for the tab bar at the top
128                 h--
129                 v.y = 1
130         } else {
131                 v.y = 0
132         }
133         v.width = int(float32(w) * float32(v.widthPercent) / 100)
134         // We subtract 1 for the statusline
135         v.height = int(float32(h) * float32(v.heightPercent) / 100)
136         if settings["statusline"].(bool) {
137                 // Make room for the status line if it is enabled
138                 v.height--
139         }
140 }
141
142 // ScrollUp scrolls the view up n lines (if possible)
143 func (v *View) ScrollUp(n int) {
144         // Try to scroll by n but if it would overflow, scroll by 1
145         if v.Topline-n >= 0 {
146                 v.Topline -= n
147         } else if v.Topline > 0 {
148                 v.Topline--
149         }
150 }
151
152 // ScrollDown scrolls the view down n lines (if possible)
153 func (v *View) ScrollDown(n int) {
154         // Try to scroll by n but if it would overflow, scroll by 1
155         if v.Topline+n <= v.Buf.NumLines-v.height {
156                 v.Topline += n
157         } else if v.Topline < v.Buf.NumLines-v.height {
158                 v.Topline++
159         }
160 }
161
162 // CanClose returns whether or not the view can be closed
163 // If there are unsaved changes, the user will be asked if the view can be closed
164 // causing them to lose the unsaved changes
165 // The message is what to print after saying "You have unsaved changes. "
166 func (v *View) CanClose(msg string) bool {
167         if v.Buf.IsModified {
168                 quit, canceled := messenger.Prompt("You have unsaved changes. "+msg, "Unsaved", NoCompletion)
169                 if !canceled {
170                         if strings.ToLower(quit) == "yes" || strings.ToLower(quit) == "y" {
171                                 return true
172                         } else if strings.ToLower(quit) == "save" || strings.ToLower(quit) == "s" {
173                                 v.Save()
174                                 return true
175                         }
176                 }
177         } else {
178                 return true
179         }
180         return false
181 }
182
183 // OpenBuffer opens a new buffer in this view.
184 // This resets the topline, event handler and cursor.
185 func (v *View) OpenBuffer(buf *Buffer) {
186         screen.Clear()
187         v.CloseBuffer()
188         v.Buf = buf
189         v.Cursor = &buf.Cursor
190         v.Topline = 0
191         v.leftCol = 0
192         v.Cursor.ResetSelection()
193         v.Relocate()
194         v.messages = make(map[string][]GutterMessage)
195
196         v.matches = Match(v)
197
198         // Set mouseReleased to true because we assume the mouse is not being pressed when
199         // the editor is opened
200         v.mouseReleased = true
201         v.lastClickTime = time.Time{}
202 }
203
204 // CloseBuffer performs any closing functions on the buffer
205 func (v *View) CloseBuffer() {
206         if v.Buf != nil {
207                 v.Buf.Serialize()
208         }
209 }
210
211 // ReOpen reloads the current buffer
212 func (v *View) ReOpen() {
213         if v.CanClose("Continue? (yes, no, save) ") {
214                 screen.Clear()
215                 v.Buf.ReOpen()
216                 v.Relocate()
217                 v.matches = Match(v)
218         }
219 }
220
221 // Relocate moves the view window so that the cursor is in view
222 // This is useful if the user has scrolled far away, and then starts typing
223 func (v *View) Relocate() bool {
224         ret := false
225         cy := v.Cursor.Y
226         scrollmargin := int(settings["scrollmargin"].(float64))
227         if cy < v.Topline+scrollmargin && cy > scrollmargin-1 {
228                 v.Topline = cy - scrollmargin
229                 ret = true
230         } else if cy < v.Topline {
231                 v.Topline = cy
232                 ret = true
233         }
234         if cy > v.Topline+v.height-1-scrollmargin && cy < v.Buf.NumLines-scrollmargin {
235                 v.Topline = cy - v.height + 1 + scrollmargin
236                 ret = true
237         } else if cy >= v.Buf.NumLines-scrollmargin && cy > v.height {
238                 v.Topline = v.Buf.NumLines - v.height
239                 ret = true
240         }
241
242         cx := v.Cursor.GetVisualX()
243         if cx < v.leftCol {
244                 v.leftCol = cx
245                 ret = true
246         }
247         if cx+v.lineNumOffset+1 > v.leftCol+v.width {
248                 v.leftCol = cx - v.width + v.lineNumOffset + 1
249                 ret = true
250         }
251         return ret
252 }
253
254 // MoveToMouseClick moves the cursor to location x, y assuming x, y were given
255 // by a mouse click
256 func (v *View) MoveToMouseClick(x, y int) {
257         if y-v.Topline > v.height-1 {
258                 v.ScrollDown(1)
259                 y = v.height + v.Topline - 1
260         }
261         if y >= v.Buf.NumLines {
262                 y = v.Buf.NumLines - 1
263         }
264         if y < 0 {
265                 y = 0
266         }
267         if x < 0 {
268                 x = 0
269         }
270
271         x = v.Cursor.GetCharPosInLine(y, x)
272         if x > Count(v.Buf.Line(y)) {
273                 x = Count(v.Buf.Line(y))
274         }
275         v.Cursor.X = x
276         v.Cursor.Y = y
277         v.Cursor.LastVisualX = v.Cursor.GetVisualX()
278 }
279
280 // HandleEvent handles an event passed by the main loop
281 func (v *View) HandleEvent(event tcell.Event) {
282         // This bool determines whether the view is relocated at the end of the function
283         // By default it's true because most events should cause a relocate
284         relocate := true
285
286         v.Buf.CheckModTime()
287
288         switch e := event.(type) {
289         case *tcell.EventResize:
290                 // Window resized
291                 v.Resize(e.Size())
292         case *tcell.EventKey:
293                 if e.Key() == tcell.KeyRune && (e.Modifiers() == 0 || e.Modifiers() == tcell.ModShift) {
294                         // Insert a character
295                         if v.Cursor.HasSelection() {
296                                 v.Cursor.DeleteSelection()
297                                 v.Cursor.ResetSelection()
298                         }
299                         v.Buf.Insert(v.Cursor.Loc, string(e.Rune()))
300                         v.Cursor.Right()
301                 } else {
302                         for key, actions := range bindings {
303                                 if e.Key() == key.keyCode {
304                                         if e.Key() == tcell.KeyRune {
305                                                 if e.Rune() != key.r {
306                                                         continue
307                                                 }
308                                         }
309                                         if e.Modifiers() == key.modifiers {
310                                                 relocate = false
311                                                 for _, action := range actions {
312                                                         relocate = action(v) || relocate
313                                                         for _, pl := range loadedPlugins {
314                                                                 funcName := strings.Split(runtime.FuncForPC(reflect.ValueOf(action).Pointer()).Name(), ".")
315                                                                 err := Call(pl+"_on"+funcName[len(funcName)-1], nil)
316                                                                 if err != nil && !strings.HasPrefix(err.Error(), "function does not exist") {
317                                                                         TermMessage(err)
318                                                                 }
319                                                         }
320                                                 }
321                                         }
322                                 }
323                         }
324                 }
325         case *tcell.EventPaste:
326                 if v.Cursor.HasSelection() {
327                         v.Cursor.DeleteSelection()
328                         v.Cursor.ResetSelection()
329                 }
330                 clip := e.Text()
331                 v.Buf.Insert(v.Cursor.Loc, clip)
332                 v.Cursor.Loc = v.Cursor.Loc.Move(Count(clip), v.Buf)
333                 v.freshClip = false
334         case *tcell.EventMouse:
335                 x, y := e.Position()
336                 x -= v.lineNumOffset - v.leftCol
337                 y += v.Topline - v.y
338                 // Don't relocate for mouse events
339                 relocate = false
340
341                 button := e.Buttons()
342
343                 switch button {
344                 case tcell.Button1:
345                         // Left click
346                         if v.mouseReleased {
347                                 v.MoveToMouseClick(x, y)
348                                 if time.Since(v.lastClickTime)/time.Millisecond < doubleClickThreshold {
349                                         if v.doubleClick {
350                                                 // Triple click
351                                                 v.lastClickTime = time.Now()
352
353                                                 v.tripleClick = true
354                                                 v.doubleClick = false
355
356                                                 v.Cursor.SelectLine()
357                                         } else {
358                                                 // Double click
359                                                 v.lastClickTime = time.Now()
360
361                                                 v.doubleClick = true
362                                                 v.tripleClick = false
363
364                                                 v.Cursor.SelectWord()
365                                         }
366                                 } else {
367                                         v.doubleClick = false
368                                         v.tripleClick = false
369                                         v.lastClickTime = time.Now()
370
371                                         v.Cursor.OrigSelection[0] = v.Cursor.Loc
372                                         v.Cursor.CurSelection[0] = v.Cursor.Loc
373                                         v.Cursor.CurSelection[1] = v.Cursor.Loc
374                                 }
375                                 v.mouseReleased = false
376                         } else if !v.mouseReleased {
377                                 v.MoveToMouseClick(x, y)
378                                 if v.tripleClick {
379                                         v.Cursor.AddLineToSelection()
380                                 } else if v.doubleClick {
381                                         v.Cursor.AddWordToSelection()
382                                 } else {
383                                         v.Cursor.CurSelection[1] = v.Cursor.Loc
384                                 }
385                         }
386                 case tcell.ButtonNone:
387                         // Mouse event with no click
388                         if !v.mouseReleased {
389                                 // Mouse was just released
390
391                                 // Relocating here isn't really necessary because the cursor will
392                                 // be in the right place from the last mouse event
393                                 // However, if we are running in a terminal that doesn't support mouse motion
394                                 // events, this still allows the user to make selections, except only after they
395                                 // release the mouse
396
397                                 if !v.doubleClick && !v.tripleClick {
398                                         v.MoveToMouseClick(x, y)
399                                         v.Cursor.CurSelection[1] = v.Cursor.Loc
400                                 }
401                                 v.mouseReleased = true
402                         }
403                 case tcell.WheelUp:
404                         // Scroll up
405                         scrollspeed := int(settings["scrollspeed"].(float64))
406                         v.ScrollUp(scrollspeed)
407                 case tcell.WheelDown:
408                         // Scroll down
409                         scrollspeed := int(settings["scrollspeed"].(float64))
410                         v.ScrollDown(scrollspeed)
411                 }
412         }
413
414         if relocate {
415                 v.Relocate()
416         }
417         if settings["syntax"].(bool) {
418                 v.matches = Match(v)
419         }
420 }
421
422 // GutterMessage creates a message in this view's gutter
423 func (v *View) GutterMessage(section string, lineN int, msg string, kind int) {
424         lineN--
425         gutterMsg := GutterMessage{
426                 lineNum: lineN,
427                 msg:     msg,
428                 kind:    kind,
429         }
430         for _, v := range v.messages {
431                 for _, gmsg := range v {
432                         if gmsg.lineNum == lineN {
433                                 return
434                         }
435                 }
436         }
437         messages := v.messages[section]
438         v.messages[section] = append(messages, gutterMsg)
439 }
440
441 // ClearGutterMessages clears all gutter messages from a given section
442 func (v *View) ClearGutterMessages(section string) {
443         v.messages[section] = []GutterMessage{}
444 }
445
446 // ClearAllGutterMessages clears all the gutter messages
447 func (v *View) ClearAllGutterMessages() {
448         for k := range v.messages {
449                 v.messages[k] = []GutterMessage{}
450         }
451 }
452
453 // DisplayView renders the view to the screen
454 func (v *View) DisplayView() {
455         // The character number of the character in the top left of the screen
456         charNum := Loc{0, v.Topline}
457
458         // Convert the length of buffer to a string, and get the length of the string
459         // We are going to have to offset by that amount
460         maxLineLength := len(strconv.Itoa(v.Buf.NumLines))
461         // + 1 for the little space after the line number
462         if settings["ruler"] == true {
463                 v.lineNumOffset = maxLineLength + 1
464         } else {
465                 v.lineNumOffset = 0
466         }
467         highlightStyle := defStyle
468
469         var hasGutterMessages bool
470         for _, v := range v.messages {
471                 if len(v) > 0 {
472                         hasGutterMessages = true
473                 }
474         }
475         if hasGutterMessages {
476                 v.lineNumOffset += 2
477         }
478
479         for lineN := 0; lineN < v.height; lineN++ {
480                 x := v.x
481                 // If the buffer is smaller than the view height
482                 if lineN+v.Topline >= v.Buf.NumLines {
483                         // We have to clear all this space
484                         for i := 0; i < v.width; i++ {
485                                 screen.SetContent(i, lineN+v.y, ' ', nil, defStyle)
486                         }
487
488                         continue
489                 }
490                 line := v.Buf.Line(lineN + v.Topline)
491
492                 if hasGutterMessages {
493                         msgOnLine := false
494                         for k := range v.messages {
495                                 for _, msg := range v.messages[k] {
496                                         if msg.lineNum == lineN+v.Topline {
497                                                 msgOnLine = true
498                                                 gutterStyle := defStyle
499                                                 switch msg.kind {
500                                                 case GutterInfo:
501                                                         if style, ok := colorscheme["gutter-info"]; ok {
502                                                                 gutterStyle = style
503                                                         }
504                                                 case GutterWarning:
505                                                         if style, ok := colorscheme["gutter-warning"]; ok {
506                                                                 gutterStyle = style
507                                                         }
508                                                 case GutterError:
509                                                         if style, ok := colorscheme["gutter-error"]; ok {
510                                                                 gutterStyle = style
511                                                         }
512                                                 }
513                                                 screen.SetContent(x, lineN+v.y, '>', nil, gutterStyle)
514                                                 x++
515                                                 screen.SetContent(x, lineN+v.y, '>', nil, gutterStyle)
516                                                 x++
517                                                 if v.Cursor.Y == lineN+v.Topline {
518                                                         messenger.Message(msg.msg)
519                                                         messenger.gutterMessage = true
520                                                 }
521                                         }
522                                 }
523                         }
524                         if !msgOnLine {
525                                 screen.SetContent(x, lineN+v.y, ' ', nil, defStyle)
526                                 x++
527                                 screen.SetContent(x, lineN+v.y, ' ', nil, defStyle)
528                                 x++
529                                 if v.Cursor.Y == lineN+v.Topline && messenger.gutterMessage {
530                                         messenger.Reset()
531                                         messenger.gutterMessage = false
532                                 }
533                         }
534                 }
535
536                 // Write the line number
537                 lineNumStyle := defStyle
538                 if style, ok := colorscheme["line-number"]; ok {
539                         lineNumStyle = style
540                 }
541                 // Write the spaces before the line number if necessary
542                 var lineNum string
543                 if settings["ruler"] == true {
544                         lineNum = strconv.Itoa(lineN + v.Topline + 1)
545                         for i := 0; i < maxLineLength-len(lineNum); i++ {
546                                 screen.SetContent(x, lineN+v.y, ' ', nil, lineNumStyle)
547                                 x++
548                         }
549                         // Write the actual line number
550                         for _, ch := range lineNum {
551                                 screen.SetContent(x, lineN+v.y, ch, nil, lineNumStyle)
552                                 x++
553                         }
554
555                         if settings["ruler"] == true {
556                                 // Write the extra space
557                                 screen.SetContent(x, lineN+v.y, ' ', nil, lineNumStyle)
558                                 x++
559                         }
560                 }
561                 // Write the line
562                 for colN, ch := range line {
563                         lineStyle := defStyle
564
565                         if settings["syntax"].(bool) {
566                                 // Syntax highlighting is enabled
567                                 highlightStyle = v.matches[lineN][colN]
568                         }
569
570                         if v.Cursor.HasSelection() &&
571                                 (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
572                                         charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
573
574                                 lineStyle = defStyle.Reverse(true)
575
576                                 if style, ok := colorscheme["selection"]; ok {
577                                         lineStyle = style
578                                 }
579                         } else {
580                                 lineStyle = highlightStyle
581                         }
582
583                         if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
584                                 if style, ok := colorscheme["cursor-line"]; ok {
585                                         fg, _, _ := style.Decompose()
586                                         lineStyle = lineStyle.Background(fg)
587                                 }
588                         }
589
590                         if ch == '\t' {
591                                 lineIndentStyle := defStyle
592                                 if style, ok := colorscheme["indent-char"]; ok {
593                                         lineIndentStyle = style
594                                 }
595                                 if v.Cursor.HasSelection() &&
596                                         (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
597                                                 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
598
599                                         lineIndentStyle = defStyle.Reverse(true)
600
601                                         if style, ok := colorscheme["selection"]; ok {
602                                                 lineIndentStyle = style
603                                         }
604                                 }
605                                 if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
606                                         if style, ok := colorscheme["cursor-line"]; ok {
607                                                 fg, _, _ := style.Decompose()
608                                                 lineIndentStyle = lineIndentStyle.Background(fg)
609                                         }
610                                 }
611                                 indentChar := []rune(settings["indentchar"].(string))
612                                 if x-v.leftCol >= v.lineNumOffset {
613                                         screen.SetContent(x-v.leftCol, lineN+v.y, indentChar[0], nil, lineIndentStyle)
614                                 }
615                                 tabSize := int(settings["tabsize"].(float64))
616                                 for i := 0; i < tabSize-1; i++ {
617                                         x++
618                                         if x-v.leftCol >= v.lineNumOffset {
619                                                 screen.SetContent(x-v.leftCol, lineN+v.y, ' ', nil, lineStyle)
620                                         }
621                                 }
622                         } else if runewidth.RuneWidth(ch) > 1 {
623                                 if x-v.leftCol >= v.lineNumOffset {
624                                         screen.SetContent(x-v.leftCol, lineN, ch, nil, lineStyle)
625                                 }
626                                 for i := 0; i < runewidth.RuneWidth(ch)-1; i++ {
627                                         x++
628                                         if x-v.leftCol >= v.lineNumOffset {
629                                                 screen.SetContent(x-v.leftCol, lineN, ' ', nil, lineStyle)
630                                         }
631                                 }
632                         } else {
633                                 if x-v.leftCol >= v.lineNumOffset {
634                                         screen.SetContent(x-v.leftCol, lineN+v.y, ch, nil, lineStyle)
635                                 }
636                         }
637                         charNum = charNum.Move(1, v.Buf)
638                         x++
639                 }
640                 // Here we are at a newline
641
642                 // The newline may be selected, in which case we should draw the selection style
643                 // with a space to represent it
644                 if v.Cursor.HasSelection() &&
645                         (charNum.GreaterEqual(v.Cursor.CurSelection[0]) && charNum.LessThan(v.Cursor.CurSelection[1]) ||
646                                 charNum.LessThan(v.Cursor.CurSelection[0]) && charNum.GreaterEqual(v.Cursor.CurSelection[1])) {
647
648                         selectStyle := defStyle.Reverse(true)
649
650                         if style, ok := colorscheme["selection"]; ok {
651                                 selectStyle = style
652                         }
653                         screen.SetContent(x-v.leftCol, lineN+v.y, ' ', nil, selectStyle)
654                         x++
655                 }
656
657                 charNum = charNum.Move(1, v.Buf)
658
659                 for i := 0; i < v.width-(x-v.leftCol); i++ {
660                         lineStyle := defStyle
661                         if settings["cursorline"].(bool) && !v.Cursor.HasSelection() && v.Cursor.Y == lineN+v.Topline {
662                                 if style, ok := colorscheme["cursor-line"]; ok {
663                                         fg, _, _ := style.Decompose()
664                                         lineStyle = lineStyle.Background(fg)
665                                 }
666                         }
667                         if !(x-v.leftCol < v.lineNumOffset) {
668                                 screen.SetContent(x+i, lineN+v.y, ' ', nil, lineStyle)
669                         }
670                 }
671         }
672 }
673
674 // DisplayCursor draws the current buffer's cursor to the screen
675 func (v *View) DisplayCursor() {
676         // Don't draw the cursor if it is out of the viewport or if it has a selection
677         if (v.Cursor.Y-v.Topline < 0 || v.Cursor.Y-v.Topline > v.height-1) || v.Cursor.HasSelection() {
678                 screen.HideCursor()
679         } else {
680                 screen.ShowCursor(v.x+v.Cursor.GetVisualX()+v.lineNumOffset-v.leftCol, v.Cursor.Y-v.Topline+v.y)
681         }
682 }
683
684 // Display renders the view, the cursor, and statusline
685 func (v *View) Display() {
686         v.DisplayView()
687         v.DisplayCursor()
688         if settings["statusline"].(bool) {
689                 v.sline.Display()
690         }
691 }