]> git.lizzy.rs Git - micro.git/blob - internal/action/actions.go
Fix cursor position change after CopyLine command (#2353)
[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
13         shellquote "github.com/kballard/go-shellquote"
14         "github.com/zyedidia/micro/v2/internal/buffer"
15         "github.com/zyedidia/micro/v2/internal/clipboard"
16         "github.com/zyedidia/micro/v2/internal/config"
17         "github.com/zyedidia/micro/v2/internal/display"
18         "github.com/zyedidia/micro/v2/internal/screen"
19         "github.com/zyedidia/micro/v2/internal/shell"
20         "github.com/zyedidia/micro/v2/internal/util"
21         "github.com/zyedidia/tcell/v2"
22 )
23
24 // ScrollUp is not an action
25 func (h *BufPane) ScrollUp(n int) {
26         v := h.GetView()
27         v.StartLine = h.Scroll(v.StartLine, -n)
28         h.SetView(v)
29 }
30
31 // ScrollDown is not an action
32 func (h *BufPane) ScrollDown(n int) {
33         v := h.GetView()
34         v.StartLine = h.Scroll(v.StartLine, n)
35         h.SetView(v)
36 }
37
38 // ScrollAdjust can be used to shift the view so that the last line is at the
39 // bottom if the user has scrolled past the last line.
40 func (h *BufPane) ScrollAdjust() {
41         v := h.GetView()
42         end := h.SLocFromLoc(h.Buf.End())
43         if h.Diff(v.StartLine, end) < h.BufView().Height-1 {
44                 v.StartLine = h.Scroll(end, -h.BufView().Height+1)
45         }
46         h.SetView(v)
47 }
48
49 // MousePress is the event that should happen when a normal click happens
50 // This is almost always bound to left click
51 func (h *BufPane) MousePress(e *tcell.EventMouse) bool {
52         b := h.Buf
53         mx, my := e.Position()
54         mouseLoc := h.LocFromVisual(buffer.Loc{mx, my})
55         h.Cursor.Loc = mouseLoc
56         if h.mouseReleased {
57                 if b.NumCursors() > 1 {
58                         b.ClearCursors()
59                         h.Relocate()
60                         h.Cursor = h.Buf.GetActiveCursor()
61                         h.Cursor.Loc = mouseLoc
62                 }
63                 if time.Since(h.lastClickTime)/time.Millisecond < config.DoubleClickThreshold && (mouseLoc.X == h.lastLoc.X && mouseLoc.Y == h.lastLoc.Y) {
64                         if h.doubleClick {
65                                 // Triple click
66                                 h.lastClickTime = time.Now()
67
68                                 h.tripleClick = true
69                                 h.doubleClick = false
70
71                                 h.Cursor.SelectLine()
72                                 h.Cursor.CopySelection(clipboard.PrimaryReg)
73                         } else {
74                                 // Double click
75                                 h.lastClickTime = time.Now()
76
77                                 h.doubleClick = true
78                                 h.tripleClick = false
79
80                                 h.Cursor.SelectWord()
81                                 h.Cursor.CopySelection(clipboard.PrimaryReg)
82                         }
83                 } else {
84                         h.doubleClick = false
85                         h.tripleClick = false
86                         h.lastClickTime = time.Now()
87
88                         h.Cursor.OrigSelection[0] = h.Cursor.Loc
89                         h.Cursor.CurSelection[0] = h.Cursor.Loc
90                         h.Cursor.CurSelection[1] = h.Cursor.Loc
91                 }
92                 h.mouseReleased = false
93         } else if !h.mouseReleased {
94                 if h.tripleClick {
95                         h.Cursor.AddLineToSelection()
96                 } else if h.doubleClick {
97                         h.Cursor.AddWordToSelection()
98                 } else {
99                         h.Cursor.SetSelectionEnd(h.Cursor.Loc)
100                 }
101         }
102
103         h.Cursor.StoreVisualX()
104         h.lastLoc = mouseLoc
105         h.Relocate()
106         return true
107 }
108
109 // ScrollUpAction scrolls the view up
110 func (h *BufPane) ScrollUpAction() bool {
111         h.ScrollUp(util.IntOpt(h.Buf.Settings["scrollspeed"]))
112         return true
113 }
114
115 // ScrollDownAction scrolls the view up
116 func (h *BufPane) ScrollDownAction() bool {
117         h.ScrollDown(util.IntOpt(h.Buf.Settings["scrollspeed"]))
118         return true
119 }
120
121 // Center centers the view on the cursor
122 func (h *BufPane) Center() bool {
123         v := h.GetView()
124         v.StartLine = h.Scroll(h.SLocFromLoc(h.Cursor.Loc), -h.BufView().Height/2)
125         h.SetView(v)
126         h.ScrollAdjust()
127         return true
128 }
129
130 // MoveCursorUp is not an action
131 func (h *BufPane) MoveCursorUp(n int) {
132         if !h.Buf.Settings["softwrap"].(bool) {
133                 h.Cursor.UpN(n)
134         } else {
135                 vloc := h.VLocFromLoc(h.Cursor.Loc)
136                 sloc := h.Scroll(vloc.SLoc, -n)
137                 if sloc == vloc.SLoc {
138                         // we are at the beginning of buffer
139                         h.Cursor.Loc = h.Buf.Start()
140                         h.Cursor.LastVisualX = 0
141                 } else {
142                         vloc.SLoc = sloc
143                         vloc.VisualX = h.Cursor.LastVisualX
144                         h.Cursor.Loc = h.LocFromVLoc(vloc)
145                 }
146         }
147 }
148
149 // MoveCursorDown is not an action
150 func (h *BufPane) MoveCursorDown(n int) {
151         if !h.Buf.Settings["softwrap"].(bool) {
152                 h.Cursor.DownN(n)
153         } else {
154                 vloc := h.VLocFromLoc(h.Cursor.Loc)
155                 sloc := h.Scroll(vloc.SLoc, n)
156                 if sloc == vloc.SLoc {
157                         // we are at the end of buffer
158                         h.Cursor.Loc = h.Buf.End()
159                         vloc = h.VLocFromLoc(h.Cursor.Loc)
160                         h.Cursor.LastVisualX = vloc.VisualX
161                 } else {
162                         vloc.SLoc = sloc
163                         vloc.VisualX = h.Cursor.LastVisualX
164                         h.Cursor.Loc = h.LocFromVLoc(vloc)
165                 }
166         }
167 }
168
169 // CursorUp moves the cursor up
170 func (h *BufPane) CursorUp() bool {
171         h.Cursor.Deselect(true)
172         h.MoveCursorUp(1)
173         h.Relocate()
174         return true
175 }
176
177 // CursorDown moves the cursor down
178 func (h *BufPane) CursorDown() bool {
179         h.Cursor.Deselect(true)
180         h.MoveCursorDown(1)
181         h.Relocate()
182         return true
183 }
184
185 // CursorLeft moves the cursor left
186 func (h *BufPane) CursorLeft() bool {
187         if h.Cursor.HasSelection() {
188                 h.Cursor.Deselect(true)
189         } else {
190                 tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
191                 tabmovement := h.Buf.Settings["tabmovement"].(bool)
192                 if tabstospaces && tabmovement {
193                         tabsize := int(h.Buf.Settings["tabsize"].(float64))
194                         line := h.Buf.LineBytes(h.Cursor.Y)
195                         if h.Cursor.X-tabsize >= 0 && util.IsSpaces(line[h.Cursor.X-tabsize:h.Cursor.X]) && util.IsBytesWhitespace(line[0:h.Cursor.X-tabsize]) {
196                                 for i := 0; i < tabsize; i++ {
197                                         h.Cursor.Left()
198                                 }
199                         } else {
200                                 h.Cursor.Left()
201                         }
202                 } else {
203                         h.Cursor.Left()
204                 }
205         }
206         h.Relocate()
207         return true
208 }
209
210 // CursorRight moves the cursor right
211 func (h *BufPane) CursorRight() bool {
212         if h.Cursor.HasSelection() {
213                 h.Cursor.Deselect(false)
214                 h.Cursor.Loc = h.Cursor.Loc.Move(1, h.Buf)
215         } else {
216                 tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
217                 tabmovement := h.Buf.Settings["tabmovement"].(bool)
218                 if tabstospaces && tabmovement {
219                         tabsize := int(h.Buf.Settings["tabsize"].(float64))
220                         line := h.Buf.LineBytes(h.Cursor.Y)
221                         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]) {
222                                 for i := 0; i < tabsize; i++ {
223                                         h.Cursor.Right()
224                                 }
225                         } else {
226                                 h.Cursor.Right()
227                         }
228                 } else {
229                         h.Cursor.Right()
230                 }
231         }
232
233         h.Relocate()
234         return true
235 }
236
237 // WordRight moves the cursor one word to the right
238 func (h *BufPane) WordRight() bool {
239         h.Cursor.Deselect(false)
240         h.Cursor.WordRight()
241         h.Relocate()
242         return true
243 }
244
245 // WordLeft moves the cursor one word to the left
246 func (h *BufPane) WordLeft() bool {
247         h.Cursor.Deselect(true)
248         h.Cursor.WordLeft()
249         h.Relocate()
250         return true
251 }
252
253 // SelectUp selects up one line
254 func (h *BufPane) SelectUp() bool {
255         if !h.Cursor.HasSelection() {
256                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
257         }
258         h.MoveCursorUp(1)
259         h.Cursor.SelectTo(h.Cursor.Loc)
260         h.Relocate()
261         return true
262 }
263
264 // SelectDown selects down one line
265 func (h *BufPane) SelectDown() bool {
266         if !h.Cursor.HasSelection() {
267                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
268         }
269         h.MoveCursorDown(1)
270         h.Cursor.SelectTo(h.Cursor.Loc)
271         h.Relocate()
272         return true
273 }
274
275 // SelectLeft selects the character to the left of the cursor
276 func (h *BufPane) SelectLeft() bool {
277         loc := h.Cursor.Loc
278         count := h.Buf.End()
279         if loc.GreaterThan(count) {
280                 loc = count
281         }
282         if !h.Cursor.HasSelection() {
283                 h.Cursor.OrigSelection[0] = loc
284         }
285         h.Cursor.Left()
286         h.Cursor.SelectTo(h.Cursor.Loc)
287         h.Relocate()
288         return true
289 }
290
291 // SelectRight selects the character to the right of the cursor
292 func (h *BufPane) SelectRight() bool {
293         loc := h.Cursor.Loc
294         count := h.Buf.End()
295         if loc.GreaterThan(count) {
296                 loc = count
297         }
298         if !h.Cursor.HasSelection() {
299                 h.Cursor.OrigSelection[0] = loc
300         }
301         h.Cursor.Right()
302         h.Cursor.SelectTo(h.Cursor.Loc)
303         h.Relocate()
304         return true
305 }
306
307 // SelectWordRight selects the word to the right of the cursor
308 func (h *BufPane) SelectWordRight() bool {
309         if !h.Cursor.HasSelection() {
310                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
311         }
312         h.Cursor.WordRight()
313         h.Cursor.SelectTo(h.Cursor.Loc)
314         h.Relocate()
315         return true
316 }
317
318 // SelectWordLeft selects the word to the left of the cursor
319 func (h *BufPane) SelectWordLeft() bool {
320         if !h.Cursor.HasSelection() {
321                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
322         }
323         h.Cursor.WordLeft()
324         h.Cursor.SelectTo(h.Cursor.Loc)
325         h.Relocate()
326         return true
327 }
328
329 // StartOfText moves the cursor to the start of the text of the line
330 func (h *BufPane) StartOfText() bool {
331         h.Cursor.Deselect(true)
332         h.Cursor.StartOfText()
333         h.Relocate()
334         return true
335 }
336
337 // StartOfTextToggle toggles the cursor between the start of the text of the line
338 // and the start of the line
339 func (h *BufPane) StartOfTextToggle() bool {
340         h.Cursor.Deselect(true)
341         if h.Cursor.IsStartOfText() {
342                 h.Cursor.Start()
343         } else {
344                 h.Cursor.StartOfText()
345         }
346         h.Relocate()
347         return true
348 }
349
350 // StartOfLine moves the cursor to the start of the line
351 func (h *BufPane) StartOfLine() bool {
352         h.Cursor.Deselect(true)
353         h.Cursor.Start()
354         h.Relocate()
355         return true
356 }
357
358 // EndOfLine moves the cursor to the end of the line
359 func (h *BufPane) EndOfLine() bool {
360         h.Cursor.Deselect(true)
361         h.Cursor.End()
362         h.Relocate()
363         return true
364 }
365
366 // SelectLine selects the entire current line
367 func (h *BufPane) SelectLine() bool {
368         h.Cursor.SelectLine()
369         h.Relocate()
370         return true
371 }
372
373 // SelectToStartOfText selects to the start of the text on the current line
374 func (h *BufPane) SelectToStartOfText() bool {
375         if !h.Cursor.HasSelection() {
376                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
377         }
378         h.Cursor.StartOfText()
379         h.Cursor.SelectTo(h.Cursor.Loc)
380         h.Relocate()
381         return true
382 }
383
384 // SelectToStartOfTextToggle toggles the selection between the start of the text
385 // on the current line and the start of the line
386 func (h *BufPane) SelectToStartOfTextToggle() bool {
387         if !h.Cursor.HasSelection() {
388                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
389         }
390         if h.Cursor.IsStartOfText() {
391                 h.Cursor.Start()
392         } else {
393                 h.Cursor.StartOfText()
394         }
395         h.Cursor.SelectTo(h.Cursor.Loc)
396         h.Relocate()
397         return true
398 }
399
400 // SelectToStartOfLine selects to the start of the current line
401 func (h *BufPane) SelectToStartOfLine() bool {
402         if !h.Cursor.HasSelection() {
403                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
404         }
405         h.Cursor.Start()
406         h.Cursor.SelectTo(h.Cursor.Loc)
407         h.Relocate()
408         return true
409 }
410
411 // SelectToEndOfLine selects to the end of the current line
412 func (h *BufPane) SelectToEndOfLine() bool {
413         if !h.Cursor.HasSelection() {
414                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
415         }
416         h.Cursor.End()
417         h.Cursor.SelectTo(h.Cursor.Loc)
418         h.Relocate()
419         return true
420 }
421
422 // ParagraphPrevious moves the cursor to the previous empty line, or beginning of the buffer if there's none
423 func (h *BufPane) ParagraphPrevious() bool {
424         var line int
425         for line = h.Cursor.Y; line > 0; line-- {
426                 if len(h.Buf.LineBytes(line)) == 0 && line != h.Cursor.Y {
427                         h.Cursor.X = 0
428                         h.Cursor.Y = line
429                         break
430                 }
431         }
432         // If no empty line found. move cursor to end of buffer
433         if line == 0 {
434                 h.Cursor.Loc = h.Buf.Start()
435         }
436         h.Relocate()
437         return true
438 }
439
440 // ParagraphNext moves the cursor to the next empty line, or end of the buffer if there's none
441 func (h *BufPane) ParagraphNext() bool {
442         var line int
443         for line = h.Cursor.Y; line < h.Buf.LinesNum(); line++ {
444                 if len(h.Buf.LineBytes(line)) == 0 && line != h.Cursor.Y {
445                         h.Cursor.X = 0
446                         h.Cursor.Y = line
447                         break
448                 }
449         }
450         // If no empty line found. move cursor to end of buffer
451         if line == h.Buf.LinesNum() {
452                 h.Cursor.Loc = h.Buf.End()
453         }
454         h.Relocate()
455         return true
456 }
457
458 // Retab changes all tabs to spaces or all spaces to tabs depending
459 // on the user's settings
460 func (h *BufPane) Retab() bool {
461         h.Buf.Retab()
462         h.Relocate()
463         return true
464 }
465
466 // CursorStart moves the cursor to the start of the buffer
467 func (h *BufPane) CursorStart() bool {
468         h.Cursor.Deselect(true)
469         h.Cursor.X = 0
470         h.Cursor.Y = 0
471         h.Cursor.StoreVisualX()
472         h.Relocate()
473         return true
474 }
475
476 // CursorEnd moves the cursor to the end of the buffer
477 func (h *BufPane) CursorEnd() bool {
478         h.Cursor.Deselect(true)
479         h.Cursor.Loc = h.Buf.End()
480         h.Cursor.StoreVisualX()
481         h.Relocate()
482         return true
483 }
484
485 // SelectToStart selects the text from the cursor to the start of the buffer
486 func (h *BufPane) SelectToStart() bool {
487         if !h.Cursor.HasSelection() {
488                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
489         }
490         h.CursorStart()
491         h.Cursor.SelectTo(h.Buf.Start())
492         h.Relocate()
493         return true
494 }
495
496 // SelectToEnd selects the text from the cursor to the end of the buffer
497 func (h *BufPane) SelectToEnd() bool {
498         if !h.Cursor.HasSelection() {
499                 h.Cursor.OrigSelection[0] = h.Cursor.Loc
500         }
501         h.CursorEnd()
502         h.Cursor.SelectTo(h.Buf.End())
503         h.Relocate()
504         return true
505 }
506
507 // InsertNewline inserts a newline plus possible some whitespace if autoindent is on
508 func (h *BufPane) InsertNewline() bool {
509         // Insert a newline
510         if h.Cursor.HasSelection() {
511                 h.Cursor.DeleteSelection()
512                 h.Cursor.ResetSelection()
513         }
514
515         ws := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))
516         cx := h.Cursor.X
517         h.Buf.Insert(h.Cursor.Loc, "\n")
518         // h.Cursor.Right()
519
520         if h.Buf.Settings["autoindent"].(bool) {
521                 if cx < len(ws) {
522                         ws = ws[0:cx]
523                 }
524                 h.Buf.Insert(h.Cursor.Loc, string(ws))
525                 // for i := 0; i < len(ws); i++ {
526                 //      h.Cursor.Right()
527                 // }
528
529                 // Remove the whitespaces if keepautoindent setting is off
530                 if util.IsSpacesOrTabs(h.Buf.LineBytes(h.Cursor.Y-1)) && !h.Buf.Settings["keepautoindent"].(bool) {
531                         line := h.Buf.LineBytes(h.Cursor.Y - 1)
532                         h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y - 1}, buffer.Loc{X: util.CharacterCount(line), Y: h.Cursor.Y - 1})
533                 }
534         }
535         h.Cursor.LastVisualX = h.Cursor.GetVisualX()
536         h.Relocate()
537         return true
538 }
539
540 // Backspace deletes the previous character
541 func (h *BufPane) Backspace() bool {
542         if h.Cursor.HasSelection() {
543                 h.Cursor.DeleteSelection()
544                 h.Cursor.ResetSelection()
545         } else if h.Cursor.Loc.GreaterThan(h.Buf.Start()) {
546                 // We have to do something a bit hacky here because we want to
547                 // delete the line by first moving left and then deleting backwards
548                 // but the undo redo would place the cursor in the wrong place
549                 // So instead we move left, save the position, move back, delete
550                 // and restore the position
551
552                 // If the user is using spaces instead of tabs and they are deleting
553                 // whitespace at the start of the line, we should delete as if it's a
554                 // tab (tabSize number of spaces)
555                 lineStart := util.SliceStart(h.Buf.LineBytes(h.Cursor.Y), h.Cursor.X)
556                 tabSize := int(h.Buf.Settings["tabsize"].(float64))
557                 if h.Buf.Settings["tabstospaces"].(bool) && util.IsSpaces(lineStart) && len(lineStart) != 0 && util.CharacterCount(lineStart)%tabSize == 0 {
558                         loc := h.Cursor.Loc
559                         h.Buf.Remove(loc.Move(-tabSize, h.Buf), loc)
560                 } else {
561                         loc := h.Cursor.Loc
562                         h.Buf.Remove(loc.Move(-1, h.Buf), loc)
563                 }
564         }
565         h.Cursor.LastVisualX = h.Cursor.GetVisualX()
566         h.Relocate()
567         return true
568 }
569
570 // DeleteWordRight deletes the word to the right of the cursor
571 func (h *BufPane) DeleteWordRight() bool {
572         h.SelectWordRight()
573         if h.Cursor.HasSelection() {
574                 h.Cursor.DeleteSelection()
575                 h.Cursor.ResetSelection()
576         }
577         h.Relocate()
578         return true
579 }
580
581 // DeleteWordLeft deletes the word to the left of the cursor
582 func (h *BufPane) DeleteWordLeft() bool {
583         h.SelectWordLeft()
584         if h.Cursor.HasSelection() {
585                 h.Cursor.DeleteSelection()
586                 h.Cursor.ResetSelection()
587         }
588         h.Relocate()
589         return true
590 }
591
592 // Delete deletes the next character
593 func (h *BufPane) Delete() bool {
594         if h.Cursor.HasSelection() {
595                 h.Cursor.DeleteSelection()
596                 h.Cursor.ResetSelection()
597         } else {
598                 loc := h.Cursor.Loc
599                 if loc.LessThan(h.Buf.End()) {
600                         h.Buf.Remove(loc, loc.Move(1, h.Buf))
601                 }
602         }
603         h.Relocate()
604         return true
605 }
606
607 // IndentSelection indents the current selection
608 func (h *BufPane) IndentSelection() bool {
609         if h.Cursor.HasSelection() {
610                 start := h.Cursor.CurSelection[0]
611                 end := h.Cursor.CurSelection[1]
612                 if end.Y < start.Y {
613                         start, end = end, start
614                         h.Cursor.SetSelectionStart(start)
615                         h.Cursor.SetSelectionEnd(end)
616                 }
617
618                 startY := start.Y
619                 endY := end.Move(-1, h.Buf).Y
620                 endX := end.Move(-1, h.Buf).X
621                 tabsize := int(h.Buf.Settings["tabsize"].(float64))
622                 indentsize := len(h.Buf.IndentString(tabsize))
623                 for y := startY; y <= endY; y++ {
624                         if len(h.Buf.LineBytes(y)) > 0 {
625                                 h.Buf.Insert(buffer.Loc{X: 0, Y: y}, h.Buf.IndentString(tabsize))
626                                 if y == startY && start.X > 0 {
627                                         h.Cursor.SetSelectionStart(start.Move(indentsize, h.Buf))
628                                 }
629                                 if y == endY {
630                                         h.Cursor.SetSelectionEnd(buffer.Loc{X: endX + indentsize + 1, Y: endY})
631                                 }
632                         }
633                 }
634                 h.Buf.RelocateCursors()
635
636                 h.Relocate()
637                 return true
638         }
639         return false
640 }
641
642 // IndentLine moves the current line forward one indentation
643 func (h *BufPane) IndentLine() bool {
644         if h.Cursor.HasSelection() {
645                 return false
646         }
647
648         tabsize := int(h.Buf.Settings["tabsize"].(float64))
649         indentstr := h.Buf.IndentString(tabsize)
650         h.Buf.Insert(buffer.Loc{X: 0, Y: h.Cursor.Y}, indentstr)
651         h.Buf.RelocateCursors()
652         h.Relocate()
653         return true
654 }
655
656 // OutdentLine moves the current line back one indentation
657 func (h *BufPane) OutdentLine() bool {
658         if h.Cursor.HasSelection() {
659                 return false
660         }
661
662         for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
663                 if len(util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))) == 0 {
664                         break
665                 }
666                 h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y}, buffer.Loc{X: 1, Y: h.Cursor.Y})
667         }
668         h.Buf.RelocateCursors()
669         h.Relocate()
670         return true
671 }
672
673 // OutdentSelection takes the current selection and moves it back one indent level
674 func (h *BufPane) OutdentSelection() bool {
675         if h.Cursor.HasSelection() {
676                 start := h.Cursor.CurSelection[0]
677                 end := h.Cursor.CurSelection[1]
678                 if end.Y < start.Y {
679                         start, end = end, start
680                         h.Cursor.SetSelectionStart(start)
681                         h.Cursor.SetSelectionEnd(end)
682                 }
683
684                 startY := start.Y
685                 endY := end.Move(-1, h.Buf).Y
686                 for y := startY; y <= endY; y++ {
687                         for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
688                                 if len(util.GetLeadingWhitespace(h.Buf.LineBytes(y))) == 0 {
689                                         break
690                                 }
691                                 h.Buf.Remove(buffer.Loc{X: 0, Y: y}, buffer.Loc{X: 1, Y: y})
692                         }
693                 }
694                 h.Buf.RelocateCursors()
695
696                 h.Relocate()
697                 return true
698         }
699         return false
700 }
701
702 // Autocomplete cycles the suggestions and performs autocompletion if there are suggestions
703 func (h *BufPane) Autocomplete() bool {
704         b := h.Buf
705
706         if h.Cursor.HasSelection() {
707                 return false
708         }
709
710         if h.Cursor.X == 0 {
711                 return false
712         }
713         r := h.Cursor.RuneUnder(h.Cursor.X)
714         prev := h.Cursor.RuneUnder(h.Cursor.X - 1)
715         if !util.IsAutocomplete(prev) || !util.IsNonAlphaNumeric(r) {
716                 // don't autocomplete if cursor is on alpha numeric character (middle of a word)
717                 return false
718         }
719
720         if b.HasSuggestions {
721                 b.CycleAutocomplete(true)
722                 return true
723         }
724         return b.Autocomplete(buffer.BufferComplete)
725 }
726
727 // CycleAutocompleteBack cycles back in the autocomplete suggestion list
728 func (h *BufPane) CycleAutocompleteBack() bool {
729         if h.Cursor.HasSelection() {
730                 return false
731         }
732
733         if h.Buf.HasSuggestions {
734                 h.Buf.CycleAutocomplete(false)
735                 return true
736         }
737         return false
738 }
739
740 // InsertTab inserts a tab or spaces
741 func (h *BufPane) InsertTab() bool {
742         b := h.Buf
743         indent := b.IndentString(util.IntOpt(b.Settings["tabsize"]))
744         tabBytes := len(indent)
745         bytesUntilIndent := tabBytes - (h.Cursor.GetVisualX() % tabBytes)
746         b.Insert(h.Cursor.Loc, indent[:bytesUntilIndent])
747         h.Relocate()
748         return true
749 }
750
751 // SaveAll saves all open buffers
752 func (h *BufPane) SaveAll() bool {
753         for _, b := range buffer.OpenBuffers {
754                 b.Save()
755         }
756         return true
757 }
758
759 // SaveCB performs a save and does a callback at the very end (after all prompts have been resolved)
760 func (h *BufPane) SaveCB(action string, callback func()) bool {
761         // If this is an empty buffer, ask for a filename
762         if h.Buf.Path == "" {
763                 h.SaveAsCB(action, callback)
764         } else {
765                 noPrompt := h.saveBufToFile(h.Buf.Path, action, callback)
766                 if noPrompt {
767                         return true
768                 }
769         }
770         return false
771 }
772
773 // Save the buffer to disk
774 func (h *BufPane) Save() bool {
775         return h.SaveCB("Save", nil)
776 }
777
778 // SaveAsCB performs a save as and does a callback at the very end (after all prompts have been resolved)
779 // The callback is only called if the save was successful
780 func (h *BufPane) SaveAsCB(action string, callback func()) bool {
781         InfoBar.Prompt("Filename: ", "", "Save", nil, func(resp string, canceled bool) {
782                 if !canceled {
783                         // the filename might or might not be quoted, so unquote first then join the strings.
784                         args, err := shellquote.Split(resp)
785                         if err != nil {
786                                 InfoBar.Error("Error parsing arguments: ", err)
787                                 return
788                         }
789                         if len(args) == 0 {
790                                 InfoBar.Error("No filename given")
791                                 return
792                         }
793                         filename := strings.Join(args, " ")
794                         noPrompt := h.saveBufToFile(filename, action, callback)
795                         if noPrompt {
796                                 h.completeAction(action)
797                         }
798                 }
799         })
800         return false
801 }
802
803 // SaveAs saves the buffer to disk with the given name
804 func (h *BufPane) SaveAs() bool {
805         return h.SaveAsCB("SaveAs", nil)
806 }
807
808 // This function saves the buffer to `filename` and changes the buffer's path and name
809 // to `filename` if the save is successful
810 // The callback is only called if the save was successful
811 func (h *BufPane) saveBufToFile(filename string, action string, callback func()) bool {
812         err := h.Buf.SaveAs(filename)
813         if err != nil {
814                 if errors.Is(err, fs.ErrPermission) {
815                         saveWithSudo := func() {
816                                 err = h.Buf.SaveAsWithSudo(filename)
817                                 if err != nil {
818                                         InfoBar.Error(err)
819                                 } else {
820                                         h.Buf.Path = filename
821                                         h.Buf.SetName(filename)
822                                         InfoBar.Message("Saved " + filename)
823                                         if callback != nil {
824                                                 callback()
825                                         }
826                                 }
827                         }
828                         if h.Buf.Settings["autosu"].(bool) {
829                                 saveWithSudo()
830                         } else {
831                                 InfoBar.YNPrompt(
832                                         fmt.Sprintf("Permission denied. Do you want to save this file using %s? (y,n)", config.GlobalSettings["sucmd"].(string)),
833                                         func(yes, canceled bool) {
834                                                 if yes && !canceled {
835                                                         saveWithSudo()
836                                                         h.completeAction(action)
837                                                 }
838                                         },
839                                 )
840                                 return false
841                         }
842                 } else {
843                         InfoBar.Error(err)
844                 }
845         } else {
846                 h.Buf.Path = filename
847                 h.Buf.SetName(filename)
848                 InfoBar.Message("Saved " + filename)
849                 if callback != nil {
850                         callback()
851                 }
852         }
853         return true
854 }
855
856 // Find opens a prompt and searches forward for the input
857 func (h *BufPane) Find() bool {
858         return h.find(true)
859 }
860
861 // FindLiteral is the same as Find() but does not support regular expressions
862 func (h *BufPane) FindLiteral() bool {
863         return h.find(false)
864 }
865
866 // Search searches for a given string/regex in the buffer and selects the next
867 // match if a match is found
868 // This function behaves the same way as Find and FindLiteral actions:
869 // it affects the buffer's LastSearch and LastSearchRegex (saved searches)
870 // for use with FindNext and FindPrevious, and turns HighlightSearch on or off
871 // according to hlsearch setting
872 func (h *BufPane) Search(str string, useRegex bool, searchDown bool) error {
873         match, found, err := h.Buf.FindNext(str, h.Buf.Start(), h.Buf.End(), h.Cursor.Loc, searchDown, useRegex)
874         if err != nil {
875                 return err
876         }
877         if found {
878                 h.Cursor.SetSelectionStart(match[0])
879                 h.Cursor.SetSelectionEnd(match[1])
880                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
881                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
882                 h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
883                 h.Buf.LastSearch = str
884                 h.Buf.LastSearchRegex = useRegex
885                 h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
886                 h.Relocate()
887         } else {
888                 h.Cursor.ResetSelection()
889         }
890         return nil
891 }
892
893 func (h *BufPane) find(useRegex bool) bool {
894         h.searchOrig = h.Cursor.Loc
895         prompt := "Find: "
896         if useRegex {
897                 prompt = "Find (regex): "
898         }
899         var eventCallback func(resp string)
900         if h.Buf.Settings["incsearch"].(bool) {
901                 eventCallback = func(resp string) {
902                         match, found, _ := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
903                         if found {
904                                 h.Cursor.SetSelectionStart(match[0])
905                                 h.Cursor.SetSelectionEnd(match[1])
906                                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
907                                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
908                                 h.Cursor.GotoLoc(match[1])
909                         } else {
910                                 h.Cursor.GotoLoc(h.searchOrig)
911                                 h.Cursor.ResetSelection()
912                         }
913                         h.Relocate()
914                 }
915         }
916         findCallback := func(resp string, canceled bool) {
917                 // Finished callback
918                 if !canceled {
919                         match, found, err := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
920                         if err != nil {
921                                 InfoBar.Error(err)
922                         }
923                         if found {
924                                 h.Cursor.SetSelectionStart(match[0])
925                                 h.Cursor.SetSelectionEnd(match[1])
926                                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
927                                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
928                                 h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
929                                 h.Buf.LastSearch = resp
930                                 h.Buf.LastSearchRegex = useRegex
931                                 h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
932                         } else {
933                                 h.Cursor.ResetSelection()
934                                 InfoBar.Message("No matches found")
935                         }
936                 } else {
937                         h.Cursor.ResetSelection()
938                 }
939                 h.Relocate()
940         }
941         pattern := string(h.Cursor.GetSelection())
942         if eventCallback != nil && pattern != "" {
943                 eventCallback(pattern)
944         }
945         InfoBar.Prompt(prompt, pattern, "Find", eventCallback, findCallback)
946         if pattern != "" {
947                 InfoBar.SelectAll()
948         }
949         return true
950 }
951
952 // ToggleHighlightSearch toggles highlighting all instances of the last used search term
953 func (h *BufPane) ToggleHighlightSearch() bool {
954         h.Buf.HighlightSearch = !h.Buf.HighlightSearch
955         return true
956 }
957
958 // UnhighlightSearch unhighlights all instances of the last used search term
959 func (h *BufPane) UnhighlightSearch() bool {
960         h.Buf.HighlightSearch = false
961         return true
962 }
963
964 // FindNext searches forwards for the last used search term
965 func (h *BufPane) FindNext() bool {
966         // If the cursor is at the start of a selection and we search we want
967         // to search from the end of the selection in the case that
968         // the selection is a search result in which case we wouldn't move at
969         // at all which would be bad
970         searchLoc := h.Cursor.Loc
971         if h.Cursor.HasSelection() {
972                 searchLoc = h.Cursor.CurSelection[1]
973         }
974         match, found, err := h.Buf.FindNext(h.Buf.LastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, true, h.Buf.LastSearchRegex)
975         if err != nil {
976                 InfoBar.Error(err)
977         }
978         if found {
979                 h.Cursor.SetSelectionStart(match[0])
980                 h.Cursor.SetSelectionEnd(match[1])
981                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
982                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
983                 h.Cursor.Loc = h.Cursor.CurSelection[1]
984         } else {
985                 h.Cursor.ResetSelection()
986         }
987         h.Relocate()
988         return true
989 }
990
991 // FindPrevious searches backwards for the last used search term
992 func (h *BufPane) FindPrevious() bool {
993         // If the cursor is at the end of a selection and we search we want
994         // to search from the beginning of the selection in the case that
995         // the selection is a search result in which case we wouldn't move at
996         // at all which would be bad
997         searchLoc := h.Cursor.Loc
998         if h.Cursor.HasSelection() {
999                 searchLoc = h.Cursor.CurSelection[0]
1000         }
1001         match, found, err := h.Buf.FindNext(h.Buf.LastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, false, h.Buf.LastSearchRegex)
1002         if err != nil {
1003                 InfoBar.Error(err)
1004         }
1005         if found {
1006                 h.Cursor.SetSelectionStart(match[0])
1007                 h.Cursor.SetSelectionEnd(match[1])
1008                 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
1009                 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
1010                 h.Cursor.Loc = h.Cursor.CurSelection[1]
1011         } else {
1012                 h.Cursor.ResetSelection()
1013         }
1014         h.Relocate()
1015         return true
1016 }
1017
1018 // Undo undoes the last action
1019 func (h *BufPane) Undo() bool {
1020         h.Buf.Undo()
1021         InfoBar.Message("Undid action")
1022         h.Relocate()
1023         return true
1024 }
1025
1026 // Redo redoes the last action
1027 func (h *BufPane) Redo() bool {
1028         h.Buf.Redo()
1029         InfoBar.Message("Redid action")
1030         h.Relocate()
1031         return true
1032 }
1033
1034 // Copy the selection to the system clipboard
1035 func (h *BufPane) Copy() bool {
1036         if h.Cursor.HasSelection() {
1037                 h.Cursor.CopySelection(clipboard.ClipboardReg)
1038                 h.freshClip = true
1039                 InfoBar.Message("Copied selection")
1040         }
1041         h.Relocate()
1042         return true
1043 }
1044
1045 // CopyLine copies the current line to the clipboard
1046 func (h *BufPane) CopyLine() bool {
1047         if h.Cursor.HasSelection() {
1048                 return false
1049         }
1050         origLoc := h.Cursor.Loc
1051         h.Cursor.SelectLine()
1052         h.Cursor.CopySelection(clipboard.ClipboardReg)
1053         h.freshClip = true
1054         InfoBar.Message("Copied line")
1055
1056         h.Cursor.Deselect(true)
1057         h.Cursor.Loc = origLoc
1058         h.Relocate()
1059         return true
1060 }
1061
1062 // CutLine cuts the current line to the clipboard
1063 func (h *BufPane) CutLine() bool {
1064         h.Cursor.SelectLine()
1065         if !h.Cursor.HasSelection() {
1066                 return false
1067         }
1068         if h.freshClip {
1069                 if h.Cursor.HasSelection() {
1070                         if clip, err := clipboard.Read(clipboard.ClipboardReg); err != nil {
1071                                 InfoBar.Error(err)
1072                         } else {
1073                                 clipboard.WriteMulti(clip+string(h.Cursor.GetSelection()), clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
1074                         }
1075                 }
1076         } else if time.Since(h.lastCutTime)/time.Second > 10*time.Second || !h.freshClip {
1077                 h.Copy()
1078         }
1079         h.freshClip = true
1080         h.lastCutTime = time.Now()
1081         h.Cursor.DeleteSelection()
1082         h.Cursor.ResetSelection()
1083         InfoBar.Message("Cut line")
1084         h.Relocate()
1085         return true
1086 }
1087
1088 // Cut the selection to the system clipboard
1089 func (h *BufPane) Cut() bool {
1090         if h.Cursor.HasSelection() {
1091                 h.Cursor.CopySelection(clipboard.ClipboardReg)
1092                 h.Cursor.DeleteSelection()
1093                 h.Cursor.ResetSelection()
1094                 h.freshClip = true
1095                 InfoBar.Message("Cut selection")
1096
1097                 h.Relocate()
1098                 return true
1099         }
1100         return h.CutLine()
1101 }
1102
1103 // DuplicateLine duplicates the current line or selection
1104 func (h *BufPane) DuplicateLine() bool {
1105         var infoMessage = "Duplicated line"
1106         if h.Cursor.HasSelection() {
1107                 infoMessage = "Duplicated selection"
1108                 h.Buf.Insert(h.Cursor.CurSelection[1], string(h.Cursor.GetSelection()))
1109         } else {
1110                 h.Cursor.End()
1111                 h.Buf.Insert(h.Cursor.Loc, "\n"+string(h.Buf.LineBytes(h.Cursor.Y)))
1112                 // h.Cursor.Right()
1113         }
1114
1115         InfoBar.Message(infoMessage)
1116         h.Relocate()
1117         return true
1118 }
1119
1120 // DeleteLine deletes the current line
1121 func (h *BufPane) DeleteLine() bool {
1122         h.Cursor.SelectLine()
1123         if !h.Cursor.HasSelection() {
1124                 return false
1125         }
1126         h.Cursor.DeleteSelection()
1127         h.Cursor.ResetSelection()
1128         InfoBar.Message("Deleted line")
1129         h.Relocate()
1130         return true
1131 }
1132
1133 // MoveLinesUp moves up the current line or selected lines if any
1134 func (h *BufPane) MoveLinesUp() bool {
1135         if h.Cursor.HasSelection() {
1136                 if h.Cursor.CurSelection[0].Y == 0 {
1137                         InfoBar.Message("Cannot move further up")
1138                         return false
1139                 }
1140                 start := h.Cursor.CurSelection[0].Y
1141                 end := h.Cursor.CurSelection[1].Y
1142                 sel := 1
1143                 if start > end {
1144                         end, start = start, end
1145                         sel = 0
1146                 }
1147
1148                 compensate := false
1149                 if h.Cursor.CurSelection[sel].X != 0 {
1150                         end++
1151                 } else {
1152                         compensate = true
1153                 }
1154
1155                 h.Buf.MoveLinesUp(
1156                         start,
1157                         end,
1158                 )
1159                 if compensate {
1160                         h.Cursor.CurSelection[sel].Y -= 1
1161                 }
1162         } else {
1163                 if h.Cursor.Loc.Y == 0 {
1164                         InfoBar.Message("Cannot move further up")
1165                         return false
1166                 }
1167                 h.Buf.MoveLinesUp(
1168                         h.Cursor.Loc.Y,
1169                         h.Cursor.Loc.Y+1,
1170                 )
1171         }
1172
1173         h.Relocate()
1174         return true
1175 }
1176
1177 // MoveLinesDown moves down the current line or selected lines if any
1178 func (h *BufPane) MoveLinesDown() bool {
1179         if h.Cursor.HasSelection() {
1180                 if h.Cursor.CurSelection[1].Y >= h.Buf.LinesNum() {
1181                         InfoBar.Message("Cannot move further down")
1182                         return false
1183                 }
1184                 start := h.Cursor.CurSelection[0].Y
1185                 end := h.Cursor.CurSelection[1].Y
1186                 sel := 1
1187                 if start > end {
1188                         end, start = start, end
1189                         sel = 0
1190                 }
1191
1192                 if h.Cursor.CurSelection[sel].X != 0 {
1193                         end++
1194                 }
1195
1196                 h.Buf.MoveLinesDown(
1197                         start,
1198                         end,
1199                 )
1200         } else {
1201                 if h.Cursor.Loc.Y >= h.Buf.LinesNum()-1 {
1202                         InfoBar.Message("Cannot move further down")
1203                         return false
1204                 }
1205                 h.Buf.MoveLinesDown(
1206                         h.Cursor.Loc.Y,
1207                         h.Cursor.Loc.Y+1,
1208                 )
1209         }
1210
1211         h.Relocate()
1212         return true
1213 }
1214
1215 // Paste whatever is in the system clipboard into the buffer
1216 // Delete and paste if the user has a selection
1217 func (h *BufPane) Paste() bool {
1218         clip, err := clipboard.ReadMulti(clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
1219         if err != nil {
1220                 InfoBar.Error(err)
1221         } else {
1222                 h.paste(clip)
1223         }
1224         h.Relocate()
1225         return true
1226 }
1227
1228 // PastePrimary pastes from the primary clipboard (only use on linux)
1229 func (h *BufPane) PastePrimary() bool {
1230         clip, err := clipboard.ReadMulti(clipboard.PrimaryReg, h.Cursor.Num, h.Buf.NumCursors())
1231         if err != nil {
1232                 InfoBar.Error(err)
1233         } else {
1234                 h.paste(clip)
1235         }
1236         h.Relocate()
1237         return true
1238 }
1239
1240 func (h *BufPane) paste(clip string) {
1241         if h.Buf.Settings["smartpaste"].(bool) {
1242                 if h.Cursor.X > 0 && len(util.GetLeadingWhitespace([]byte(strings.TrimLeft(clip, "\r\n")))) == 0 {
1243                         leadingWS := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))
1244                         clip = strings.ReplaceAll(clip, "\n", "\n"+string(leadingWS))
1245                 }
1246         }
1247
1248         if h.Cursor.HasSelection() {
1249                 h.Cursor.DeleteSelection()
1250                 h.Cursor.ResetSelection()
1251         }
1252
1253         h.Buf.Insert(h.Cursor.Loc, clip)
1254         // h.Cursor.Loc = h.Cursor.Loc.Move(Count(clip), h.Buf)
1255         h.freshClip = false
1256         InfoBar.Message("Pasted clipboard")
1257 }
1258
1259 // JumpToMatchingBrace moves the cursor to the matching brace if it is
1260 // currently on a brace
1261 func (h *BufPane) JumpToMatchingBrace() bool {
1262         for _, bp := range buffer.BracePairs {
1263                 r := h.Cursor.RuneUnder(h.Cursor.X)
1264                 rl := h.Cursor.RuneUnder(h.Cursor.X - 1)
1265                 if r == bp[0] || r == bp[1] || rl == bp[0] || rl == bp[1] {
1266                         matchingBrace, left, found := h.Buf.FindMatchingBrace(bp, h.Cursor.Loc)
1267                         if found {
1268                                 if left {
1269                                         h.Cursor.GotoLoc(matchingBrace)
1270                                 } else {
1271                                         h.Cursor.GotoLoc(matchingBrace.Move(1, h.Buf))
1272                                 }
1273                                 h.Relocate()
1274                                 return true
1275                         }
1276                 }
1277         }
1278         return false
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 }