7 luar "layeh.com/gopher-luar"
9 lua "github.com/yuin/gopher-lua"
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/display"
14 ulua "github.com/zyedidia/micro/v2/internal/lua"
15 "github.com/zyedidia/micro/v2/internal/screen"
16 "github.com/zyedidia/tcell/v2"
19 type BufKeyAction func(*BufPane) bool
20 type BufMouseAction func(*BufPane, *tcell.EventMouse) bool
22 var BufBindings *KeyTree
24 func BufKeyActionGeneral(a BufKeyAction) PaneKeyAction {
25 return func(p Pane) bool {
26 return a(p.(*BufPane))
30 func BufMouseActionGeneral(a BufMouseAction) PaneMouseAction {
31 return func(p Pane, me *tcell.EventMouse) bool {
32 return a(p.(*BufPane), me)
37 BufBindings = NewKeyTree()
40 func LuaAction(fn string) func(*BufPane) bool {
41 luaFn := strings.Split(fn, ".")
45 plName, plFn := luaFn[0], luaFn[1]
46 pl := config.FindPlugin(plName)
50 return func(h *BufPane) bool {
51 val, err := pl.Call(plFn, luar.New(ulua.L, h))
53 screen.TermMessage(err)
55 if v, ok := val.(lua.LBool); !ok {
63 // BufMapKey maps an event to an action
64 func BufMapEvent(k Event, action string) {
65 switch e := k.(type) {
66 case KeyEvent, KeySequenceEvent, RawEvent:
69 bufMapMouse(e, action)
73 func bufMapKey(k Event, action string) {
74 var actionfns []func(*BufPane) bool
82 // TODO: fix problem when complex bindings have these
83 // characters (escape them?)
84 idx := strings.IndexAny(action, "&|,")
88 types = append(types, action[idx])
89 action = action[idx+1:]
91 types = append(types, ' ')
95 var afn func(*BufPane) bool
96 if strings.HasPrefix(a, "command:") {
97 a = strings.SplitN(a, ":", 2)[1]
98 afn = CommandAction(a)
99 names = append(names, "")
100 } else if strings.HasPrefix(a, "command-edit:") {
101 a = strings.SplitN(a, ":", 2)[1]
102 afn = CommandEditAction(a)
103 names = append(names, "")
104 } else if strings.HasPrefix(a, "lua:") {
105 a = strings.SplitN(a, ":", 2)[1]
108 screen.TermMessage("Lua Error:", a, "does not exist")
111 split := strings.SplitN(a, ".", 2)
113 a = strings.Title(split[0]) + strings.Title(split[1])
118 names = append(names, a)
119 } else if f, ok := BufKeyActions[a]; ok {
121 names = append(names, a)
123 screen.TermMessage("Error in bindings: action", a, "does not exist")
126 actionfns = append(actionfns, afn)
128 bufAction := func(h *BufPane) bool {
129 cursors := h.Buf.GetCursors()
131 for i, a := range actionfns {
133 for j, c := range cursors {
137 h.Buf.SetCurCursor(c.Num)
139 if i == 0 || (success && types[i-1] == '&') || (!success && types[i-1] == '|') || (types[i-1] == ',') {
140 innerSuccess = innerSuccess && h.execAction(a, names[i], j)
145 // if the action changed the current pane, update the reference
146 h = MainTab().CurPane()
147 success = innerSuccess
152 BufBindings.RegisterKeyBinding(k, BufKeyActionGeneral(bufAction))
155 // BufMapMouse maps a mouse event to an action
156 func bufMapMouse(k MouseEvent, action string) {
157 if f, ok := BufMouseActions[action]; ok {
158 BufBindings.RegisterMouseBinding(k, BufMouseActionGeneral(f))
161 // delete(BufMouseBindings, k)
166 // BufUnmap unmaps a key or mouse event from any action
167 func BufUnmap(k Event) {
169 // delete(BufKeyBindings, k)
171 // switch e := k.(type) {
173 // delete(BufMouseBindings, e)
177 // The BufPane connects the buffer and the window
178 // It provides a cursor (or multiple) and defines a set of actions
179 // that can be taken on the buffer
180 // The ActionHandler can access the window for necessary info about
181 // visual positions for mouse clicks and scrolling
182 type BufPane struct {
185 // Buf is the buffer this BufPane views
187 // Bindings stores the association of key events and actions
190 // Cursor is the currently active buffer cursor
191 Cursor *buffer.Cursor
193 // Since tcell doesn't differentiate between a mouse release event
194 // and a mouse move event with no keys pressed, we need to keep
195 // track of whether or not the mouse was pressed (or not released) last event to determine
196 // mouse release events
199 // We need to keep track of insert key press toggle
201 // This stores when the last click was
202 // This is useful for detecting double and triple clicks
203 lastClickTime time.Time
206 // lastCutTime stores when the last ctrl+k was issued.
207 // It is used for clearing the clipboard to replace it with fresh cut lines.
208 lastCutTime time.Time
210 // freshClip returns true if the clipboard has never been pasted.
213 // Was the last mouse event actually a double click?
214 // Useful for detecting triple clicks -- if a double click is detected
215 // but the last mouse event was actually a double click, it's a triple click
217 // Same here, just to keep track for mouse move events
220 // Last search stores the last successful search for FindNext and FindPrev
223 // Should the current multiple cursor selection search based on word or
224 // based on selection (false for selection, true for word)
230 // remember original location of a search in case the search is canceled
231 searchOrig buffer.Loc
234 func NewBufPane(buf *buffer.Buffer, win display.BWindow, tab *Tab) *BufPane {
240 h.Cursor = h.Buf.GetActiveCursor()
241 h.mouseReleased = true
243 config.RunPluginFn("onBufPaneOpen", luar.New(ulua.L, h))
248 func NewBufPaneFromBuf(buf *buffer.Buffer, tab *Tab) *BufPane {
249 w := display.NewBufWindow(0, 0, 0, 0, buf)
250 return NewBufPane(buf, w, tab)
253 func (h *BufPane) SetTab(t *Tab) {
257 func (h *BufPane) Tab() *Tab {
261 func (h *BufPane) ResizePane(size int) {
262 n := h.tab.GetNode(h.splitID)
267 // PluginCB calls all plugin callbacks with a certain name and
268 // displays an error if there is one and returns the aggregrate
270 func (h *BufPane) PluginCB(cb string) bool {
271 b, err := config.RunPluginFnBool(cb, luar.New(ulua.L, h))
273 screen.TermMessage(err)
278 // PluginCBRune is the same as PluginCB but also passes a rune to
280 func (h *BufPane) PluginCBRune(cb string, r rune) bool {
281 b, err := config.RunPluginFnBool(cb, luar.New(ulua.L, h), luar.New(ulua.L, string(r)))
283 screen.TermMessage(err)
288 func (h *BufPane) OpenBuffer(b *buffer.Buffer) {
291 h.BWindow.SetBuffer(b)
292 h.Cursor = b.GetActiveCursor()
293 h.Resize(h.GetView().Width, h.GetView().Height)
295 // Set mouseReleased to true because we assume the mouse is not being pressed when
296 // the editor is opened
297 h.mouseReleased = true
298 // Set isOverwriteMode to false, because we assume we are in the default mode when editor
300 h.isOverwriteMode = false
301 h.lastClickTime = time.Time{}
304 func (h *BufPane) ID() uint64 {
308 func (h *BufPane) SetID(i uint64) {
312 func (h *BufPane) Name() string {
314 if h.Buf.Modified() {
320 // HandleEvent executes the tcell event properly
321 func (h *BufPane) HandleEvent(event tcell.Event) {
322 if h.Buf.ExternallyModified() && !h.Buf.ReloadDisabled {
323 InfoBar.YNPrompt("The file on disk has changed. Reload file? (y,n,esc)", func(yes, canceled bool) {
325 h.Buf.DisableReload()
327 if !yes || canceled {
328 h.Buf.UpdateModTime()
336 switch e := event.(type) {
337 case *tcell.EventRaw:
342 case *tcell.EventPaste:
345 case *tcell.EventKey:
352 done := h.DoKeyEvent(ke)
353 if !done && e.Key() == tcell.KeyRune {
354 h.DoRuneInsert(e.Rune())
356 case *tcell.EventMouse:
360 _, my := e.Position()
361 if h.Buf.Type.Kind != buffer.BTInfo.Kind && h.Buf.Settings["statusline"].(bool) && my >= h.GetView().Y+h.GetView().Height-1 {
364 case tcell.ButtonNone:
365 // Mouse event with no click
366 if !h.mouseReleased {
367 // Mouse was just released
369 // mx, my := e.Position()
370 // mouseLoc := h.LocFromVisual(buffer.Loc{X: mx, Y: my})
372 // we could finish the selection based on the release location as described
373 // below but when the mouse click is within the scroll margin this will
374 // cause a scroll and selection even for a simple mouse click which is
376 // for terminals that don't support mouse motion events, selection via
377 // the mouse won't work but this is ok
379 // Relocating here isn't really necessary because the cursor will
380 // be in the right place from the last mouse event
381 // However, if we are running in a terminal that doesn't support mouse motion
382 // events, this still allows the user to make selections, except only after they
385 // if !h.doubleClick && !h.tripleClick {
386 // h.Cursor.SetSelectionEnd(h.Cursor.Loc)
388 if h.Cursor.HasSelection() {
389 h.Cursor.CopySelection(clipboard.PrimaryReg)
391 h.mouseReleased = true
400 h.DoMouseEvent(me, e)
406 // Display any gutter messages for this line
407 c := h.Buf.GetActiveCursor()
409 for _, m := range h.Buf.Messages {
410 if c.Y == m.Start.Y || c.Y == m.End.Y {
411 InfoBar.GutterMessage(m.Msg)
416 if none && InfoBar.HasGutter {
417 InfoBar.ClearGutter()
422 func (h *BufPane) Bindings() *KeyTree {
423 if h.bindings != nil {
429 // DoKeyEvent executes a key event by finding the action it is bound
430 // to and executing it (possibly multiple times for multiple cursors)
431 func (h *BufPane) DoKeyEvent(e Event) bool {
432 binds := h.Bindings()
433 action, more := binds.NextEvent(e, nil)
434 if action != nil && !more {
438 } else if action == nil && !more {
444 func (h *BufPane) execAction(action func(*BufPane) bool, name string, cursor int) bool {
445 if name != "Autocomplete" && name != "CycleAutocompleteBack" {
446 h.Buf.HasSuggestions = false
449 _, isMulti := MultiActions[name]
450 if (!isMulti && cursor == 0) || isMulti {
451 if h.PluginCB("pre" + name) {
453 success = success && h.PluginCB("on"+name)
457 if name != "ToggleMacro" && name != "PlayMacro" {
458 curmacro = append(curmacro, action)
470 func (h *BufPane) completeAction(action string) {
471 h.PluginCB("on" + action)
474 func (h *BufPane) HasKeyEvent(e Event) bool {
477 // _, ok := BufKeyBindings[e]
481 // DoMouseEvent executes a mouse event by finding the action it is bound
482 // to and executing it
483 func (h *BufPane) DoMouseEvent(e MouseEvent, te *tcell.EventMouse) bool {
484 binds := h.Bindings()
485 action, _ := binds.NextEvent(e, te)
494 // if action, ok := BufMouseBindings[e]; ok {
495 // if action(h, te) {
499 // } else if h.HasKeyEvent(e) {
500 // return h.DoKeyEvent(e)
505 // DoRuneInsert inserts a given rune into the current buffer
506 // (possibly multiple times for multiple cursors)
507 func (h *BufPane) DoRuneInsert(r rune) {
508 cursors := h.Buf.GetCursors()
509 for _, c := range cursors {
510 // Insert a character
511 h.Buf.SetCurCursor(c.Num)
513 if !h.PluginCBRune("preRune", r) {
516 if c.HasSelection() {
521 if h.isOverwriteMode {
524 h.Buf.Replace(c.Loc, next, string(r))
526 h.Buf.Insert(c.Loc, string(r))
529 curmacro = append(curmacro, r)
532 h.PluginCBRune("onRune", r)
536 func (h *BufPane) VSplitIndex(buf *buffer.Buffer, right bool) *BufPane {
537 e := NewBufPaneFromBuf(buf, h.tab)
538 e.splitID = MainTab().GetNode(h.splitID).VSplit(right)
539 MainTab().Panes = append(MainTab().Panes, e)
541 MainTab().SetActive(len(MainTab().Panes) - 1)
544 func (h *BufPane) HSplitIndex(buf *buffer.Buffer, bottom bool) *BufPane {
545 e := NewBufPaneFromBuf(buf, h.tab)
546 e.splitID = MainTab().GetNode(h.splitID).HSplit(bottom)
547 MainTab().Panes = append(MainTab().Panes, e)
549 MainTab().SetActive(len(MainTab().Panes) - 1)
553 func (h *BufPane) VSplitBuf(buf *buffer.Buffer) *BufPane {
554 return h.VSplitIndex(buf, h.Buf.Settings["splitright"].(bool))
556 func (h *BufPane) HSplitBuf(buf *buffer.Buffer) *BufPane {
557 return h.HSplitIndex(buf, h.Buf.Settings["splitbottom"].(bool))
559 func (h *BufPane) Close() {
563 func (h *BufPane) SetActive(b bool) {
564 h.BWindow.SetActive(b)
566 // Display any gutter messages for this line
567 c := h.Buf.GetActiveCursor()
569 for _, m := range h.Buf.Messages {
570 if c.Y == m.Start.Y || c.Y == m.End.Y {
571 InfoBar.GutterMessage(m.Msg)
576 if none && InfoBar.HasGutter {
577 InfoBar.ClearGutter()
583 // BufKeyActions contains the list of all possible key actions the bufhandler could execute
584 var BufKeyActions = map[string]BufKeyAction{
585 "CursorUp": (*BufPane).CursorUp,
586 "CursorDown": (*BufPane).CursorDown,
587 "CursorPageUp": (*BufPane).CursorPageUp,
588 "CursorPageDown": (*BufPane).CursorPageDown,
589 "CursorLeft": (*BufPane).CursorLeft,
590 "CursorRight": (*BufPane).CursorRight,
591 "CursorStart": (*BufPane).CursorStart,
592 "CursorEnd": (*BufPane).CursorEnd,
593 "SelectToStart": (*BufPane).SelectToStart,
594 "SelectToEnd": (*BufPane).SelectToEnd,
595 "SelectUp": (*BufPane).SelectUp,
596 "SelectDown": (*BufPane).SelectDown,
597 "SelectLeft": (*BufPane).SelectLeft,
598 "SelectRight": (*BufPane).SelectRight,
599 "WordRight": (*BufPane).WordRight,
600 "WordLeft": (*BufPane).WordLeft,
601 "SelectWordRight": (*BufPane).SelectWordRight,
602 "SelectWordLeft": (*BufPane).SelectWordLeft,
603 "DeleteWordRight": (*BufPane).DeleteWordRight,
604 "DeleteWordLeft": (*BufPane).DeleteWordLeft,
605 "SelectLine": (*BufPane).SelectLine,
606 "SelectToStartOfLine": (*BufPane).SelectToStartOfLine,
607 "SelectToStartOfText": (*BufPane).SelectToStartOfText,
608 "SelectToStartOfTextToggle": (*BufPane).SelectToStartOfTextToggle,
609 "SelectToEndOfLine": (*BufPane).SelectToEndOfLine,
610 "ParagraphPrevious": (*BufPane).ParagraphPrevious,
611 "ParagraphNext": (*BufPane).ParagraphNext,
612 "InsertNewline": (*BufPane).InsertNewline,
613 "Backspace": (*BufPane).Backspace,
614 "Delete": (*BufPane).Delete,
615 "InsertTab": (*BufPane).InsertTab,
616 "Save": (*BufPane).Save,
617 "SaveAll": (*BufPane).SaveAll,
618 "SaveAs": (*BufPane).SaveAs,
619 "Find": (*BufPane).Find,
620 "FindLiteral": (*BufPane).FindLiteral,
621 "FindNext": (*BufPane).FindNext,
622 "FindPrevious": (*BufPane).FindPrevious,
623 "Center": (*BufPane).Center,
624 "Undo": (*BufPane).Undo,
625 "Redo": (*BufPane).Redo,
626 "Copy": (*BufPane).Copy,
627 "CopyLine": (*BufPane).CopyLine,
628 "Cut": (*BufPane).Cut,
629 "CutLine": (*BufPane).CutLine,
630 "DuplicateLine": (*BufPane).DuplicateLine,
631 "DeleteLine": (*BufPane).DeleteLine,
632 "MoveLinesUp": (*BufPane).MoveLinesUp,
633 "MoveLinesDown": (*BufPane).MoveLinesDown,
634 "IndentSelection": (*BufPane).IndentSelection,
635 "OutdentSelection": (*BufPane).OutdentSelection,
636 "Autocomplete": (*BufPane).Autocomplete,
637 "CycleAutocompleteBack": (*BufPane).CycleAutocompleteBack,
638 "OutdentLine": (*BufPane).OutdentLine,
639 "IndentLine": (*BufPane).IndentLine,
640 "Paste": (*BufPane).Paste,
641 "PastePrimary": (*BufPane).PastePrimary,
642 "SelectAll": (*BufPane).SelectAll,
643 "OpenFile": (*BufPane).OpenFile,
644 "Start": (*BufPane).Start,
645 "End": (*BufPane).End,
646 "PageUp": (*BufPane).PageUp,
647 "PageDown": (*BufPane).PageDown,
648 "SelectPageUp": (*BufPane).SelectPageUp,
649 "SelectPageDown": (*BufPane).SelectPageDown,
650 "HalfPageUp": (*BufPane).HalfPageUp,
651 "HalfPageDown": (*BufPane).HalfPageDown,
652 "StartOfText": (*BufPane).StartOfText,
653 "StartOfTextToggle": (*BufPane).StartOfTextToggle,
654 "StartOfLine": (*BufPane).StartOfLine,
655 "EndOfLine": (*BufPane).EndOfLine,
656 "ToggleHelp": (*BufPane).ToggleHelp,
657 "ToggleKeyMenu": (*BufPane).ToggleKeyMenu,
658 "ToggleDiffGutter": (*BufPane).ToggleDiffGutter,
659 "ToggleRuler": (*BufPane).ToggleRuler,
660 "ClearStatus": (*BufPane).ClearStatus,
661 "ShellMode": (*BufPane).ShellMode,
662 "CommandMode": (*BufPane).CommandMode,
663 "ToggleOverwriteMode": (*BufPane).ToggleOverwriteMode,
664 "Escape": (*BufPane).Escape,
665 "Quit": (*BufPane).Quit,
666 "QuitAll": (*BufPane).QuitAll,
667 "AddTab": (*BufPane).AddTab,
668 "PreviousTab": (*BufPane).PreviousTab,
669 "NextTab": (*BufPane).NextTab,
670 "NextSplit": (*BufPane).NextSplit,
671 "PreviousSplit": (*BufPane).PreviousSplit,
672 "Unsplit": (*BufPane).Unsplit,
673 "VSplit": (*BufPane).VSplitAction,
674 "HSplit": (*BufPane).HSplitAction,
675 "ToggleMacro": (*BufPane).ToggleMacro,
676 "PlayMacro": (*BufPane).PlayMacro,
677 "Suspend": (*BufPane).Suspend,
678 "ScrollUp": (*BufPane).ScrollUpAction,
679 "ScrollDown": (*BufPane).ScrollDownAction,
680 "SpawnMultiCursor": (*BufPane).SpawnMultiCursor,
681 "SpawnMultiCursorUp": (*BufPane).SpawnMultiCursorUp,
682 "SpawnMultiCursorDown": (*BufPane).SpawnMultiCursorDown,
683 "SpawnMultiCursorSelect": (*BufPane).SpawnMultiCursorSelect,
684 "RemoveMultiCursor": (*BufPane).RemoveMultiCursor,
685 "RemoveAllMultiCursors": (*BufPane).RemoveAllMultiCursors,
686 "SkipMultiCursor": (*BufPane).SkipMultiCursor,
687 "JumpToMatchingBrace": (*BufPane).JumpToMatchingBrace,
688 "JumpLine": (*BufPane).JumpLine,
689 "Deselect": (*BufPane).Deselect,
690 "ClearInfo": (*BufPane).ClearInfo,
691 "None": (*BufPane).None,
693 // This was changed to InsertNewline but I don't want to break backwards compatibility
694 "InsertEnter": (*BufPane).InsertNewline,
697 // BufMouseActions contains the list of all possible mouse actions the bufhandler could execute
698 var BufMouseActions = map[string]BufMouseAction{
699 "MousePress": (*BufPane).MousePress,
700 "MouseMultiCursor": (*BufPane).MouseMultiCursor,
703 // MultiActions is a list of actions that should be executed multiple
704 // times if there are multiple cursors (one per cursor)
705 // Generally actions that modify global editor state like quitting or
706 // saving should not be included in this list
707 var MultiActions = map[string]bool{
710 "CursorPageUp": true,
711 "CursorPageDown": true,
716 "SelectToStart": true,
724 "SelectWordRight": true,
725 "SelectWordLeft": true,
726 "DeleteWordRight": true,
727 "DeleteWordLeft": true,
729 "SelectToStartOfLine": true,
730 "SelectToStartOfText": true,
731 "SelectToStartOfTextToggle": true,
732 "SelectToEndOfLine": true,
733 "ParagraphPrevious": true,
734 "ParagraphNext": true,
735 "InsertNewline": true,
740 "FindPrevious": true,
745 "DuplicateLine": true,
748 "MoveLinesDown": true,
749 "IndentSelection": true,
750 "OutdentSelection": true,
754 "PastePrimary": true,
755 "SelectPageUp": true,
756 "SelectPageDown": true,
759 "StartOfTextToggle": true,
761 "JumpToMatchingBrace": true,