]> git.lizzy.rs Git - micro.git/blob - internal/action/actions.go
9c76d6018e6b2b3988b270d0ca08fbf2414c0341
[micro.git] / internal / action / actions.go
1 package action
2
3 import (
4         "errors"
5         "fmt"
6         "io/fs"
7         "regexp"
8         "runtime"
9         "strings"
10         "time"
11
12         shellquote "github.com/kballard/go-shellquote"
13         "github.com/zyedidia/micro/v2/internal/buffer"
14         "github.com/zyedidia/micro/v2/internal/clipboard"
15         "github.com/zyedidia/micro/v2/internal/config"
16         "github.com/zyedidia/micro/v2/internal/display"
17         "github.com/zyedidia/micro/v2/internal/screen"
18         "github.com/zyedidia/micro/v2/internal/shell"
19         "github.com/zyedidia/micro/v2/internal/util"
20         "github.com/zyedidia/tcell/v2"
21 )
22
23 // ScrollUp is not an action
24 func (h *BufPane) ScrollUp(n int) {
25         v := h.GetView()
26         v.StartLine = h.Scroll(v.StartLine, -n)
27         h.SetView(v)
28 }
29
30 // ScrollDown is not an action
31 func (h *BufPane) ScrollDown(n int) {
32         v := h.GetView()
33         v.StartLine = h.Scroll(v.StartLine, n)
34         h.SetView(v)
35 }
36
37 // ScrollAdjust can be used to shift the view so that the last line is at the
38 // bottom if the user has scrolled past the last line.
39 func (h *BufPane) ScrollAdjust() {
40         v := h.GetView()
41         end := h.SLocFromLoc(h.Buf.End())
42         if h.Diff(v.StartLine, end) < h.BufView().Height-1 {
43                 v.StartLine = h.Scroll(end, -h.BufView().Height+1)
44         }
45         h.SetView(v)
46 }
47
48 // MousePress is the event that should happen when a normal click happens
49 // This is almost always bound to left click
50 func (h *BufPane) MousePress(e *tcell.EventMouse) bool {
51         b := h.Buf
52         mx, my := e.Position()
53         mouseLoc := h.LocFromVisual(buffer.Loc{mx, my})
54         h.Cursor.Loc = mouseLoc
55         if h.mouseReleased {
56                 if b.NumCursors() > 1 {
57                         b.ClearCursors()
58                         h.Relocate()
59                         h.Cursor = h.Buf.GetActiveCursor()
60                         h.Cursor.Loc = mouseLoc
61                 }
62                 if time.Since(h.lastClickTime)/time.Millisecond < config.DoubleClickThreshold && (mouseLoc.X == h.lastLoc.X && mouseLoc.Y == h.lastLoc.Y) {
63                         if h.doubleClick {
64                                 // Triple click
65                                 h.lastClickTime = time.Now()
66
67                                 h.tripleClick = true
68                                 h.doubleClick = false
69
70                                 h.Cursor.SelectLine()
71                                 h.Cursor.CopySelection(clipboard.PrimaryReg)
72                         } else {
73                                 // Double click
74                                 h.lastClickTime = time.Now()
75
76                                 h.doubleClick = true
77                                 h.tripleClick = false
78
79                                 h.Cursor.SelectWord()
80                                 h.Cursor.CopySelection(clipboard.PrimaryReg)
81                         }
82                 } else {
83                         h.doubleClick = false
84                         h.tripleClick = false
85                         h.lastClickTime = time.Now()
86
87                         h.Cursor.OrigSelection[0] = h.Cursor.Loc
88                         h.Cursor.CurSelection[0] = h.Cursor.Loc
89                         h.Cursor.CurSelection[1] = h.Cursor.Loc
90                 }
91                 h.mouseReleased = false
92         } else if !h.mouseReleased {
93                 if h.tripleClick {
94                         h.Cursor.AddLineToSelection()
95                 } else if h.doubleClick {
96                         h.Cursor.AddWordToSelection()
97                 } else {
98                         h.Cursor.SetSelectionEnd(h.Cursor.Loc)
99                 }
100         }
101
102         h.Cursor.StoreVisualX()
103         h.lastLoc = mouseLoc
104         h.Relocate()
105         return true
106 }
107
108 // ScrollUpAction scrolls the view up
109 func (h *BufPane) ScrollUpAction() bool {
110         h.ScrollUp(util.IntOpt(h.Buf.Settings["scrollspeed"]))
111         return true
112 }
113
114 // ScrollDownAction scrolls the view up
115 func (h *BufPane) ScrollDownAction() bool {
116         h.ScrollDown(util.IntOpt(h.Buf.Settings["scrollspeed"]))
117         return true
118 }
119
120 // Center centers the view on the cursor
121 func (h *BufPane) Center() bool {
122         v := h.GetView()
123         v.StartLine = h.Scroll(h.SLocFromLoc(h.Cursor.Loc), -h.BufView().Height/2)
124         h.SetView(v)
125         h.ScrollAdjust()
126         return true
127 }
128
129 // MoveCursorUp is not an action
130 func (h *BufPane) MoveCursorUp(n int) {
131         if !h.Buf.Settings["softwrap"].(bool) {
132                 h.Cursor.UpN(n)
133         } else {
134                 vloc := h.VLocFromLoc(h.Cursor.Loc)
135                 sloc := h.Scroll(vloc.SLoc, -n)
136                 if sloc == vloc.SLoc {
137                         // we are at the beginning of buffer
138                         h.Cursor.Loc = h.Buf.Start()
139                         h.Cursor.LastVisualX = 0
140                 } else {
141                         vloc.SLoc = sloc
142                         vloc.VisualX = h.Cursor.LastVisualX
143                         h.Cursor.Loc = h.LocFromVLoc(vloc)
144                 }
145         }
146 }
147
148 // MoveCursorDown is not an action
149 func (h *BufPane) MoveCursorDown(n int) {
150         if !h.Buf.Settings["softwrap"].(bool) {
151                 h.Cursor.DownN(n)
152         } else {
153                 vloc := h.VLocFromLoc(h.Cursor.Loc)
154                 sloc := h.Scroll(vloc.SLoc, n)
155                 if sloc == vloc.SLoc {
156                         // we are at the end of buffer
157                         h.Cursor.Loc = h.Buf.End()
158                         vloc = h.VLocFromLoc(h.Cursor.Loc)
159                         h.Cursor.LastVisualX = vloc.VisualX
160                 } else {
161                         vloc.SLoc = sloc
162                         vloc.VisualX = h.Cursor.LastVisualX
163                         h.Cursor.Loc = h.LocFromVLoc(vloc)
164                 }
165         }
166 }
167
168 // CursorUp moves the cursor up
169 func (h *BufPane) CursorUp() bool {
170         h.Cursor.Deselect(true)
171         h.MoveCursorUp(1)
172         h.Relocate()
173         return true
174 }
175
176 // CursorDown moves the cursor down
177 func (h *BufPane) CursorDown() bool {
178         h.Cursor.Deselect(true)
179         h.MoveCursorDown(1)
180         h.Relocate()
181         return true
182 }
183
184 // CursorLeft moves the cursor left
185 func (h *BufPane) CursorLeft() bool {
186         if h.Cursor.HasSelection() {
187                 h.Cursor.Deselect(true)
188         } else {
189                 tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
190                 tabmovement := h.Buf.Settings["tabmovement"].(bool)
191                 if tabstospaces && tabmovement {
192                         tabsize := int(h.Buf.Settings["tabsize"].(float64))
193                         line := h.Buf.LineBytes(h.Cursor.Y)
194                         if h.Cursor.X-tabsize >= 0 && util.IsSpaces(line[h.Cursor.X-tabsize:h.Cursor.X]) && util.IsBytesWhitespace(line[0:h.Cursor.X-tabsize]) {
195                                 for i := 0; i < tabsize; i++ {
196                                         h.Cursor.Left()
197                                 }
198                         } else {
199                                 h.Cursor.Left()
200                         }
201                 } else {
202                         h.Cursor.Left()
203                 }
204         }
205         h.Relocate()
206         return true
207 }
208
209 // CursorRight moves the cursor right
210 func (h *BufPane) CursorRight() bool {
211         if h.Cursor.HasSelection() {
212                 h.Cursor.Deselect(false)
213                 h.Cursor.Loc = h.Cursor.Loc.Move(1, h.Buf)
214         } else {
215                 tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
216                 tabmovement := h.Buf.Settings["tabmovement"].(bool)
217                 if tabstospaces && tabmovement {
218                         tabsize := int(h.Buf.Settings["tabsize"].(float64))
219                         line := h.Buf.LineBytes(h.Cursor.Y)
220                         if h.Cursor.X+tabsize < util.CharacterCount(line) && util.IsSpaces(line[h.Cursor.X:h.Cursor.X+tabsize]) && util.IsBytesWhitespace(line[0:h.Cursor.X]) {
221                                 for i := 0; i < tabsize; i++ {
222                                         h.Cursor.Right()
223                                 }
224                         } else {
225                                 h.Cursor.Right()
226                         }
227                 } else {
228                         h.Cursor.Right()
229                 }
230         }
231
232         h.Relocate()
233         return true
234 }
235
236 // WordRight moves the cursor one word to the right
237 func (h *BufPane) WordRight() bool {
238         h.Cursor.Deselect(false)
239         h.Cursor.WordRight()
240         h.Relocate()
241         return true
242 }
243
244 // WordLeft moves the cursor one word to the left
245 func (h *BufPane) WordLeft() bool {
246         h.Cursor.Deselect(true)
247         h.Cursor.WordLeft()
248         h.Relocate()
249         return true
250 }
251
252 // SelectUp selects up one line
253 func (h *BufPane) SelectUp() bool {
254         if !h.Cursor.HasSelection() {
255                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
256         }
257         h.MoveCursorUp(1)
258         h.Cursor.SelectTo(h.Cursor.Loc)
259         h.Relocate()
260         return true
261 }
262
263 // SelectDown selects down one line
264 func (h *BufPane) SelectDown() bool {
265         if !h.Cursor.HasSelection() {
266                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
267         }
268         h.MoveCursorDown(1)
269         h.Cursor.SelectTo(h.Cursor.Loc)
270         h.Relocate()
271         return true
272 }
273
274 // SelectLeft selects the character to the left of the cursor
275 func (h *BufPane) SelectLeft() bool {
276         loc := h.Cursor.Loc
277         count := h.Buf.End()
278         if loc.GreaterThan(count) {
279                 loc = count
280         }
281         if !h.Cursor.HasSelection() {
282                 h.Cursor.OrigSelection[0] = loc
283         }
284         h.Cursor.Left()
285         h.Cursor.SelectTo(h.Cursor.Loc)
286         h.Relocate()
287         return true
288 }
289
290 // SelectRight selects the character to the right of the cursor
291 func (h *BufPane) SelectRight() bool {
292         loc := h.Cursor.Loc
293         count := h.Buf.End()
294         if loc.GreaterThan(count) {
295                 loc = count
296         }
297         if !h.Cursor.HasSelection() {
298                 h.Cursor.OrigSelection[0] = loc
299         }
300         h.Cursor.Right()
301         h.Cursor.SelectTo(h.Cursor.Loc)
302         h.Relocate()
303         return true
304 }
305
306 // SelectWordRight selects the word to the right of the cursor
307 func (h *BufPane) SelectWordRight() bool {
308         if !h.Cursor.HasSelection() {
309                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
310         }
311         h.Cursor.WordRight()
312         h.Cursor.SelectTo(h.Cursor.Loc)
313         h.Relocate()
314         return true
315 }
316
317 // SelectWordLeft selects the word to the left of the cursor
318 func (h *BufPane) SelectWordLeft() bool {
319         if !h.Cursor.HasSelection() {
320                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
321         }
322         h.Cursor.WordLeft()
323         h.Cursor.SelectTo(h.Cursor.Loc)
324         h.Relocate()
325         return true
326 }
327
328 // StartOfText moves the cursor to the start of the text of the line
329 func (h *BufPane) StartOfText() bool {
330         h.Cursor.Deselect(true)
331         h.Cursor.StartOfText()
332         h.Relocate()
333         return true
334 }
335
336 // StartOfTextToggle toggles the cursor between the start of the text of the line
337 // and the start of the line
338 func (h *BufPane) StartOfTextToggle() bool {
339         h.Cursor.Deselect(true)
340         if h.Cursor.IsStartOfText() {
341                 h.Cursor.Start()
342         } else {
343                 h.Cursor.StartOfText()
344         }
345         h.Relocate()
346         return true
347 }
348
349 // StartOfLine moves the cursor to the start of the line
350 func (h *BufPane) StartOfLine() bool {
351         h.Cursor.Deselect(true)
352         h.Cursor.Start()
353         h.Relocate()
354         return true
355 }
356
357 // EndOfLine moves the cursor to the end of the line
358 func (h *BufPane) EndOfLine() bool {
359         h.Cursor.Deselect(true)
360         h.Cursor.End()
361         h.Relocate()
362         return true
363 }
364
365 // SelectLine selects the entire current line
366 func (h *BufPane) SelectLine() bool {
367         h.Cursor.SelectLine()
368         h.Relocate()
369         return true
370 }
371
372 // SelectToStartOfText selects to the start of the text on the current line
373 func (h *BufPane) SelectToStartOfText() bool {
374         if !h.Cursor.HasSelection() {
375                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
376         }
377         h.Cursor.StartOfText()
378         h.Cursor.SelectTo(h.Cursor.Loc)
379         h.Relocate()
380         return true
381 }
382
383 // SelectToStartOfTextToggle toggles the selection between the start of the text
384 // on the current line and the start of the line
385 func (h *BufPane) SelectToStartOfTextToggle() bool {
386         if !h.Cursor.HasSelection() {
387                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
388         }
389         if h.Cursor.IsStartOfText() {
390                 h.Cursor.Start()
391         } else {
392                 h.Cursor.StartOfText()
393         }
394         h.Cursor.SelectTo(h.Cursor.Loc)
395         h.Relocate()
396         return true
397 }
398
399 // SelectToStartOfLine selects to the start of the current line
400 func (h *BufPane) SelectToStartOfLine() bool {
401         if !h.Cursor.HasSelection() {
402                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
403         }
404         h.Cursor.Start()
405         h.Cursor.SelectTo(h.Cursor.Loc)
406         h.Relocate()
407         return true
408 }
409
410 // SelectToEndOfLine selects to the end of the current line
411 func (h *BufPane) SelectToEndOfLine() bool {
412         if !h.Cursor.HasSelection() {
413                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
414         }
415         h.Cursor.End()
416         h.Cursor.SelectTo(h.Cursor.Loc)
417         h.Relocate()
418         return true
419 }
420
421 // ParagraphPrevious moves the cursor to the previous empty line, or beginning of the buffer if there's none
422 func (h *BufPane) ParagraphPrevious() bool {
423         var line int
424         for line = h.Cursor.Y; line > 0; line-- {
425                 if len(h.Buf.LineBytes(line)) == 0 && line != h.Cursor.Y {
426                         h.Cursor.X = 0
427                         h.Cursor.Y = line
428                         break
429                 }
430         }
431         // If no empty line found. move cursor to end of buffer
432         if line == 0 {
433                 h.Cursor.Loc = h.Buf.Start()
434         }
435         h.Relocate()
436         return true
437 }
438
439 // ParagraphNext moves the cursor to the next empty line, or end of the buffer if there's none
440 func (h *BufPane) ParagraphNext() bool {
441         var line int
442         for line = h.Cursor.Y; line < h.Buf.LinesNum(); line++ {
443                 if len(h.Buf.LineBytes(line)) == 0 && line != h.Cursor.Y {
444                         h.Cursor.X = 0
445                         h.Cursor.Y = line
446                         break
447                 }
448         }
449         // If no empty line found. move cursor to end of buffer
450         if line == h.Buf.LinesNum() {
451                 h.Cursor.Loc = h.Buf.End()
452         }
453         h.Relocate()
454         return true
455 }
456
457 // Retab changes all tabs to spaces or all spaces to tabs depending
458 // on the user's settings
459 func (h *BufPane) Retab() bool {
460         h.Buf.Retab()
461         h.Relocate()
462         return true
463 }
464
465 // CursorStart moves the cursor to the start of the buffer
466 func (h *BufPane) CursorStart() bool {
467         h.Cursor.Deselect(true)
468         h.Cursor.X = 0
469         h.Cursor.Y = 0
470         h.Cursor.StoreVisualX()
471         h.Relocate()
472         return true
473 }
474
475 // CursorEnd moves the cursor to the end of the buffer
476 func (h *BufPane) CursorEnd() bool {
477         h.Cursor.Deselect(true)
478         h.Cursor.Loc = h.Buf.End()
479         h.Cursor.StoreVisualX()
480         h.Relocate()
481         return true
482 }
483
484 // SelectToStart selects the text from the cursor to the start of the buffer
485 func (h *BufPane) SelectToStart() bool {
486         if !h.Cursor.HasSelection() {
487                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
488         }
489         h.CursorStart()
490         h.Cursor.SelectTo(h.Buf.Start())
491         h.Relocate()
492         return true
493 }
494
495 // SelectToEnd selects the text from the cursor to the end of the buffer
496 func (h *BufPane) SelectToEnd() bool {
497         if !h.Cursor.HasSelection() {
498                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
499         }
500         h.CursorEnd()
501         h.Cursor.SelectTo(h.Buf.End())
502         h.Relocate()
503         return true
504 }
505
506 // InsertNewline inserts a newline plus possible some whitespace if autoindent is on
507 func (h *BufPane) InsertNewline() bool {
508         // Insert a newline
509         if h.Cursor.HasSelection() {
510                 h.Cursor.DeleteSelection()
511                 h.Cursor.ResetSelection()
512         }
513
514         ws := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))
515         cx := h.Cursor.X
516         h.Buf.Insert(h.Cursor.Loc, "\n")
517         // h.Cursor.Right()
518
519         if h.Buf.Settings["autoindent"].(bool) {
520                 if cx < len(ws) {
521                         ws = ws[0:cx]
522                 }
523                 h.Buf.Insert(h.Cursor.Loc, string(ws))
524                 // for i := 0; i < len(ws); i++ {
525                 //      h.Cursor.Right()
526                 // }
527
528                 // Remove the whitespaces if keepautoindent setting is off
529                 if util.IsSpacesOrTabs(h.Buf.LineBytes(h.Cursor.Y-1)) && !h.Buf.Settings["keepautoindent"].(bool) {
530                         line := h.Buf.LineBytes(h.Cursor.Y - 1)
531                         h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y - 1}, buffer.Loc{X: util.CharacterCount(line), Y: h.Cursor.Y - 1})
532                 }
533         }
534         h.Cursor.LastVisualX = h.Cursor.GetVisualX()
535         h.Relocate()
536         return true
537 }
538
539 // Backspace deletes the previous character
540 func (h *BufPane) Backspace() bool {
541         if h.Cursor.HasSelection() {
542                 h.Cursor.DeleteSelection()
543                 h.Cursor.ResetSelection()
544         } else if h.Cursor.Loc.GreaterThan(h.Buf.Start()) {
545                 // We have to do something a bit hacky here because we want to
546                 // delete the line by first moving left and then deleting backwards
547                 // but the undo redo would place the cursor in the wrong place
548                 // So instead we move left, save the position, move back, delete
549                 // and restore the position
550
551                 // If the user is using spaces instead of tabs and they are deleting
552                 // whitespace at the start of the line, we should delete as if it's a
553                 // tab (tabSize number of spaces)
554                 lineStart := util.SliceStart(h.Buf.LineBytes(h.Cursor.Y), h.Cursor.X)
555                 tabSize := int(h.Buf.Settings["tabsize"].(float64))
556                 if h.Buf.Settings["tabstospaces"].(bool) && util.IsSpaces(lineStart) && len(lineStart) != 0 && util.CharacterCount(lineStart)%tabSize == 0 {
557                         loc := h.Cursor.Loc
558                         h.Buf.Remove(loc.Move(-tabSize, h.Buf), loc)
559                 } else {
560                         loc := h.Cursor.Loc
561                         h.Buf.Remove(loc.Move(-1, h.Buf), loc)
562                 }
563         }
564         h.Cursor.LastVisualX = h.Cursor.GetVisualX()
565         h.Relocate()
566         return true
567 }
568
569 // DeleteWordRight deletes the word to the right of the cursor
570 func (h *BufPane) DeleteWordRight() bool {
571         h.SelectWordRight()
572         if h.Cursor.HasSelection() {
573                 h.Cursor.DeleteSelection()
574                 h.Cursor.ResetSelection()
575         }
576         h.Relocate()
577         return true
578 }
579
580 // DeleteWordLeft deletes the word to the left of the cursor
581 func (h *BufPane) DeleteWordLeft() bool {
582         h.SelectWordLeft()
583         if h.Cursor.HasSelection() {
584                 h.Cursor.DeleteSelection()
585                 h.Cursor.ResetSelection()
586         }
587         h.Relocate()
588         return true
589 }
590
591 // Delete deletes the next character
592 func (h *BufPane) Delete() bool {
593         if h.Cursor.HasSelection() {
594                 h.Cursor.DeleteSelection()
595                 h.Cursor.ResetSelection()
596         } else {
597                 loc := h.Cursor.Loc
598                 if loc.LessThan(h.Buf.End()) {
599                         h.Buf.Remove(loc, loc.Move(1, h.Buf))
600                 }
601         }
602         h.Relocate()
603         return true
604 }
605
606 // IndentSelection indents the current selection
607 func (h *BufPane) IndentSelection() bool {
608         if h.Cursor.HasSelection() {
609                 start := h.Cursor.CurSelection[0]
610                 end := h.Cursor.CurSelection[1]
611                 if end.Y < start.Y {
612                         start, end = end, start
613                         h.Cursor.SetSelectionStart(start)
614                         h.Cursor.SetSelectionEnd(end)
615                 }
616
617                 startY := start.Y
618                 endY := end.Move(-1, h.Buf).Y
619                 endX := end.Move(-1, h.Buf).X
620                 tabsize := int(h.Buf.Settings["tabsize"].(float64))
621                 indentsize := len(h.Buf.IndentString(tabsize))
622                 for y := startY; y <= endY; y++ {
623                         if len(h.Buf.LineBytes(y)) > 0 {
624                                 h.Buf.Insert(buffer.Loc{X: 0, Y: y}, h.Buf.IndentString(tabsize))
625                                 if y == startY && start.X > 0 {
626                                         h.Cursor.SetSelectionStart(start.Move(indentsize, h.Buf))
627                                 }
628                                 if y == endY {
629                                         h.Cursor.SetSelectionEnd(buffer.Loc{X: endX + indentsize + 1, Y: endY})
630                                 }
631                         }
632                 }
633                 h.Buf.RelocateCursors()
634
635                 h.Relocate()
636                 return true
637         }
638         return false
639 }
640
641 // IndentLine moves the current line forward one indentation
642 func (h *BufPane) IndentLine() bool {
643         if h.Cursor.HasSelection() {
644                 return false
645         }
646
647         tabsize := int(h.Buf.Settings["tabsize"].(float64))
648         indentstr := h.Buf.IndentString(tabsize)
649         h.Buf.Insert(buffer.Loc{X: 0, Y: h.Cursor.Y}, indentstr)
650         h.Buf.RelocateCursors()
651         h.Relocate()
652         return true
653 }
654
655 // OutdentLine moves the current line back one indentation
656 func (h *BufPane) OutdentLine() bool {
657         if h.Cursor.HasSelection() {
658                 return false
659         }
660
661         for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
662                 if len(util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))) == 0 {
663                         break
664                 }
665                 h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y}, buffer.Loc{X: 1, Y: h.Cursor.Y})
666         }
667         h.Buf.RelocateCursors()
668         h.Relocate()
669         return true
670 }
671
672 // OutdentSelection takes the current selection and moves it back one indent level
673 func (h *BufPane) OutdentSelection() bool {
674         if h.Cursor.HasSelection() {
675                 start := h.Cursor.CurSelection[0]
676                 end := h.Cursor.CurSelection[1]
677                 if end.Y < start.Y {
678                         start, end = end, start
679                         h.Cursor.SetSelectionStart(start)
680                         h.Cursor.SetSelectionEnd(end)
681                 }
682
683                 startY := start.Y
684                 endY := end.Move(-1, h.Buf).Y
685                 for y := startY; y <= endY; y++ {
686                         for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
687                                 if len(util.GetLeadingWhitespace(h.Buf.LineBytes(y))) == 0 {
688                                         break
689                                 }
690                                 h.Buf.Remove(buffer.Loc{X: 0, Y: y}, buffer.Loc{X: 1, Y: y})
691                         }
692                 }
693                 h.Buf.RelocateCursors()
694
695                 h.Relocate()
696                 return true
697         }
698         return false
699 }
700
701 // Autocomplete cycles the suggestions and performs autocompletion if there are suggestions
702 func (h *BufPane) Autocomplete() bool {
703         b := h.Buf
704
705         if h.Cursor.HasSelection() {
706                 return false
707         }
708
709         if h.Cursor.X == 0 {
710                 return false
711         }
712         r := h.Cursor.RuneUnder(h.Cursor.X)
713         prev := h.Cursor.RuneUnder(h.Cursor.X - 1)
714         if !util.IsAutocomplete(prev) || !util.IsNonAlphaNumeric(r) {
715                 // don't autocomplete if cursor is on alpha numeric character (middle of a word)
716                 return false
717         }
718
719         if b.HasSuggestions {
720                 b.CycleAutocomplete(true)
721                 return true
722         }
723         return b.Autocomplete(buffer.BufferComplete)
724 }
725
726 // CycleAutocompleteBack cycles back in the autocomplete suggestion list
727 func (h *BufPane) CycleAutocompleteBack() bool {
728         if h.Cursor.HasSelection() {
729                 return false
730         }
731
732         if h.Buf.HasSuggestions {
733                 h.Buf.CycleAutocomplete(false)
734                 return true
735         }
736         return false
737 }
738
739 // InsertTab inserts a tab or spaces
740 func (h *BufPane) InsertTab() bool {
741         b := h.Buf
742         indent := b.IndentString(util.IntOpt(b.Settings["tabsize"]))
743         tabBytes := len(indent)
744         bytesUntilIndent := tabBytes - (h.Cursor.GetVisualX() % tabBytes)
745         b.Insert(h.Cursor.Loc, indent[:bytesUntilIndent])
746         h.Relocate()
747         return true
748 }
749
750 // SaveAll saves all open buffers
751 func (h *BufPane) SaveAll() bool {
752         for _, b := range buffer.OpenBuffers {
753                 b.Save()
754         }
755         return true
756 }
757
758 // SaveCB performs a save and does a callback at the very end (after all prompts have been resolved)
759 func (h *BufPane) SaveCB(action string, callback func()) bool {
760         // If this is an empty buffer, ask for a filename
761         if h.Buf.Path == "" {
762                 h.SaveAsCB(action, callback)
763         } else {
764                 noPrompt := h.saveBufToFile(h.Buf.Path, action, callback)
765                 if noPrompt {
766                         return true
767                 }
768         }
769         return false
770 }
771
772 // Save the buffer to disk
773 func (h *BufPane) Save() bool {
774         return h.SaveCB("Save", nil)
775 }
776
777 // SaveAsCB performs a save as and does a callback at the very end (after all prompts have been resolved)
778 // The callback is only called if the save was successful
779 func (h *BufPane) SaveAsCB(action string, callback func()) bool {
780         InfoBar.Prompt("Filename: ", "", "Save", nil, func(resp string, canceled bool) {
781                 if !canceled {
782                         // the filename might or might not be quoted, so unquote first then join the strings.
783                         args, err := shellquote.Split(resp)
784                         if err != nil {
785                                 InfoBar.Error("Error parsing arguments: ", err)
786                                 return
787                         }
788                         if len(args) == 0 {
789                                 InfoBar.Error("No filename given")
790                                 return
791                         }
792                         filename := strings.Join(args, " ")
793                         noPrompt := h.saveBufToFile(filename, action, callback)
794                         if noPrompt {
795                                 h.completeAction(action)
796                         }
797                 }
798         })
799         return false
800 }
801
802 // SaveAs saves the buffer to disk with the given name
803 func (h *BufPane) SaveAs() bool {
804         return h.SaveAsCB("SaveAs", nil)
805 }
806
807 // This function saves the buffer to `filename` and changes the buffer's path and name
808 // to `filename` if the save is successful
809 // The callback is only called if the save was successful
810 func (h *BufPane) saveBufToFile(filename string, action string, callback func()) bool {
811         err := h.Buf.SaveAs(filename)
812         if err != nil {
813                 if errors.Is(err, fs.ErrPermission) {
814                         saveWithSudo := func() {
815                                 err = h.Buf.SaveAsWithSudo(filename)
816                                 if err != nil {
817                                         InfoBar.Error(err)
818                                 } else {
819                                         h.Buf.Path = filename
820                                         h.Buf.SetName(filename)
821                                         InfoBar.Message("Saved " + filename)
822                                         if callback != nil {
823                                                 callback()
824                                         }
825                                 }
826                         }
827                         if h.Buf.Settings["autosu"].(bool) {
828                                 saveWithSudo()
829                         } else {
830                                 InfoBar.YNPrompt(
831                                         fmt.Sprintf("Permission denied. Do you want to save this file using %s? (y,n)", config.GlobalSettings["sucmd"].(string)),
832                                         func(yes, canceled bool) {
833                                                 if yes && !canceled {
834                                                         saveWithSudo()
835                                                         h.completeAction(action)
836                                                 }
837                                         },
838                                 )
839                                 return false
840                         }
841                 } else {
842                         InfoBar.Error(err)
843                 }
844         } else {
845                 h.Buf.Path = filename
846                 h.Buf.SetName(filename)
847                 InfoBar.Message("Saved " + filename)
848                 if callback != nil {
849                         callback()
850                 }
851         }
852         return true
853 }
854
855 // Find opens a prompt and searches forward for the input
856 func (h *BufPane) Find() bool {
857         return h.find(true)
858 }
859
860 // FindLiteral is the same as Find() but does not support regular expressions
861 func (h *BufPane) FindLiteral() bool {
862         return h.find(false)
863 }
864
865 // Search searches for a given string/regex in the buffer and selects the next
866 // match if a match is found
867 // This function behaves the same way as Find and FindLiteral actions:
868 // it affects the buffer's LastSearch and LastSearchRegex (saved searches)
869 // for use with FindNext and FindPrevious, and turns HighlightSearch on or off
870 // according to hlsearch setting
871 func (h *BufPane) Search(str string, useRegex bool, searchDown bool) error {
872         match, found, err := h.Buf.FindNext(str, h.Buf.Start(), h.Buf.End(), h.Cursor.Loc, searchDown, useRegex)
873         if err != nil {
874                 return err
875         }
876         if found {
877                 h.Cursor.SetSelectionStart(match[0])
878                 h.Cursor.SetSelectionEnd(match[1])
879                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
880                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
881                 h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
882                 h.Buf.LastSearch = str
883                 h.Buf.LastSearchRegex = useRegex
884                 h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
885                 h.Relocate()
886         } else {
887                 h.Cursor.ResetSelection()
888         }
889         return nil
890 }
891
892 func (h *BufPane) find(useRegex bool) bool {
893         h.searchOrig = h.Cursor.Loc
894         prompt := "Find: "
895         if useRegex {
896                 prompt = "Find (regex): "
897         }
898         var eventCallback func(resp string)
899         if h.Buf.Settings["incsearch"].(bool) {
900                 eventCallback = func(resp string) {
901                         match, found, _ := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
902                         if found {
903                                 h.Cursor.SetSelectionStart(match[0])
904                                 h.Cursor.SetSelectionEnd(match[1])
905                                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
906                                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
907                                 h.Cursor.GotoLoc(match[1])
908                         } else {
909                                 h.Cursor.GotoLoc(h.searchOrig)
910                                 h.Cursor.ResetSelection()
911                         }
912                         h.Relocate()
913                 }
914         }
915         findCallback := func(resp string, canceled bool) {
916                 // Finished callback
917                 if !canceled {
918                         match, found, err := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
919                         if err != nil {
920                                 InfoBar.Error(err)
921                         }
922                         if found {
923                                 h.Cursor.SetSelectionStart(match[0])
924                                 h.Cursor.SetSelectionEnd(match[1])
925                                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
926                                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
927                                 h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
928                                 h.Buf.LastSearch = resp
929                                 h.Buf.LastSearchRegex = useRegex
930                                 h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
931                         } else {
932                                 h.Cursor.ResetSelection()
933                                 InfoBar.Message("No matches found")
934                         }
935                 } else {
936                         h.Cursor.ResetSelection()
937                 }
938                 h.Relocate()
939         }
940         pattern := string(h.Cursor.GetSelection())
941         if eventCallback != nil && pattern != "" {
942                 eventCallback(pattern)
943         }
944         InfoBar.Prompt(prompt, pattern, "Find", eventCallback, findCallback)
945         if pattern != "" {
946                 InfoBar.SelectAll()
947         }
948         return true
949 }
950
951 // ToggleHighlightSearch toggles highlighting all instances of the last used search term
952 func (h *BufPane) ToggleHighlightSearch() bool {
953         h.Buf.HighlightSearch = !h.Buf.HighlightSearch
954         return true
955 }
956
957 // UnhighlightSearch unhighlights all instances of the last used search term
958 func (h *BufPane) UnhighlightSearch() bool {
959         h.Buf.HighlightSearch = false
960         return true
961 }
962
963 // FindNext searches forwards for the last used search term
964 func (h *BufPane) FindNext() bool {
965         // If the cursor is at the start of a selection and we search we want
966         // to search from the end of the selection in the case that
967         // the selection is a search result in which case we wouldn't move at
968         // at all which would be bad
969         searchLoc := h.Cursor.Loc
970         if h.Cursor.HasSelection() {
971                 searchLoc = h.Cursor.CurSelection[1]
972         }
973         match, found, err := h.Buf.FindNext(h.Buf.LastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, true, h.Buf.LastSearchRegex)
974         if err != nil {
975                 InfoBar.Error(err)
976         }
977         if found {
978                 h.Cursor.SetSelectionStart(match[0])
979                 h.Cursor.SetSelectionEnd(match[1])
980                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
981                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
982                 h.Cursor.Loc = h.Cursor.CurSelection[1]
983         } else {
984                 h.Cursor.ResetSelection()
985         }
986         h.Relocate()
987         return true
988 }
989
990 // FindPrevious searches backwards for the last used search term
991 func (h *BufPane) FindPrevious() bool {
992         // If the cursor is at the end of a selection and we search we want
993         // to search from the beginning of the selection in the case that
994         // the selection is a search result in which case we wouldn't move at
995         // at all which would be bad
996         searchLoc := h.Cursor.Loc
997         if h.Cursor.HasSelection() {
998                 searchLoc = h.Cursor.CurSelection[0]
999         }
1000         match, found, err := h.Buf.FindNext(h.Buf.LastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, false, h.Buf.LastSearchRegex)
1001         if err != nil {
1002                 InfoBar.Error(err)
1003         }
1004         if found {
1005                 h.Cursor.SetSelectionStart(match[0])
1006                 h.Cursor.SetSelectionEnd(match[1])
1007                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
1008                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
1009                 h.Cursor.Loc = h.Cursor.CurSelection[1]
1010         } else {
1011                 h.Cursor.ResetSelection()
1012         }
1013         h.Relocate()
1014         return true
1015 }
1016
1017 // Undo undoes the last action
1018 func (h *BufPane) Undo() bool {
1019         h.Buf.Undo()
1020         InfoBar.Message("Undid action")
1021         h.Relocate()
1022         return true
1023 }
1024
1025 // Redo redoes the last action
1026 func (h *BufPane) Redo() bool {
1027         h.Buf.Redo()
1028         InfoBar.Message("Redid action")
1029         h.Relocate()
1030         return true
1031 }
1032
1033 // Copy the selection to the system clipboard
1034 func (h *BufPane) Copy() bool {
1035         if h.Cursor.HasSelection() {
1036                 h.Cursor.CopySelection(clipboard.ClipboardReg)
1037                 h.freshClip = true
1038                 InfoBar.Message("Copied selection")
1039         }
1040         h.Relocate()
1041         return true
1042 }
1043
1044 // CopyLine copies the current line to the clipboard
1045 func (h *BufPane) CopyLine() bool {
1046         if h.Cursor.HasSelection() {
1047                 return false
1048         }
1049         h.Cursor.SelectLine()
1050         h.Cursor.CopySelection(clipboard.ClipboardReg)
1051         h.freshClip = true
1052         InfoBar.Message("Copied line")
1053
1054         h.Cursor.Deselect(true)
1055         h.Relocate()
1056         return true
1057 }
1058
1059 // CutLine cuts the current line to the clipboard
1060 func (h *BufPane) CutLine() bool {
1061         h.Cursor.SelectLine()
1062         if !h.Cursor.HasSelection() {
1063                 return false
1064         }
1065         if h.freshClip {
1066                 if h.Cursor.HasSelection() {
1067                         if clip, err := clipboard.Read(clipboard.ClipboardReg); err != nil {
1068                                 InfoBar.Error(err)
1069                         } else {
1070                                 clipboard.WriteMulti(clip+string(h.Cursor.GetSelection()), clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
1071                         }
1072                 }
1073         } else if time.Since(h.lastCutTime)/time.Second > 10*time.Second || !h.freshClip {
1074                 h.Copy()
1075         }
1076         h.freshClip = true
1077         h.lastCutTime = time.Now()
1078         h.Cursor.DeleteSelection()
1079         h.Cursor.ResetSelection()
1080         InfoBar.Message("Cut line")
1081         h.Relocate()
1082         return true
1083 }
1084
1085 // Cut the selection to the system clipboard
1086 func (h *BufPane) Cut() bool {
1087         if h.Cursor.HasSelection() {
1088                 h.Cursor.CopySelection(clipboard.ClipboardReg)
1089                 h.Cursor.DeleteSelection()
1090                 h.Cursor.ResetSelection()
1091                 h.freshClip = true
1092                 InfoBar.Message("Cut selection")
1093
1094                 h.Relocate()
1095                 return true
1096         }
1097         return h.CutLine()
1098 }
1099
1100 // DuplicateLine duplicates the current line or selection
1101 func (h *BufPane) DuplicateLine() bool {
1102         var infoMessage = "Duplicated line"
1103         if h.Cursor.HasSelection() {
1104                 infoMessage = "Duplicated selection"
1105                 h.Buf.Insert(h.Cursor.CurSelection[1], string(h.Cursor.GetSelection()))
1106         } else {
1107                 h.Cursor.End()
1108                 h.Buf.Insert(h.Cursor.Loc, "\n"+string(h.Buf.LineBytes(h.Cursor.Y)))
1109                 // h.Cursor.Right()
1110         }
1111
1112         InfoBar.Message(infoMessage)
1113         h.Relocate()
1114         return true
1115 }
1116
1117 // DeleteLine deletes the current line
1118 func (h *BufPane) DeleteLine() bool {
1119         h.Cursor.SelectLine()
1120         if !h.Cursor.HasSelection() {
1121                 return false
1122         }
1123         h.Cursor.DeleteSelection()
1124         h.Cursor.ResetSelection()
1125         InfoBar.Message("Deleted line")
1126         h.Relocate()
1127         return true
1128 }
1129
1130 // MoveLinesUp moves up the current line or selected lines if any
1131 func (h *BufPane) MoveLinesUp() bool {
1132         if h.Cursor.HasSelection() {
1133                 if h.Cursor.CurSelection[0].Y == 0 {
1134                         InfoBar.Message("Cannot move further up")
1135                         return false
1136                 }
1137                 start := h.Cursor.CurSelection[0].Y
1138                 end := h.Cursor.CurSelection[1].Y
1139                 sel := 1
1140                 if start > end {
1141                         end, start = start, end
1142                         sel = 0
1143                 }
1144
1145                 compensate := false
1146                 if h.Cursor.CurSelection[sel].X != 0 {
1147                         end++
1148                 } else {
1149                         compensate = true
1150                 }
1151
1152                 h.Buf.MoveLinesUp(
1153                         start,
1154                         end,
1155                 )
1156                 if compensate {
1157                         h.Cursor.CurSelection[sel].Y -= 1
1158                 }
1159         } else {
1160                 if h.Cursor.Loc.Y == 0 {
1161                         InfoBar.Message("Cannot move further up")
1162                         return false
1163                 }
1164                 h.Buf.MoveLinesUp(
1165                         h.Cursor.Loc.Y,
1166                         h.Cursor.Loc.Y+1,
1167                 )
1168         }
1169
1170         h.Relocate()
1171         return true
1172 }
1173
1174 // MoveLinesDown moves down the current line or selected lines if any
1175 func (h *BufPane) MoveLinesDown() bool {
1176         if h.Cursor.HasSelection() {
1177                 if h.Cursor.CurSelection[1].Y >= h.Buf.LinesNum() {
1178                         InfoBar.Message("Cannot move further down")
1179                         return false
1180                 }
1181                 start := h.Cursor.CurSelection[0].Y
1182                 end := h.Cursor.CurSelection[1].Y
1183                 sel := 1
1184                 if start > end {
1185                         end, start = start, end
1186                         sel = 0
1187                 }
1188
1189                 if h.Cursor.CurSelection[sel].X != 0 {
1190                         end++
1191                 }
1192
1193                 h.Buf.MoveLinesDown(
1194                         start,
1195                         end,
1196                 )
1197         } else {
1198                 if h.Cursor.Loc.Y >= h.Buf.LinesNum()-1 {
1199                         InfoBar.Message("Cannot move further down")
1200                         return false
1201                 }
1202                 h.Buf.MoveLinesDown(
1203                         h.Cursor.Loc.Y,
1204                         h.Cursor.Loc.Y+1,
1205                 )
1206         }
1207
1208         h.Relocate()
1209         return true
1210 }
1211
1212 // Paste whatever is in the system clipboard into the buffer
1213 // Delete and paste if the user has a selection
1214 func (h *BufPane) Paste() bool {
1215         clip, err := clipboard.ReadMulti(clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
1216         if err != nil {
1217                 InfoBar.Error(err)
1218         } else {
1219                 h.paste(clip)
1220         }
1221         h.Relocate()
1222         return true
1223 }
1224
1225 // PastePrimary pastes from the primary clipboard (only use on linux)
1226 func (h *BufPane) PastePrimary() bool {
1227         clip, err := clipboard.ReadMulti(clipboard.PrimaryReg, h.Cursor.Num, h.Buf.NumCursors())
1228         if err != nil {
1229                 InfoBar.Error(err)
1230         } else {
1231                 h.paste(clip)
1232         }
1233         h.Relocate()
1234         return true
1235 }
1236
1237 func (h *BufPane) paste(clip string) {
1238         if h.Buf.Settings["smartpaste"].(bool) {
1239                 if h.Cursor.X > 0 && len(util.GetLeadingWhitespace([]byte(strings.TrimLeft(clip, "\r\n")))) == 0 {
1240                         leadingWS := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))
1241                         clip = strings.ReplaceAll(clip, "\n", "\n"+string(leadingWS))
1242                 }
1243         }
1244
1245         if h.Cursor.HasSelection() {
1246                 h.Cursor.DeleteSelection()
1247                 h.Cursor.ResetSelection()
1248         }
1249
1250         h.Buf.Insert(h.Cursor.Loc, clip)
1251         // h.Cursor.Loc = h.Cursor.Loc.Move(Count(clip), h.Buf)
1252         h.freshClip = false
1253         InfoBar.Message("Pasted clipboard")
1254 }
1255
1256 // JumpToMatchingBrace moves the cursor to the matching brace if it is
1257 // currently on a brace
1258 func (h *BufPane) JumpToMatchingBrace() bool {
1259         for _, bp := range buffer.BracePairs {
1260                 r := h.Cursor.RuneUnder(h.Cursor.X)
1261                 rl := h.Cursor.RuneUnder(h.Cursor.X - 1)
1262                 if r == bp[0] || r == bp[1] || rl == bp[0] || rl == bp[1] {
1263                         matchingBrace, left, found := h.Buf.FindMatchingBrace(bp, h.Cursor.Loc)
1264                         if found {
1265                                 if left {
1266                                         h.Cursor.GotoLoc(matchingBrace)
1267                                 } else {
1268                                         h.Cursor.GotoLoc(matchingBrace.Move(1, h.Buf))
1269                                 }
1270                                 break
1271                         } else {
1272                                 return false
1273                         }
1274                 }
1275         }
1276
1277         h.Relocate()
1278         return true
1279 }
1280
1281 // SelectAll selects the entire buffer
1282 func (h *BufPane) SelectAll() bool {
1283         h.Cursor.SetSelectionStart(h.Buf.Start())
1284         h.Cursor.SetSelectionEnd(h.Buf.End())
1285         // Put the cursor at the beginning
1286         h.Cursor.X = 0
1287         h.Cursor.Y = 0
1288         h.Relocate()
1289         return true
1290 }
1291
1292 // OpenFile opens a new file in the buffer
1293 func (h *BufPane) OpenFile() bool {
1294         InfoBar.Prompt("> ", "open ", "Open", nil, func(resp string, canceled bool) {
1295                 if !canceled {
1296                         h.HandleCommand(resp)
1297                 }
1298         })
1299         return true
1300 }
1301
1302 // OpenFile opens a new file in the buffer
1303 func (h *BufPane) JumpLine() bool {
1304         InfoBar.Prompt("> ", "goto ", "Command", nil, func(resp string, canceled bool) {
1305                 if !canceled {
1306                         h.HandleCommand(resp)
1307                 }
1308         })
1309         return true
1310 }
1311
1312 // Start moves the viewport to the start of the buffer
1313 func (h *BufPane) Start() bool {
1314         v := h.GetView()
1315         v.StartLine = display.SLoc{0, 0}
1316         h.SetView(v)
1317         return true
1318 }
1319
1320 // End moves the viewport to the end of the buffer
1321 func (h *BufPane) End() bool {
1322         v := h.GetView()
1323         v.StartLine = h.Scroll(h.SLocFromLoc(h.Buf.End()), -h.BufView().Height+1)
1324         h.SetView(v)
1325         return true
1326 }
1327
1328 // PageUp scrolls the view up a page
1329 func (h *BufPane) PageUp() bool {
1330         h.ScrollUp(h.BufView().Height)
1331         return true
1332 }
1333
1334 // PageDown scrolls the view down a page
1335 func (h *BufPane) PageDown() bool {
1336         h.ScrollDown(h.BufView().Height)
1337         h.ScrollAdjust()
1338         return true
1339 }
1340
1341 // SelectPageUp selects up one page
1342 func (h *BufPane) SelectPageUp() bool {
1343         if !h.Cursor.HasSelection() {
1344                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
1345         }
1346         h.MoveCursorUp(h.BufView().Height)
1347         h.Cursor.SelectTo(h.Cursor.Loc)
1348         h.Relocate()
1349         return true
1350 }
1351
1352 // SelectPageDown selects down one page
1353 func (h *BufPane) SelectPageDown() bool {
1354         if !h.Cursor.HasSelection() {
1355                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
1356         }
1357         h.MoveCursorDown(h.BufView().Height)
1358         h.Cursor.SelectTo(h.Cursor.Loc)
1359         h.Relocate()
1360         return true
1361 }
1362
1363 // CursorPageUp places the cursor a page up
1364 func (h *BufPane) CursorPageUp() bool {
1365         h.Cursor.Deselect(true)
1366
1367         if h.Cursor.HasSelection() {
1368                 h.Cursor.Loc = h.Cursor.CurSelection[0]
1369                 h.Cursor.ResetSelection()
1370                 h.Cursor.StoreVisualX()
1371         }
1372         h.MoveCursorUp(h.BufView().Height)
1373         h.Relocate()
1374         return true
1375 }
1376
1377 // CursorPageDown places the cursor a page up
1378 func (h *BufPane) CursorPageDown() bool {
1379         h.Cursor.Deselect(false)
1380
1381         if h.Cursor.HasSelection() {
1382                 h.Cursor.Loc = h.Cursor.CurSelection[1]
1383                 h.Cursor.ResetSelection()
1384                 h.Cursor.StoreVisualX()
1385         }
1386         h.MoveCursorDown(h.BufView().Height)
1387         h.Relocate()
1388         return true
1389 }
1390
1391 // HalfPageUp scrolls the view up half a page
1392 func (h *BufPane) HalfPageUp() bool {
1393         h.ScrollUp(h.BufView().Height / 2)
1394         return true
1395 }
1396
1397 // HalfPageDown scrolls the view down half a page
1398 func (h *BufPane) HalfPageDown() bool {
1399         h.ScrollDown(h.BufView().Height / 2)
1400         h.ScrollAdjust()
1401         return true
1402 }
1403
1404 // ToggleDiffGutter turns the diff gutter off and on
1405 func (h *BufPane) ToggleDiffGutter() bool {
1406         if !h.Buf.Settings["diffgutter"].(bool) {
1407                 h.Buf.Settings["diffgutter"] = true
1408                 h.Buf.UpdateDiff(func(synchronous bool) {
1409                         screen.Redraw()
1410                 })
1411                 InfoBar.Message("Enabled diff gutter")
1412         } else {
1413                 h.Buf.Settings["diffgutter"] = false
1414                 InfoBar.Message("Disabled diff gutter")
1415         }
1416         return true
1417 }
1418
1419 // ToggleRuler turns line numbers off and on
1420 func (h *BufPane) ToggleRuler() bool {
1421         if !h.Buf.Settings["ruler"].(bool) {
1422                 h.Buf.Settings["ruler"] = true
1423                 InfoBar.Message("Enabled ruler")
1424         } else {
1425                 h.Buf.Settings["ruler"] = false
1426                 InfoBar.Message("Disabled ruler")
1427         }
1428         return true
1429 }
1430
1431 // ClearStatus clears the messenger bar
1432 func (h *BufPane) ClearStatus() bool {
1433         InfoBar.Message("")
1434         return true
1435 }
1436
1437 // ToggleHelp toggles the help screen
1438 func (h *BufPane) ToggleHelp() bool {
1439         if h.Buf.Type == buffer.BTHelp {
1440                 h.Quit()
1441         } else {
1442                 h.openHelp("help")
1443         }
1444         return true
1445 }
1446
1447 // ToggleKeyMenu toggles the keymenu option and resizes all tabs
1448 func (h *BufPane) ToggleKeyMenu() bool {
1449         config.GlobalSettings["keymenu"] = !config.GetGlobalOption("keymenu").(bool)
1450         Tabs.Resize()
1451         return true
1452 }
1453
1454 // ShellMode opens a terminal to run a shell command
1455 func (h *BufPane) ShellMode() bool {
1456         InfoBar.Prompt("$ ", "", "Shell", nil, func(resp string, canceled bool) {
1457                 if !canceled {
1458                         // The true here is for openTerm to make the command interactive
1459                         shell.RunInteractiveShell(resp, true, false)
1460                 }
1461         })
1462
1463         return true
1464 }
1465
1466 // CommandMode lets the user enter a command
1467 func (h *BufPane) CommandMode() bool {
1468         InfoBar.Prompt("> ", "", "Command", nil, func(resp string, canceled bool) {
1469                 if !canceled {
1470                         h.HandleCommand(resp)
1471                 }
1472         })
1473         return true
1474 }
1475
1476 // ToggleOverwriteMode lets the user toggle the text overwrite mode
1477 func (h *BufPane) ToggleOverwriteMode() bool {
1478         h.isOverwriteMode = !h.isOverwriteMode
1479         return true
1480 }
1481
1482 // Escape leaves current mode
1483 func (h *BufPane) Escape() bool {
1484         return true
1485 }
1486
1487 // Deselect deselects on the current cursor
1488 func (h *BufPane) Deselect() bool {
1489         h.Cursor.Deselect(true)
1490         return true
1491 }
1492
1493 // ClearInfo clears the infobar
1494 func (h *BufPane) ClearInfo() bool {
1495         InfoBar.Message("")
1496         return true
1497 }
1498
1499 // ForceQuit closes the current tab or view even if there are unsaved changes
1500 // (no prompt)
1501 func (h *BufPane) ForceQuit() bool {
1502         h.Buf.Close()
1503         if len(MainTab().Panes) > 1 {
1504                 h.Unsplit()
1505         } else if len(Tabs.List) > 1 {
1506                 Tabs.RemoveTab(h.splitID)
1507         } else {
1508                 screen.Screen.Fini()
1509                 InfoBar.Close()
1510                 runtime.Goexit()
1511         }
1512         return true
1513 }
1514
1515 // Quit this will close the current tab or view that is open
1516 func (h *BufPane) Quit() bool {
1517         if h.Buf.Modified() {
1518                 if config.GlobalSettings["autosave"].(float64) > 0 {
1519                         // autosave on means we automatically save when quitting
1520                         h.SaveCB("Quit", func() {
1521                                 h.ForceQuit()
1522                         })
1523                 } else {
1524                         InfoBar.YNPrompt("Save changes to "+h.Buf.GetName()+" before closing? (y,n,esc)", func(yes, canceled bool) {
1525                                 if !canceled && !yes {
1526                                         h.ForceQuit()
1527                                 } else if !canceled && yes {
1528                                         h.SaveCB("Quit", func() {
1529                                                 h.ForceQuit()
1530                                         })
1531                                 }
1532                         })
1533                 }
1534         } else {
1535                 h.ForceQuit()
1536         }
1537         return true
1538 }
1539
1540 // QuitAll quits the whole editor; all splits and tabs
1541 func (h *BufPane) QuitAll() bool {
1542         anyModified := false
1543         for _, b := range buffer.OpenBuffers {
1544                 if b.Modified() {
1545                         anyModified = true
1546                         break
1547                 }
1548         }
1549
1550         quit := func() {
1551                 for _, b := range buffer.OpenBuffers {
1552                         b.Close()
1553                 }
1554                 screen.Screen.Fini()
1555                 InfoBar.Close()
1556                 runtime.Goexit()
1557         }
1558
1559         if anyModified {
1560                 InfoBar.YNPrompt("Quit micro? (all open buffers will be closed without saving)", func(yes, canceled bool) {
1561                         if !canceled && yes {
1562                                 quit()
1563                         }
1564                 })
1565         } else {
1566                 quit()
1567         }
1568
1569         return true
1570 }
1571
1572 // AddTab adds a new tab with an empty buffer
1573 func (h *BufPane) AddTab() bool {
1574         width, height := screen.Screen.Size()
1575         iOffset := config.GetInfoBarOffset()
1576         b := buffer.NewBufferFromString("", "", buffer.BTDefault)
1577         tp := NewTabFromBuffer(0, 0, width, height-iOffset, b)
1578         Tabs.AddTab(tp)
1579         Tabs.SetActive(len(Tabs.List) - 1)
1580
1581         return true
1582 }
1583
1584 // PreviousTab switches to the previous tab in the tab list
1585 func (h *BufPane) PreviousTab() bool {
1586         tabsLen := len(Tabs.List)
1587         a := Tabs.Active() + tabsLen
1588         Tabs.SetActive((a - 1) % tabsLen)
1589
1590         return true
1591 }
1592
1593 // NextTab switches to the next tab in the tab list
1594 func (h *BufPane) NextTab() bool {
1595         a := Tabs.Active()
1596         Tabs.SetActive((a + 1) % len(Tabs.List))
1597
1598         return true
1599 }
1600
1601 // VSplitAction opens an empty vertical split
1602 func (h *BufPane) VSplitAction() bool {
1603         h.VSplitBuf(buffer.NewBufferFromString("", "", buffer.BTDefault))
1604
1605         return true
1606 }
1607
1608 // HSplitAction opens an empty horizontal split
1609 func (h *BufPane) HSplitAction() bool {
1610         h.HSplitBuf(buffer.NewBufferFromString("", "", buffer.BTDefault))
1611
1612         return true
1613 }
1614
1615 // Unsplit closes all splits in the current tab except the active one
1616 func (h *BufPane) Unsplit() bool {
1617         tab := h.tab
1618         n := tab.GetNode(h.splitID)
1619         ok := n.Unsplit()
1620         if ok {
1621                 tab.RemovePane(tab.GetPane(h.splitID))
1622                 tab.Resize()
1623                 tab.SetActive(len(tab.Panes) - 1)
1624
1625                 return true
1626         }
1627         return false
1628 }
1629
1630 // NextSplit changes the view to the next split
1631 func (h *BufPane) NextSplit() bool {
1632         a := h.tab.active
1633         if a < len(h.tab.Panes)-1 {
1634                 a++
1635         } else {
1636                 a = 0
1637         }
1638
1639         h.tab.SetActive(a)
1640
1641         return true
1642 }
1643
1644 // PreviousSplit changes the view to the previous split
1645 func (h *BufPane) PreviousSplit() bool {
1646         a := h.tab.active
1647         if a > 0 {
1648                 a--
1649         } else {
1650                 a = len(h.tab.Panes) - 1
1651         }
1652         h.tab.SetActive(a)
1653
1654         return true
1655 }
1656
1657 var curmacro []interface{}
1658 var recordingMacro bool
1659
1660 // ToggleMacro toggles recording of a macro
1661 func (h *BufPane) ToggleMacro() bool {
1662         recordingMacro = !recordingMacro
1663         if recordingMacro {
1664                 curmacro = []interface{}{}
1665                 InfoBar.Message("Recording")
1666         } else {
1667                 InfoBar.Message("Stopped recording")
1668         }
1669         h.Relocate()
1670         return true
1671 }
1672
1673 // PlayMacro plays back the most recently recorded macro
1674 func (h *BufPane) PlayMacro() bool {
1675         if recordingMacro {
1676                 return false
1677         }
1678         for _, action := range curmacro {
1679                 switch t := action.(type) {
1680                 case rune:
1681                         h.DoRuneInsert(t)
1682                 case func(*BufPane) bool:
1683                         t(h)
1684                 }
1685         }
1686         h.Relocate()
1687         return true
1688 }
1689
1690 // SpawnMultiCursor creates a new multiple cursor at the next occurrence of the current selection or current word
1691 func (h *BufPane) SpawnMultiCursor() bool {
1692         spawner := h.Buf.GetCursor(h.Buf.NumCursors() - 1)
1693         if !spawner.HasSelection() {
1694                 spawner.SelectWord()
1695                 h.multiWord = true
1696                 h.Relocate()
1697                 return true
1698         }
1699
1700         sel := spawner.GetSelection()
1701         searchStart := spawner.CurSelection[1]
1702
1703         search := string(sel)
1704         search = regexp.QuoteMeta(search)
1705         if h.multiWord {
1706                 search = "\\b" + search + "\\b"
1707         }
1708         match, found, err := h.Buf.FindNext(search, h.Buf.Start(), h.Buf.End(), searchStart, true, true)
1709         if err != nil {
1710                 InfoBar.Error(err)
1711         }
1712         if found {
1713                 c := buffer.NewCursor(h.Buf, buffer.Loc{})
1714                 c.SetSelectionStart(match[0])
1715                 c.SetSelectionEnd(match[1])
1716                 c.OrigSelection[0] = c.CurSelection[0]
1717                 c.OrigSelection[1] = c.CurSelection[1]
1718                 c.Loc = c.CurSelection[1]
1719
1720                 h.Buf.AddCursor(c)
1721                 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1722                 h.Buf.MergeCursors()
1723         } else {
1724                 InfoBar.Message("No matches found")
1725         }
1726
1727         h.Relocate()
1728         return true
1729 }
1730
1731 // SpawnMultiCursorUp creates additional cursor, at the same X (if possible), one Y less.
1732 func (h *BufPane) SpawnMultiCursorUp() bool {
1733         if h.Cursor.Y == 0 {
1734                 return false
1735         }
1736         h.Cursor.GotoLoc(buffer.Loc{h.Cursor.X, h.Cursor.Y - 1})
1737         h.Cursor.Relocate()
1738
1739         c := buffer.NewCursor(h.Buf, buffer.Loc{h.Cursor.X, h.Cursor.Y + 1})
1740         h.Buf.AddCursor(c)
1741         h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1742         h.Buf.MergeCursors()
1743
1744         h.Relocate()
1745         return true
1746 }
1747
1748 // SpawnMultiCursorDown creates additional cursor, at the same X (if possible), one Y more.
1749 func (h *BufPane) SpawnMultiCursorDown() bool {
1750         if h.Cursor.Y+1 == h.Buf.LinesNum() {
1751                 return false
1752         }
1753         h.Cursor.GotoLoc(buffer.Loc{h.Cursor.X, h.Cursor.Y + 1})
1754         h.Cursor.Relocate()
1755
1756         c := buffer.NewCursor(h.Buf, buffer.Loc{h.Cursor.X, h.Cursor.Y - 1})
1757         h.Buf.AddCursor(c)
1758         h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1759         h.Buf.MergeCursors()
1760         h.Relocate()
1761         return true
1762 }
1763
1764 // SpawnMultiCursorSelect adds a cursor at the beginning of each line of a selection
1765 func (h *BufPane) SpawnMultiCursorSelect() bool {
1766         // Avoid cases where multiple cursors already exist, that would create problems
1767         if h.Buf.NumCursors() > 1 {
1768                 return false
1769         }
1770
1771         var startLine int
1772         var endLine int
1773
1774         a, b := h.Cursor.CurSelection[0].Y, h.Cursor.CurSelection[1].Y
1775         if a > b {
1776                 startLine, endLine = b, a
1777         } else {
1778                 startLine, endLine = a, b
1779         }
1780
1781         if h.Cursor.HasSelection() {
1782                 h.Cursor.ResetSelection()
1783                 h.Cursor.GotoLoc(buffer.Loc{0, startLine})
1784
1785                 for i := startLine; i <= endLine; i++ {
1786                         c := buffer.NewCursor(h.Buf, buffer.Loc{0, i})
1787                         c.StoreVisualX()
1788                         h.Buf.AddCursor(c)
1789                 }
1790                 h.Buf.MergeCursors()
1791         } else {
1792                 return false
1793         }
1794         InfoBar.Message("Added cursors from selection")
1795         return true
1796 }
1797
1798 // MouseMultiCursor is a mouse action which puts a new cursor at the mouse position
1799 func (h *BufPane) MouseMultiCursor(e *tcell.EventMouse) bool {
1800         b := h.Buf
1801         mx, my := e.Position()
1802         mouseLoc := h.LocFromVisual(buffer.Loc{X: mx, Y: my})
1803         c := buffer.NewCursor(b, mouseLoc)
1804         b.AddCursor(c)
1805         b.MergeCursors()
1806
1807         return true
1808 }
1809
1810 // SkipMultiCursor moves the current multiple cursor to the next available position
1811 func (h *BufPane) SkipMultiCursor() bool {
1812         lastC := h.Buf.GetCursor(h.Buf.NumCursors() - 1)
1813         sel := lastC.GetSelection()
1814         searchStart := lastC.CurSelection[1]
1815
1816         search := string(sel)
1817         search = regexp.QuoteMeta(search)
1818         if h.multiWord {
1819                 search = "\\b" + search + "\\b"
1820         }
1821
1822         match, found, err := h.Buf.FindNext(search, h.Buf.Start(), h.Buf.End(), searchStart, true, true)
1823         if err != nil {
1824                 InfoBar.Error(err)
1825         }
1826         if found {
1827                 lastC.SetSelectionStart(match[0])
1828                 lastC.SetSelectionEnd(match[1])
1829                 lastC.OrigSelection[0] = lastC.CurSelection[0]
1830                 lastC.OrigSelection[1] = lastC.CurSelection[1]
1831                 lastC.Loc = lastC.CurSelection[1]
1832
1833                 h.Buf.MergeCursors()
1834                 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1835         } else {
1836                 InfoBar.Message("No matches found")
1837         }
1838         h.Relocate()
1839         return true
1840 }
1841
1842 // RemoveMultiCursor removes the latest multiple cursor
1843 func (h *BufPane) RemoveMultiCursor() bool {
1844         if h.Buf.NumCursors() > 1 {
1845                 h.Buf.RemoveCursor(h.Buf.NumCursors() - 1)
1846                 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1847                 h.Buf.UpdateCursors()
1848         } else {
1849                 h.multiWord = false
1850         }
1851         h.Relocate()
1852         return true
1853 }
1854
1855 // RemoveAllMultiCursors removes all cursors except the base cursor
1856 func (h *BufPane) RemoveAllMultiCursors() bool {
1857         h.Buf.ClearCursors()
1858         h.multiWord = false
1859         h.Relocate()
1860         return true
1861 }
1862
1863 // None is an action that does nothing
1864 func (h *BufPane) None() bool {
1865         return true
1866 }