9 shellquote "github.com/kballard/go-shellquote"
10 "github.com/zyedidia/micro/v2/internal/buffer"
11 "github.com/zyedidia/micro/v2/internal/clipboard"
12 "github.com/zyedidia/micro/v2/internal/config"
13 "github.com/zyedidia/micro/v2/internal/screen"
14 "github.com/zyedidia/micro/v2/internal/shell"
15 "github.com/zyedidia/micro/v2/internal/util"
16 "github.com/zyedidia/tcell/v2"
19 // ScrollUp is not an action
20 func (h *BufPane) ScrollUp(n int) {
30 // ScrollDown is not an action
31 func (h *BufPane) ScrollDown(n int) {
33 if v.StartLine <= h.Buf.LinesNum()-1-n {
39 // MousePress is the event that should happen when a normal click happens
40 // This is almost always bound to left click
41 func (h *BufPane) MousePress(e *tcell.EventMouse) bool {
43 mx, my := e.Position()
44 mouseLoc := h.LocFromVisual(buffer.Loc{mx, my})
45 h.Cursor.Loc = mouseLoc
47 if b.NumCursors() > 1 {
50 h.Cursor = h.Buf.GetActiveCursor()
51 h.Cursor.Loc = mouseLoc
53 if time.Since(h.lastClickTime)/time.Millisecond < config.DoubleClickThreshold && (mouseLoc.X == h.lastLoc.X && mouseLoc.Y == h.lastLoc.Y) {
56 h.lastClickTime = time.Now()
62 h.Cursor.CopySelection(clipboard.PrimaryReg)
65 h.lastClickTime = time.Now()
71 h.Cursor.CopySelection(clipboard.PrimaryReg)
76 h.lastClickTime = time.Now()
78 h.Cursor.OrigSelection[0] = h.Cursor.Loc
79 h.Cursor.CurSelection[0] = h.Cursor.Loc
80 h.Cursor.CurSelection[1] = h.Cursor.Loc
82 h.mouseReleased = false
83 } else if !h.mouseReleased {
85 h.Cursor.AddLineToSelection()
86 } else if h.doubleClick {
87 h.Cursor.AddWordToSelection()
89 h.Cursor.SetSelectionEnd(h.Cursor.Loc)
93 h.Cursor.StoreVisualX()
99 // ScrollUpAction scrolls the view up
100 func (h *BufPane) ScrollUpAction() bool {
101 h.ScrollUp(util.IntOpt(h.Buf.Settings["scrollspeed"]))
105 // ScrollDownAction scrolls the view up
106 func (h *BufPane) ScrollDownAction() bool {
107 h.ScrollDown(util.IntOpt(h.Buf.Settings["scrollspeed"]))
111 // Center centers the view on the cursor
112 func (h *BufPane) Center() bool {
114 v.StartLine = h.Cursor.Y - v.Height/2
115 if v.StartLine+v.Height > h.Buf.LinesNum() {
116 v.StartLine = h.Buf.LinesNum() - v.Height
126 // CursorUp moves the cursor up
127 func (h *BufPane) CursorUp() bool {
128 h.Cursor.Deselect(true)
134 // CursorDown moves the cursor down
135 func (h *BufPane) CursorDown() bool {
136 h.Cursor.Deselect(true)
142 // CursorLeft moves the cursor left
143 func (h *BufPane) CursorLeft() bool {
144 if h.Cursor.HasSelection() {
145 h.Cursor.Deselect(true)
147 tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
148 tabmovement := h.Buf.Settings["tabmovement"].(bool)
149 if tabstospaces && tabmovement {
150 tabsize := int(h.Buf.Settings["tabsize"].(float64))
151 line := h.Buf.LineBytes(h.Cursor.Y)
152 if h.Cursor.X-tabsize >= 0 && util.IsSpaces(line[h.Cursor.X-tabsize:h.Cursor.X]) && util.IsBytesWhitespace(line[0:h.Cursor.X-tabsize]) {
153 for i := 0; i < tabsize; i++ {
167 // CursorRight moves the cursor right
168 func (h *BufPane) CursorRight() bool {
169 if h.Cursor.HasSelection() {
170 h.Cursor.Deselect(false)
171 h.Cursor.Loc = h.Cursor.Loc.Move(1, h.Buf)
173 tabstospaces := h.Buf.Settings["tabstospaces"].(bool)
174 tabmovement := h.Buf.Settings["tabmovement"].(bool)
175 if tabstospaces && tabmovement {
176 tabsize := int(h.Buf.Settings["tabsize"].(float64))
177 line := h.Buf.LineBytes(h.Cursor.Y)
178 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]) {
179 for i := 0; i < tabsize; i++ {
194 // WordRight moves the cursor one word to the right
195 func (h *BufPane) WordRight() bool {
196 h.Cursor.Deselect(false)
202 // WordLeft moves the cursor one word to the left
203 func (h *BufPane) WordLeft() bool {
204 h.Cursor.Deselect(true)
210 // SelectUp selects up one line
211 func (h *BufPane) SelectUp() bool {
212 if !h.Cursor.HasSelection() {
213 h.Cursor.OrigSelection[0] = h.Cursor.Loc
216 h.Cursor.SelectTo(h.Cursor.Loc)
221 // SelectDown selects down one line
222 func (h *BufPane) SelectDown() bool {
223 if !h.Cursor.HasSelection() {
224 h.Cursor.OrigSelection[0] = h.Cursor.Loc
227 h.Cursor.SelectTo(h.Cursor.Loc)
232 // SelectLeft selects the character to the left of the cursor
233 func (h *BufPane) SelectLeft() bool {
236 if loc.GreaterThan(count) {
239 if !h.Cursor.HasSelection() {
240 h.Cursor.OrigSelection[0] = loc
243 h.Cursor.SelectTo(h.Cursor.Loc)
248 // SelectRight selects the character to the right of the cursor
249 func (h *BufPane) SelectRight() bool {
252 if loc.GreaterThan(count) {
255 if !h.Cursor.HasSelection() {
256 h.Cursor.OrigSelection[0] = loc
259 h.Cursor.SelectTo(h.Cursor.Loc)
264 // SelectWordRight selects the word to the right of the cursor
265 func (h *BufPane) SelectWordRight() bool {
266 if !h.Cursor.HasSelection() {
267 h.Cursor.OrigSelection[0] = h.Cursor.Loc
270 h.Cursor.SelectTo(h.Cursor.Loc)
275 // SelectWordLeft selects the word to the left of the cursor
276 func (h *BufPane) SelectWordLeft() bool {
277 if !h.Cursor.HasSelection() {
278 h.Cursor.OrigSelection[0] = h.Cursor.Loc
281 h.Cursor.SelectTo(h.Cursor.Loc)
286 // StartOfText moves the cursor to the start of the text of the line
287 func (h *BufPane) StartOfText() bool {
288 h.Cursor.Deselect(true)
289 h.Cursor.StartOfText()
294 // StartOfTextToggle toggles the cursor between the start of the text of the line
295 // and the start of the line
296 func (h *BufPane) StartOfTextToggle() bool {
297 h.Cursor.Deselect(true)
298 if h.Cursor.IsStartOfText() {
301 h.Cursor.StartOfText()
307 // StartOfLine moves the cursor to the start of the line
308 func (h *BufPane) StartOfLine() bool {
309 h.Cursor.Deselect(true)
315 // EndOfLine moves the cursor to the end of the line
316 func (h *BufPane) EndOfLine() bool {
317 h.Cursor.Deselect(true)
323 // SelectLine selects the entire current line
324 func (h *BufPane) SelectLine() bool {
325 h.Cursor.SelectLine()
330 // SelectToStartOfText selects to the start of the text on the current line
331 func (h *BufPane) SelectToStartOfText() bool {
332 if !h.Cursor.HasSelection() {
333 h.Cursor.OrigSelection[0] = h.Cursor.Loc
335 h.Cursor.StartOfText()
336 h.Cursor.SelectTo(h.Cursor.Loc)
341 // SelectToStartOfTextToggle toggles the selection between the start of the text
342 // on the current line and the start of the line
343 func (h *BufPane) SelectToStartOfTextToggle() bool {
344 if !h.Cursor.HasSelection() {
345 h.Cursor.OrigSelection[0] = h.Cursor.Loc
347 if h.Cursor.IsStartOfText() {
350 h.Cursor.StartOfText()
352 h.Cursor.SelectTo(h.Cursor.Loc)
357 // SelectToStartOfLine selects to the start of the current line
358 func (h *BufPane) SelectToStartOfLine() bool {
359 if !h.Cursor.HasSelection() {
360 h.Cursor.OrigSelection[0] = h.Cursor.Loc
363 h.Cursor.SelectTo(h.Cursor.Loc)
368 // SelectToEndOfLine selects to the end of the current line
369 func (h *BufPane) SelectToEndOfLine() bool {
370 if !h.Cursor.HasSelection() {
371 h.Cursor.OrigSelection[0] = h.Cursor.Loc
374 h.Cursor.SelectTo(h.Cursor.Loc)
379 // ParagraphPrevious moves the cursor to the previous empty line, or beginning of the buffer if there's none
380 func (h *BufPane) ParagraphPrevious() bool {
382 for line = h.Cursor.Y; line > 0; line-- {
383 if len(h.Buf.LineBytes(line)) == 0 && line != h.Cursor.Y {
389 // If no empty line found. move cursor to end of buffer
391 h.Cursor.Loc = h.Buf.Start()
397 // ParagraphNext moves the cursor to the next empty line, or end of the buffer if there's none
398 func (h *BufPane) ParagraphNext() bool {
400 for line = h.Cursor.Y; line < h.Buf.LinesNum(); line++ {
401 if len(h.Buf.LineBytes(line)) == 0 && line != h.Cursor.Y {
407 // If no empty line found. move cursor to end of buffer
408 if line == h.Buf.LinesNum() {
409 h.Cursor.Loc = h.Buf.End()
415 // Retab changes all tabs to spaces or all spaces to tabs depending
416 // on the user's settings
417 func (h *BufPane) Retab() bool {
423 // CursorStart moves the cursor to the start of the buffer
424 func (h *BufPane) CursorStart() bool {
425 h.Cursor.Deselect(true)
428 h.Cursor.StoreVisualX()
433 // CursorEnd moves the cursor to the end of the buffer
434 func (h *BufPane) CursorEnd() bool {
435 h.Cursor.Deselect(true)
436 h.Cursor.Loc = h.Buf.End()
437 h.Cursor.StoreVisualX()
442 // SelectToStart selects the text from the cursor to the start of the buffer
443 func (h *BufPane) SelectToStart() bool {
444 if !h.Cursor.HasSelection() {
445 h.Cursor.OrigSelection[0] = h.Cursor.Loc
448 h.Cursor.SelectTo(h.Buf.Start())
453 // SelectToEnd selects the text from the cursor to the end of the buffer
454 func (h *BufPane) SelectToEnd() bool {
455 if !h.Cursor.HasSelection() {
456 h.Cursor.OrigSelection[0] = h.Cursor.Loc
459 h.Cursor.SelectTo(h.Buf.End())
464 // InsertNewline inserts a newline plus possible some whitespace if autoindent is on
465 func (h *BufPane) InsertNewline() bool {
467 if h.Cursor.HasSelection() {
468 h.Cursor.DeleteSelection()
469 h.Cursor.ResetSelection()
472 ws := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))
474 h.Buf.Insert(h.Cursor.Loc, "\n")
477 if h.Buf.Settings["autoindent"].(bool) {
481 h.Buf.Insert(h.Cursor.Loc, string(ws))
482 // for i := 0; i < len(ws); i++ {
486 // Remove the whitespaces if keepautoindent setting is off
487 if util.IsSpacesOrTabs(h.Buf.LineBytes(h.Cursor.Y-1)) && !h.Buf.Settings["keepautoindent"].(bool) {
488 line := h.Buf.LineBytes(h.Cursor.Y - 1)
489 h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y - 1}, buffer.Loc{X: util.CharacterCount(line), Y: h.Cursor.Y - 1})
492 h.Cursor.LastVisualX = h.Cursor.GetVisualX()
497 // Backspace deletes the previous character
498 func (h *BufPane) Backspace() bool {
499 if h.Cursor.HasSelection() {
500 h.Cursor.DeleteSelection()
501 h.Cursor.ResetSelection()
502 } else if h.Cursor.Loc.GreaterThan(h.Buf.Start()) {
503 // We have to do something a bit hacky here because we want to
504 // delete the line by first moving left and then deleting backwards
505 // but the undo redo would place the cursor in the wrong place
506 // So instead we move left, save the position, move back, delete
507 // and restore the position
509 // If the user is using spaces instead of tabs and they are deleting
510 // whitespace at the start of the line, we should delete as if it's a
511 // tab (tabSize number of spaces)
512 lineStart := util.SliceStart(h.Buf.LineBytes(h.Cursor.Y), h.Cursor.X)
513 tabSize := int(h.Buf.Settings["tabsize"].(float64))
514 if h.Buf.Settings["tabstospaces"].(bool) && util.IsSpaces(lineStart) && len(lineStart) != 0 && util.CharacterCount(lineStart)%tabSize == 0 {
516 h.Buf.Remove(loc.Move(-tabSize, h.Buf), loc)
519 h.Buf.Remove(loc.Move(-1, h.Buf), loc)
522 h.Cursor.LastVisualX = h.Cursor.GetVisualX()
527 // DeleteWordRight deletes the word to the right of the cursor
528 func (h *BufPane) DeleteWordRight() bool {
530 if h.Cursor.HasSelection() {
531 h.Cursor.DeleteSelection()
532 h.Cursor.ResetSelection()
538 // DeleteWordLeft deletes the word to the left of the cursor
539 func (h *BufPane) DeleteWordLeft() bool {
541 if h.Cursor.HasSelection() {
542 h.Cursor.DeleteSelection()
543 h.Cursor.ResetSelection()
549 // Delete deletes the next character
550 func (h *BufPane) Delete() bool {
551 if h.Cursor.HasSelection() {
552 h.Cursor.DeleteSelection()
553 h.Cursor.ResetSelection()
556 if loc.LessThan(h.Buf.End()) {
557 h.Buf.Remove(loc, loc.Move(1, h.Buf))
564 // IndentSelection indents the current selection
565 func (h *BufPane) IndentSelection() bool {
566 if h.Cursor.HasSelection() {
567 start := h.Cursor.CurSelection[0]
568 end := h.Cursor.CurSelection[1]
570 start, end = end, start
571 h.Cursor.SetSelectionStart(start)
572 h.Cursor.SetSelectionEnd(end)
576 endY := end.Move(-1, h.Buf).Y
577 endX := end.Move(-1, h.Buf).X
578 tabsize := int(h.Buf.Settings["tabsize"].(float64))
579 indentsize := len(h.Buf.IndentString(tabsize))
580 for y := startY; y <= endY; y++ {
581 if len(h.Buf.LineBytes(y)) > 0 {
582 h.Buf.Insert(buffer.Loc{X: 0, Y: y}, h.Buf.IndentString(tabsize))
583 if y == startY && start.X > 0 {
584 h.Cursor.SetSelectionStart(start.Move(indentsize, h.Buf))
587 h.Cursor.SetSelectionEnd(buffer.Loc{X: endX + indentsize + 1, Y: endY})
591 h.Buf.RelocateCursors()
599 // IndentLine moves the current line forward one indentation
600 func (h *BufPane) IndentLine() bool {
601 if h.Cursor.HasSelection() {
605 tabsize := int(h.Buf.Settings["tabsize"].(float64))
606 indentstr := h.Buf.IndentString(tabsize)
607 h.Buf.Insert(buffer.Loc{X: 0, Y: h.Cursor.Y}, indentstr)
608 h.Buf.RelocateCursors()
613 // OutdentLine moves the current line back one indentation
614 func (h *BufPane) OutdentLine() bool {
615 if h.Cursor.HasSelection() {
619 for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
620 if len(util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))) == 0 {
623 h.Buf.Remove(buffer.Loc{X: 0, Y: h.Cursor.Y}, buffer.Loc{X: 1, Y: h.Cursor.Y})
625 h.Buf.RelocateCursors()
630 // OutdentSelection takes the current selection and moves it back one indent level
631 func (h *BufPane) OutdentSelection() bool {
632 if h.Cursor.HasSelection() {
633 start := h.Cursor.CurSelection[0]
634 end := h.Cursor.CurSelection[1]
636 start, end = end, start
637 h.Cursor.SetSelectionStart(start)
638 h.Cursor.SetSelectionEnd(end)
642 endY := end.Move(-1, h.Buf).Y
643 for y := startY; y <= endY; y++ {
644 for x := 0; x < len(h.Buf.IndentString(util.IntOpt(h.Buf.Settings["tabsize"]))); x++ {
645 if len(util.GetLeadingWhitespace(h.Buf.LineBytes(y))) == 0 {
648 h.Buf.Remove(buffer.Loc{X: 0, Y: y}, buffer.Loc{X: 1, Y: y})
651 h.Buf.RelocateCursors()
659 // Autocomplete cycles the suggestions and performs autocompletion if there are suggestions
660 func (h *BufPane) Autocomplete() bool {
663 if h.Cursor.HasSelection() {
670 r := h.Cursor.RuneUnder(h.Cursor.X)
671 prev := h.Cursor.RuneUnder(h.Cursor.X - 1)
672 if !util.IsAutocomplete(prev) || !util.IsNonAlphaNumeric(r) {
673 // don't autocomplete if cursor is on alpha numeric character (middle of a word)
677 if b.HasSuggestions {
678 b.CycleAutocomplete(true)
681 return b.Autocomplete(buffer.BufferComplete)
684 // CycleAutocompleteBack cycles back in the autocomplete suggestion list
685 func (h *BufPane) CycleAutocompleteBack() bool {
686 if h.Cursor.HasSelection() {
690 if h.Buf.HasSuggestions {
691 h.Buf.CycleAutocomplete(false)
697 // InsertTab inserts a tab or spaces
698 func (h *BufPane) InsertTab() bool {
700 indent := b.IndentString(util.IntOpt(b.Settings["tabsize"]))
701 tabBytes := len(indent)
702 bytesUntilIndent := tabBytes - (h.Cursor.GetVisualX() % tabBytes)
703 b.Insert(h.Cursor.Loc, indent[:bytesUntilIndent])
708 // SaveAll saves all open buffers
709 func (h *BufPane) SaveAll() bool {
710 for _, b := range buffer.OpenBuffers {
716 // SaveCB performs a save and does a callback at the very end (after all prompts have been resolved)
717 func (h *BufPane) SaveCB(action string, callback func()) bool {
718 // If this is an empty buffer, ask for a filename
719 if h.Buf.Path == "" {
720 h.SaveAsCB(action, callback)
722 noPrompt := h.saveBufToFile(h.Buf.Path, action, callback)
730 // Save the buffer to disk
731 func (h *BufPane) Save() bool {
732 return h.SaveCB("Save", nil)
735 // SaveAsCB performs a save as and does a callback at the very end (after all prompts have been resolved)
736 // The callback is only called if the save was successful
737 func (h *BufPane) SaveAsCB(action string, callback func()) bool {
738 InfoBar.Prompt("Filename: ", "", "Save", nil, func(resp string, canceled bool) {
740 // the filename might or might not be quoted, so unquote first then join the strings.
741 args, err := shellquote.Split(resp)
743 InfoBar.Error("Error parsing arguments: ", err)
747 InfoBar.Error("No filename given")
750 filename := strings.Join(args, " ")
751 noPrompt := h.saveBufToFile(filename, action, callback)
753 h.completeAction(action)
760 // SaveAs saves the buffer to disk with the given name
761 func (h *BufPane) SaveAs() bool {
762 return h.SaveAsCB("SaveAs", nil)
765 // This function saves the buffer to `filename` and changes the buffer's path and name
766 // to `filename` if the save is successful
767 // The callback is only called if the save was successful
768 func (h *BufPane) saveBufToFile(filename string, action string, callback func()) bool {
769 err := h.Buf.SaveAs(filename)
771 if strings.HasSuffix(err.Error(), "permission denied") {
772 saveWithSudo := func() {
773 err = h.Buf.SaveAsWithSudo(filename)
777 h.Buf.Path = filename
778 h.Buf.SetName(filename)
779 InfoBar.Message("Saved " + filename)
785 if h.Buf.Settings["autosu"].(bool) {
788 InfoBar.YNPrompt("Permission denied. Do you want to save this file using sudo? (y,n)", func(yes, canceled bool) {
789 if yes && !canceled {
791 h.completeAction(action)
800 h.Buf.Path = filename
801 h.Buf.SetName(filename)
802 InfoBar.Message("Saved " + filename)
810 // Find opens a prompt and searches forward for the input
811 func (h *BufPane) Find() bool {
815 // FindLiteral is the same as Find() but does not support regular expressions
816 func (h *BufPane) FindLiteral() bool {
820 // Search searches for a given string/regex in the buffer and selects the next
821 // match if a match is found
822 // This function affects lastSearch and lastSearchRegex (saved searches) for
823 // use with FindNext and FindPrevious
824 func (h *BufPane) Search(str string, useRegex bool, searchDown bool) error {
825 match, found, err := h.Buf.FindNext(str, h.Buf.Start(), h.Buf.End(), h.Cursor.Loc, searchDown, useRegex)
830 h.Cursor.SetSelectionStart(match[0])
831 h.Cursor.SetSelectionEnd(match[1])
832 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
833 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
834 h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
836 h.lastSearchRegex = useRegex
839 h.Cursor.ResetSelection()
844 func (h *BufPane) find(useRegex bool) bool {
845 h.searchOrig = h.Cursor.Loc
848 prompt = "Find (regex): "
850 InfoBar.Prompt(prompt, "", "Find", func(resp string) {
852 match, found, _ := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
854 h.Cursor.SetSelectionStart(match[0])
855 h.Cursor.SetSelectionEnd(match[1])
856 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
857 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
858 h.Cursor.GotoLoc(match[1])
860 h.Cursor.GotoLoc(h.searchOrig)
861 h.Cursor.ResetSelection()
864 }, func(resp string, canceled bool) {
867 match, found, err := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
872 h.Cursor.SetSelectionStart(match[0])
873 h.Cursor.SetSelectionEnd(match[1])
874 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
875 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
876 h.Cursor.GotoLoc(h.Cursor.CurSelection[1])
878 h.lastSearchRegex = useRegex
880 h.Cursor.ResetSelection()
881 InfoBar.Message("No matches found")
884 h.Cursor.ResetSelection()
892 // FindNext searches forwards for the last used search term
893 func (h *BufPane) FindNext() bool {
894 // If the cursor is at the start of a selection and we search we want
895 // to search from the end of the selection in the case that
896 // the selection is a search result in which case we wouldn't move at
897 // at all which would be bad
898 searchLoc := h.Cursor.Loc
899 if h.Cursor.HasSelection() {
900 searchLoc = h.Cursor.CurSelection[1]
902 match, found, err := h.Buf.FindNext(h.lastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, true, h.lastSearchRegex)
907 h.Cursor.SetSelectionStart(match[0])
908 h.Cursor.SetSelectionEnd(match[1])
909 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
910 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
911 h.Cursor.Loc = h.Cursor.CurSelection[1]
913 h.Cursor.ResetSelection()
919 // FindPrevious searches backwards for the last used search term
920 func (h *BufPane) FindPrevious() bool {
921 // If the cursor is at the end of a selection and we search we want
922 // to search from the beginning of the selection in the case that
923 // the selection is a search result in which case we wouldn't move at
924 // at all which would be bad
925 searchLoc := h.Cursor.Loc
926 if h.Cursor.HasSelection() {
927 searchLoc = h.Cursor.CurSelection[0]
929 match, found, err := h.Buf.FindNext(h.lastSearch, h.Buf.Start(), h.Buf.End(), searchLoc, false, h.lastSearchRegex)
934 h.Cursor.SetSelectionStart(match[0])
935 h.Cursor.SetSelectionEnd(match[1])
936 h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
937 h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
938 h.Cursor.Loc = h.Cursor.CurSelection[1]
940 h.Cursor.ResetSelection()
946 // Undo undoes the last action
947 func (h *BufPane) Undo() bool {
949 InfoBar.Message("Undid action")
954 // Redo redoes the last action
955 func (h *BufPane) Redo() bool {
957 InfoBar.Message("Redid action")
962 // Copy the selection to the system clipboard
963 func (h *BufPane) Copy() bool {
964 if h.Cursor.HasSelection() {
965 h.Cursor.CopySelection(clipboard.ClipboardReg)
967 InfoBar.Message("Copied selection")
973 // Copy the current line to the clipboard
974 func (h *BufPane) CopyLine() bool {
975 if h.Cursor.HasSelection() {
978 h.Cursor.SelectLine()
979 h.Cursor.CopySelection(clipboard.ClipboardReg)
981 InfoBar.Message("Copied line")
983 h.Cursor.Deselect(true)
988 // CutLine cuts the current line to the clipboard
989 func (h *BufPane) CutLine() bool {
990 h.Cursor.SelectLine()
991 if !h.Cursor.HasSelection() {
995 if h.Cursor.HasSelection() {
996 if clip, err := clipboard.Read(clipboard.ClipboardReg); err != nil {
999 clipboard.WriteMulti(clip+string(h.Cursor.GetSelection()), clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
1002 } else if time.Since(h.lastCutTime)/time.Second > 10*time.Second || !h.freshClip {
1006 h.lastCutTime = time.Now()
1007 h.Cursor.DeleteSelection()
1008 h.Cursor.ResetSelection()
1009 InfoBar.Message("Cut line")
1014 // Cut the selection to the system clipboard
1015 func (h *BufPane) Cut() bool {
1016 if h.Cursor.HasSelection() {
1017 h.Cursor.CopySelection(clipboard.ClipboardReg)
1018 h.Cursor.DeleteSelection()
1019 h.Cursor.ResetSelection()
1021 InfoBar.Message("Cut selection")
1030 // DuplicateLine duplicates the current line or selection
1031 func (h *BufPane) DuplicateLine() bool {
1032 if h.Cursor.HasSelection() {
1033 h.Buf.Insert(h.Cursor.CurSelection[1], string(h.Cursor.GetSelection()))
1036 h.Buf.Insert(h.Cursor.Loc, "\n"+string(h.Buf.LineBytes(h.Cursor.Y)))
1040 InfoBar.Message("Duplicated line")
1045 // DeleteLine deletes the current line
1046 func (h *BufPane) DeleteLine() bool {
1047 h.Cursor.SelectLine()
1048 if !h.Cursor.HasSelection() {
1051 h.Cursor.DeleteSelection()
1052 h.Cursor.ResetSelection()
1053 InfoBar.Message("Deleted line")
1058 // MoveLinesUp moves up the current line or selected lines if any
1059 func (h *BufPane) MoveLinesUp() bool {
1060 if h.Cursor.HasSelection() {
1061 if h.Cursor.CurSelection[0].Y == 0 {
1062 InfoBar.Message("Cannot move further up")
1065 start := h.Cursor.CurSelection[0].Y
1066 end := h.Cursor.CurSelection[1].Y
1069 end, start = start, end
1074 if h.Cursor.CurSelection[sel].X != 0 {
1085 h.Cursor.CurSelection[sel].Y -= 1
1088 if h.Cursor.Loc.Y == 0 {
1089 InfoBar.Message("Cannot move further up")
1102 // MoveLinesDown moves down the current line or selected lines if any
1103 func (h *BufPane) MoveLinesDown() bool {
1104 if h.Cursor.HasSelection() {
1105 if h.Cursor.CurSelection[1].Y >= h.Buf.LinesNum() {
1106 InfoBar.Message("Cannot move further down")
1109 start := h.Cursor.CurSelection[0].Y
1110 end := h.Cursor.CurSelection[1].Y
1113 end, start = start, end
1117 if h.Cursor.CurSelection[sel].X != 0 {
1121 h.Buf.MoveLinesDown(
1126 if h.Cursor.Loc.Y >= h.Buf.LinesNum()-1 {
1127 InfoBar.Message("Cannot move further down")
1130 h.Buf.MoveLinesDown(
1140 // Paste whatever is in the system clipboard into the buffer
1141 // Delete and paste if the user has a selection
1142 func (h *BufPane) Paste() bool {
1143 clip, err := clipboard.ReadMulti(clipboard.ClipboardReg, h.Cursor.Num, h.Buf.NumCursors())
1153 // PastePrimary pastes from the primary clipboard (only use on linux)
1154 func (h *BufPane) PastePrimary() bool {
1155 clip, err := clipboard.ReadMulti(clipboard.PrimaryReg, h.Cursor.Num, h.Buf.NumCursors())
1165 func (h *BufPane) paste(clip string) {
1166 if h.Buf.Settings["smartpaste"].(bool) {
1167 if h.Cursor.X > 0 && len(util.GetLeadingWhitespace([]byte(strings.TrimLeft(clip, "\r\n")))) == 0 {
1168 leadingWS := util.GetLeadingWhitespace(h.Buf.LineBytes(h.Cursor.Y))
1169 clip = strings.Replace(clip, "\n", "\n"+string(leadingWS), -1)
1173 if h.Cursor.HasSelection() {
1174 h.Cursor.DeleteSelection()
1175 h.Cursor.ResetSelection()
1178 h.Buf.Insert(h.Cursor.Loc, clip)
1179 // h.Cursor.Loc = h.Cursor.Loc.Move(Count(clip), h.Buf)
1181 InfoBar.Message("Pasted clipboard")
1184 // JumpToMatchingBrace moves the cursor to the matching brace if it is
1185 // currently on a brace
1186 func (h *BufPane) JumpToMatchingBrace() bool {
1187 for _, bp := range buffer.BracePairs {
1188 r := h.Cursor.RuneUnder(h.Cursor.X)
1189 rl := h.Cursor.RuneUnder(h.Cursor.X - 1)
1190 if r == bp[0] || r == bp[1] || rl == bp[0] || rl == bp[1] {
1191 matchingBrace, left, found := h.Buf.FindMatchingBrace(bp, h.Cursor.Loc)
1194 h.Cursor.GotoLoc(matchingBrace)
1196 h.Cursor.GotoLoc(matchingBrace.Move(1, h.Buf))
1209 // SelectAll selects the entire buffer
1210 func (h *BufPane) SelectAll() bool {
1211 h.Cursor.SetSelectionStart(h.Buf.Start())
1212 h.Cursor.SetSelectionEnd(h.Buf.End())
1213 // Put the cursor at the beginning
1220 // OpenFile opens a new file in the buffer
1221 func (h *BufPane) OpenFile() bool {
1222 InfoBar.Prompt("> ", "open ", "Open", nil, func(resp string, canceled bool) {
1224 h.HandleCommand(resp)
1230 // OpenFile opens a new file in the buffer
1231 func (h *BufPane) JumpLine() bool {
1232 InfoBar.Prompt("> ", "goto ", "Command", nil, func(resp string, canceled bool) {
1234 h.HandleCommand(resp)
1240 // Start moves the viewport to the start of the buffer
1241 func (h *BufPane) Start() bool {
1248 // End moves the viewport to the end of the buffer
1249 func (h *BufPane) End() bool {
1250 // TODO: softwrap problems?
1252 if v.Height > h.Buf.LinesNum() {
1256 v.StartLine = h.Buf.LinesNum() - v.Height
1262 // PageUp scrolls the view up a page
1263 func (h *BufPane) PageUp() bool {
1265 if v.StartLine > v.Height {
1266 h.ScrollUp(v.Height)
1274 // PageDown scrolls the view down a page
1275 func (h *BufPane) PageDown() bool {
1277 if h.Buf.LinesNum()-(v.StartLine+v.Height) > v.Height {
1278 h.ScrollDown(v.Height)
1279 } else if h.Buf.LinesNum() >= v.Height {
1280 v.StartLine = h.Buf.LinesNum() - v.Height
1285 // SelectPageUp selects up one page
1286 func (h *BufPane) SelectPageUp() bool {
1287 if !h.Cursor.HasSelection() {
1288 h.Cursor.OrigSelection[0] = h.Cursor.Loc
1290 h.Cursor.UpN(h.GetView().Height)
1291 h.Cursor.SelectTo(h.Cursor.Loc)
1296 // SelectPageDown selects down one page
1297 func (h *BufPane) SelectPageDown() bool {
1298 if !h.Cursor.HasSelection() {
1299 h.Cursor.OrigSelection[0] = h.Cursor.Loc
1301 h.Cursor.DownN(h.GetView().Height)
1302 h.Cursor.SelectTo(h.Cursor.Loc)
1307 // CursorPageUp places the cursor a page up
1308 func (h *BufPane) CursorPageUp() bool {
1309 h.Cursor.Deselect(true)
1311 if h.Cursor.HasSelection() {
1312 h.Cursor.Loc = h.Cursor.CurSelection[0]
1313 h.Cursor.ResetSelection()
1314 h.Cursor.StoreVisualX()
1316 h.Cursor.UpN(h.GetView().Height)
1321 // CursorPageDown places the cursor a page up
1322 func (h *BufPane) CursorPageDown() bool {
1323 h.Cursor.Deselect(false)
1325 if h.Cursor.HasSelection() {
1326 h.Cursor.Loc = h.Cursor.CurSelection[1]
1327 h.Cursor.ResetSelection()
1328 h.Cursor.StoreVisualX()
1330 h.Cursor.DownN(h.GetView().Height)
1335 // HalfPageUp scrolls the view up half a page
1336 func (h *BufPane) HalfPageUp() bool {
1338 if v.StartLine > v.Height/2 {
1339 h.ScrollUp(v.Height / 2)
1347 // HalfPageDown scrolls the view down half a page
1348 func (h *BufPane) HalfPageDown() bool {
1350 if h.Buf.LinesNum()-(v.StartLine+v.Height) > v.Height/2 {
1351 h.ScrollDown(v.Height / 2)
1353 if h.Buf.LinesNum() >= v.Height {
1354 v.StartLine = h.Buf.LinesNum() - v.Height
1361 // ToggleDiffGutter turns the diff gutter off and on
1362 func (h *BufPane) ToggleDiffGutter() bool {
1363 if !h.Buf.Settings["diffgutter"].(bool) {
1364 h.Buf.Settings["diffgutter"] = true
1365 h.Buf.UpdateDiff(func(synchronous bool) {
1368 InfoBar.Message("Enabled diff gutter")
1370 h.Buf.Settings["diffgutter"] = false
1371 InfoBar.Message("Disabled diff gutter")
1376 // ToggleRuler turns line numbers off and on
1377 func (h *BufPane) ToggleRuler() bool {
1378 if !h.Buf.Settings["ruler"].(bool) {
1379 h.Buf.Settings["ruler"] = true
1380 InfoBar.Message("Enabled ruler")
1382 h.Buf.Settings["ruler"] = false
1383 InfoBar.Message("Disabled ruler")
1388 // ClearStatus clears the messenger bar
1389 func (h *BufPane) ClearStatus() bool {
1394 // ToggleHelp toggles the help screen
1395 func (h *BufPane) ToggleHelp() bool {
1396 if h.Buf.Type == buffer.BTHelp {
1404 // ToggleKeyMenu toggles the keymenu option and resizes all tabs
1405 func (h *BufPane) ToggleKeyMenu() bool {
1406 config.GlobalSettings["keymenu"] = !config.GetGlobalOption("keymenu").(bool)
1411 // ShellMode opens a terminal to run a shell command
1412 func (h *BufPane) ShellMode() bool {
1413 InfoBar.Prompt("$ ", "", "Shell", nil, func(resp string, canceled bool) {
1415 // The true here is for openTerm to make the command interactive
1416 shell.RunInteractiveShell(resp, true, false)
1423 // CommandMode lets the user enter a command
1424 func (h *BufPane) CommandMode() bool {
1425 InfoBar.Prompt("> ", "", "Command", nil, func(resp string, canceled bool) {
1427 h.HandleCommand(resp)
1433 // ToggleOverwriteMode lets the user toggle the text overwrite mode
1434 func (h *BufPane) ToggleOverwriteMode() bool {
1435 h.isOverwriteMode = !h.isOverwriteMode
1439 // Escape leaves current mode
1440 func (h *BufPane) Escape() bool {
1444 // Deselect deselects on the current cursor
1445 func (h *BufPane) Deselect() bool {
1446 h.Cursor.Deselect(true)
1450 // ClearInfo clears the infobar
1451 func (h *BufPane) ClearInfo() bool {
1456 // Quit this will close the current tab or view that is open
1457 func (h *BufPane) Quit() bool {
1460 if len(MainTab().Panes) > 1 {
1462 } else if len(Tabs.List) > 1 {
1463 Tabs.RemoveTab(h.splitID)
1465 screen.Screen.Fini()
1470 if h.Buf.Modified() {
1471 if config.GlobalSettings["autosave"].(float64) > 0 {
1472 // autosave on means we automatically save when quitting
1473 h.SaveCB("Quit", func() {
1477 InfoBar.YNPrompt("Save changes to "+h.Buf.GetName()+" before closing? (y,n,esc)", func(yes, canceled bool) {
1478 if !canceled && !yes {
1480 } else if !canceled && yes {
1481 h.SaveCB("Quit", func() {
1493 // QuitAll quits the whole editor; all splits and tabs
1494 func (h *BufPane) QuitAll() bool {
1495 anyModified := false
1496 for _, b := range buffer.OpenBuffers {
1504 for _, b := range buffer.OpenBuffers {
1507 screen.Screen.Fini()
1513 InfoBar.YNPrompt("Quit micro? (all open buffers will be closed without saving)", func(yes, canceled bool) {
1514 if !canceled && yes {
1525 // AddTab adds a new tab with an empty buffer
1526 func (h *BufPane) AddTab() bool {
1527 width, height := screen.Screen.Size()
1528 iOffset := config.GetInfoBarOffset()
1529 b := buffer.NewBufferFromString("", "", buffer.BTDefault)
1530 tp := NewTabFromBuffer(0, 0, width, height-iOffset, b)
1532 Tabs.SetActive(len(Tabs.List) - 1)
1537 // PreviousTab switches to the previous tab in the tab list
1538 func (h *BufPane) PreviousTab() bool {
1539 tabsLen := len(Tabs.List)
1540 a := Tabs.Active() + tabsLen
1541 Tabs.SetActive((a - 1) % tabsLen)
1546 // NextTab switches to the next tab in the tab list
1547 func (h *BufPane) NextTab() bool {
1549 Tabs.SetActive((a + 1) % len(Tabs.List))
1554 // VSplitAction opens an empty vertical split
1555 func (h *BufPane) VSplitAction() bool {
1556 h.VSplitBuf(buffer.NewBufferFromString("", "", buffer.BTDefault))
1561 // HSplitAction opens an empty horizontal split
1562 func (h *BufPane) HSplitAction() bool {
1563 h.HSplitBuf(buffer.NewBufferFromString("", "", buffer.BTDefault))
1568 // Unsplit closes all splits in the current tab except the active one
1569 func (h *BufPane) Unsplit() bool {
1571 n := tab.GetNode(h.splitID)
1574 tab.RemovePane(tab.GetPane(h.splitID))
1576 tab.SetActive(len(tab.Panes) - 1)
1583 // NextSplit changes the view to the next split
1584 func (h *BufPane) NextSplit() bool {
1586 if a < len(h.tab.Panes)-1 {
1597 // PreviousSplit changes the view to the previous split
1598 func (h *BufPane) PreviousSplit() bool {
1603 a = len(h.tab.Panes) - 1
1610 var curmacro []interface{}
1611 var recording_macro bool
1613 // ToggleMacro toggles recording of a macro
1614 func (h *BufPane) ToggleMacro() bool {
1615 recording_macro = !recording_macro
1616 if recording_macro {
1617 curmacro = []interface{}{}
1618 InfoBar.Message("Recording")
1620 InfoBar.Message("Stopped recording")
1626 // PlayMacro plays back the most recently recorded macro
1627 func (h *BufPane) PlayMacro() bool {
1628 if recording_macro {
1631 for _, action := range curmacro {
1632 switch t := action.(type) {
1635 case func(*BufPane) bool:
1643 // SpawnMultiCursor creates a new multiple cursor at the next occurrence of the current selection or current word
1644 func (h *BufPane) SpawnMultiCursor() bool {
1645 spawner := h.Buf.GetCursor(h.Buf.NumCursors() - 1)
1646 if !spawner.HasSelection() {
1647 spawner.SelectWord()
1653 sel := spawner.GetSelection()
1654 searchStart := spawner.CurSelection[1]
1656 search := string(sel)
1657 search = regexp.QuoteMeta(search)
1659 search = "\\b" + search + "\\b"
1661 match, found, err := h.Buf.FindNext(search, h.Buf.Start(), h.Buf.End(), searchStart, true, true)
1666 c := buffer.NewCursor(h.Buf, buffer.Loc{})
1667 c.SetSelectionStart(match[0])
1668 c.SetSelectionEnd(match[1])
1669 c.OrigSelection[0] = c.CurSelection[0]
1670 c.OrigSelection[1] = c.CurSelection[1]
1671 c.Loc = c.CurSelection[1]
1674 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1675 h.Buf.MergeCursors()
1677 InfoBar.Message("No matches found")
1684 // SpawnMultiCursorUp creates additional cursor, at the same X (if possible), one Y less.
1685 func (h *BufPane) SpawnMultiCursorUp() bool {
1686 if h.Cursor.Y == 0 {
1689 h.Cursor.GotoLoc(buffer.Loc{h.Cursor.X, h.Cursor.Y - 1})
1693 c := buffer.NewCursor(h.Buf, buffer.Loc{h.Cursor.X, h.Cursor.Y + 1})
1695 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1696 h.Buf.MergeCursors()
1702 // SpawnMultiCursorDown creates additional cursor, at the same X (if possible), one Y more.
1703 func (h *BufPane) SpawnMultiCursorDown() bool {
1704 if h.Cursor.Y+1 == h.Buf.LinesNum() {
1707 h.Cursor.GotoLoc(buffer.Loc{h.Cursor.X, h.Cursor.Y + 1})
1711 c := buffer.NewCursor(h.Buf, buffer.Loc{h.Cursor.X, h.Cursor.Y - 1})
1713 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1714 h.Buf.MergeCursors()
1719 // SpawnMultiCursorSelect adds a cursor at the beginning of each line of a selection
1720 func (h *BufPane) SpawnMultiCursorSelect() bool {
1721 // Avoid cases where multiple cursors already exist, that would create problems
1722 if h.Buf.NumCursors() > 1 {
1729 a, b := h.Cursor.CurSelection[0].Y, h.Cursor.CurSelection[1].Y
1731 startLine, endLine = b, a
1733 startLine, endLine = a, b
1736 if h.Cursor.HasSelection() {
1737 h.Cursor.ResetSelection()
1738 h.Cursor.GotoLoc(buffer.Loc{0, startLine})
1740 for i := startLine; i <= endLine; i++ {
1741 c := buffer.NewCursor(h.Buf, buffer.Loc{0, i})
1745 h.Buf.MergeCursors()
1749 InfoBar.Message("Added cursors from selection")
1753 // MouseMultiCursor is a mouse action which puts a new cursor at the mouse position
1754 func (h *BufPane) MouseMultiCursor(e *tcell.EventMouse) bool {
1756 mx, my := e.Position()
1757 mouseLoc := h.LocFromVisual(buffer.Loc{X: mx, Y: my})
1758 c := buffer.NewCursor(b, mouseLoc)
1765 // SkipMultiCursor moves the current multiple cursor to the next available position
1766 func (h *BufPane) SkipMultiCursor() bool {
1767 lastC := h.Buf.GetCursor(h.Buf.NumCursors() - 1)
1768 sel := lastC.GetSelection()
1769 searchStart := lastC.CurSelection[1]
1771 search := string(sel)
1772 search = regexp.QuoteMeta(search)
1774 search = "\\b" + search + "\\b"
1777 match, found, err := h.Buf.FindNext(search, h.Buf.Start(), h.Buf.End(), searchStart, true, true)
1782 lastC.SetSelectionStart(match[0])
1783 lastC.SetSelectionEnd(match[1])
1784 lastC.OrigSelection[0] = lastC.CurSelection[0]
1785 lastC.OrigSelection[1] = lastC.CurSelection[1]
1786 lastC.Loc = lastC.CurSelection[1]
1788 h.Buf.MergeCursors()
1789 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1791 InfoBar.Message("No matches found")
1797 // RemoveMultiCursor removes the latest multiple cursor
1798 func (h *BufPane) RemoveMultiCursor() bool {
1799 if h.Buf.NumCursors() > 1 {
1800 h.Buf.RemoveCursor(h.Buf.NumCursors() - 1)
1801 h.Buf.SetCurCursor(h.Buf.NumCursors() - 1)
1802 h.Buf.UpdateCursors()
1810 // RemoveAllMultiCursors removes all cursors except the base cursor
1811 func (h *BufPane) RemoveAllMultiCursors() bool {
1812 h.Buf.ClearCursors()
1818 // None is an action that does nothing
1819 func (h *BufPane) None() bool {