]> git.lizzy.rs Git - micro.git/blob - internal/action/bufpane.go
Command binding fix
[micro.git] / internal / action / bufpane.go
1 package action
2
3 import (
4         "strings"
5         "time"
6
7         luar "layeh.com/gopher-luar"
8
9         lua "github.com/yuin/gopher-lua"
10         "github.com/zyedidia/micro/internal/buffer"
11         "github.com/zyedidia/micro/internal/config"
12         "github.com/zyedidia/micro/internal/display"
13         ulua "github.com/zyedidia/micro/internal/lua"
14         "github.com/zyedidia/micro/internal/screen"
15         "github.com/zyedidia/tcell"
16 )
17
18 type BufKeyAction func(*BufPane) bool
19 type BufMouseAction func(*BufPane, *tcell.EventMouse) bool
20
21 var BufKeyBindings map[Event]BufKeyAction
22 var BufKeyStrings map[Event]string
23 var BufMouseBindings map[MouseEvent]BufMouseAction
24
25 func init() {
26         BufKeyBindings = make(map[Event]BufKeyAction)
27         BufKeyStrings = make(map[Event]string)
28         BufMouseBindings = make(map[MouseEvent]BufMouseAction)
29 }
30
31 func LuaAction(fn string) func(*BufPane) bool {
32         luaFn := strings.Split(fn, ".")
33         if len(luaFn) <= 1 {
34                 return nil
35         }
36         plName, plFn := luaFn[0], luaFn[1]
37         pl := config.FindPlugin(plName)
38         if pl == nil {
39                 return nil
40         }
41         return func(h *BufPane) bool {
42                 val, err := pl.Call(plFn, luar.New(ulua.L, h))
43                 if err != nil {
44                         screen.TermMessage(err)
45                 }
46                 if v, ok := val.(lua.LBool); !ok {
47                         return false
48                 } else {
49                         return bool(v)
50                 }
51         }
52 }
53
54 // BufMapKey maps a key event to an action
55 func BufMapKey(k Event, action string) {
56         BufKeyStrings[k] = action
57         var actionfns []func(*BufPane) bool
58         var names []string
59         var types []byte
60         for i := 0; ; i++ {
61                 if action == "" {
62                         break
63                 }
64
65                 // TODO: fix problem when complex bindings have these
66                 // characters (escape them?)
67                 idx := strings.IndexAny(action, "&|,")
68                 a := action
69                 if idx >= 0 {
70                         a = action[:idx]
71                         types = append(types, action[idx])
72                         action = action[idx+1:]
73                 } else {
74                         types = append(types, ' ')
75                         action = ""
76                 }
77
78                 var afn func(*BufPane) bool
79                 if strings.HasPrefix(a, "command:") {
80                         a = strings.SplitN(a, ":", 2)[1]
81                         afn = CommandAction(a)
82                         names = append(names, "")
83                 } else if strings.HasPrefix(a, "command-edit:") {
84                         a = strings.SplitN(a, ":", 2)[1]
85                         afn = CommandEditAction(a)
86                         names = append(names, "")
87                 } else if strings.HasPrefix(a, "lua:") {
88                         a = strings.SplitN(a, ":", 2)[1]
89                         afn = LuaAction(a)
90                         if afn == nil {
91                                 screen.TermMessage("Lua Error:", a, "does not exist")
92                                 continue
93                         }
94                         names = append(names, "")
95                 } else if f, ok := BufKeyActions[a]; ok {
96                         afn = f
97                         names = append(names, a)
98                 } else {
99                         screen.TermMessage("Error:", a, "does not exist")
100                         continue
101                 }
102                 actionfns = append(actionfns, afn)
103         }
104         BufKeyBindings[k] = func(h *BufPane) bool {
105                 cursors := h.Buf.GetCursors()
106                 success := true
107                 for i, a := range actionfns {
108                         for j, c := range cursors {
109                                 h.Buf.SetCurCursor(c.Num)
110                                 h.Cursor = c
111                                 if i == 0 || (success && types[i-1] == '&') || (!success && types[i-1] == '|') || (types[i-1] == ',') {
112                                         success = h.execAction(a, names[i], j)
113                                 } else {
114                                         break
115                                 }
116                         }
117                 }
118                 return true
119         }
120 }
121
122 // BufMapMouse maps a mouse event to an action
123 func BufMapMouse(k MouseEvent, action string) {
124         if f, ok := BufMouseActions[action]; ok {
125                 BufMouseBindings[k] = f
126         } else {
127                 delete(BufMouseBindings, k)
128                 BufMapKey(k, action)
129         }
130 }
131
132 // The BufPane connects the buffer and the window
133 // It provides a cursor (or multiple) and defines a set of actions
134 // that can be taken on the buffer
135 // The ActionHandler can access the window for necessary info about
136 // visual positions for mouse clicks and scrolling
137 type BufPane struct {
138         display.BWindow
139
140         Buf *buffer.Buffer
141
142         Cursor *buffer.Cursor // the active cursor
143
144         // Since tcell doesn't differentiate between a mouse release event
145         // and a mouse move event with no keys pressed, we need to keep
146         // track of whether or not the mouse was pressed (or not released) last event to determine
147         // mouse release events
148         mouseReleased bool
149
150         // We need to keep track of insert key press toggle
151         isOverwriteMode bool
152         // This stores when the last click was
153         // This is useful for detecting double and triple clicks
154         lastClickTime time.Time
155         lastLoc       buffer.Loc
156
157         // lastCutTime stores when the last ctrl+k was issued.
158         // It is used for clearing the clipboard to replace it with fresh cut lines.
159         lastCutTime time.Time
160
161         // freshClip returns true if the clipboard has never been pasted.
162         freshClip bool
163
164         // Was the last mouse event actually a double click?
165         // Useful for detecting triple clicks -- if a double click is detected
166         // but the last mouse event was actually a double click, it's a triple click
167         doubleClick bool
168         // Same here, just to keep track for mouse move events
169         tripleClick bool
170
171         // Last search stores the last successful search for FindNext and FindPrev
172         lastSearch string
173         // Should the current multiple cursor selection search based on word or
174         // based on selection (false for selection, true for word)
175         multiWord bool
176
177         splitID uint64
178
179         // remember original location of a search in case the search is canceled
180         searchOrig buffer.Loc
181 }
182
183 func NewBufPane(buf *buffer.Buffer, win display.BWindow) *BufPane {
184         h := new(BufPane)
185         h.Buf = buf
186         h.BWindow = win
187
188         h.Cursor = h.Buf.GetActiveCursor()
189         h.mouseReleased = true
190
191         config.RunPluginFn("onBufPaneOpen", luar.New(ulua.L, h))
192
193         return h
194 }
195
196 func NewBufPaneFromBuf(buf *buffer.Buffer) *BufPane {
197         w := display.NewBufWindow(0, 0, 0, 0, buf)
198         return NewBufPane(buf, w)
199 }
200
201 // PluginCB calls all plugin callbacks with a certain name and
202 // displays an error if there is one and returns the aggregrate
203 // boolean response
204 func (h *BufPane) PluginCB(cb string) bool {
205         b, err := config.RunPluginFnBool(cb, luar.New(ulua.L, h))
206         if err != nil {
207                 screen.TermMessage(err)
208         }
209         return b
210 }
211
212 // PluginCBRune is the same as PluginCB but also passes a rune to
213 // the plugins
214 func (h *BufPane) PluginCBRune(cb string, r rune) bool {
215         b, err := config.RunPluginFnBool(cb, luar.New(ulua.L, h), luar.New(ulua.L, string(r)))
216         if err != nil {
217                 screen.TermMessage(err)
218         }
219         return b
220 }
221
222 func (h *BufPane) OpenBuffer(b *buffer.Buffer) {
223         h.Buf.Close()
224         h.Buf = b
225         h.BWindow.SetBuffer(b)
226         h.Cursor = b.GetActiveCursor()
227         h.Resize(h.GetView().Width, h.GetView().Height)
228         v := new(display.View)
229         h.SetView(v)
230         h.Relocate()
231         // Set mouseReleased to true because we assume the mouse is not being pressed when
232         // the editor is opened
233         h.mouseReleased = true
234         // Set isOverwriteMode to false, because we assume we are in the default mode when editor
235         // is opened
236         h.isOverwriteMode = false
237         h.lastClickTime = time.Time{}
238 }
239
240 func (h *BufPane) ID() uint64 {
241         return h.splitID
242 }
243
244 func (h *BufPane) SetID(i uint64) {
245         h.splitID = i
246 }
247
248 func (h *BufPane) Name() string {
249         return h.Buf.GetName()
250 }
251
252 // HandleEvent executes the tcell event properly
253 func (h *BufPane) HandleEvent(event tcell.Event) {
254         if h.Buf.ExternallyModified() {
255                 InfoBar.YNPrompt("The file on disk has changed. Reload file? (y,n)", func(yes, canceled bool) {
256                         if !yes || canceled {
257                                 h.Buf.UpdateModTime()
258                         } else {
259                                 h.Buf.ReOpen()
260                         }
261                 })
262
263         }
264
265         switch e := event.(type) {
266         case *tcell.EventRaw:
267                 re := RawEvent{
268                         esc: e.EscSeq(),
269                 }
270                 h.DoKeyEvent(re)
271         case *tcell.EventKey:
272                 ke := KeyEvent{
273                         code: e.Key(),
274                         mod:  e.Modifiers(),
275                         r:    e.Rune(),
276                 }
277
278                 done := h.DoKeyEvent(ke)
279                 if !done && e.Key() == tcell.KeyRune {
280                         h.DoRuneInsert(e.Rune())
281                 }
282         case *tcell.EventMouse:
283                 switch e.Buttons() {
284                 case tcell.ButtonNone:
285                         // Mouse event with no click
286                         if !h.mouseReleased {
287                                 // Mouse was just released
288
289                                 mx, my := e.Position()
290                                 mouseLoc := h.LocFromVisual(buffer.Loc{X: mx, Y: my})
291
292                                 // Relocating here isn't really necessary because the cursor will
293                                 // be in the right place from the last mouse event
294                                 // However, if we are running in a terminal that doesn't support mouse motion
295                                 // events, this still allows the user to make selections, except only after they
296                                 // release the mouse
297
298                                 if !h.doubleClick && !h.tripleClick {
299                                         h.Cursor.Loc = mouseLoc
300                                         h.Cursor.SetSelectionEnd(h.Cursor.Loc)
301                                         h.Cursor.CopySelection("primary")
302                                 }
303                                 h.mouseReleased = true
304                         }
305                 }
306
307                 me := MouseEvent{
308                         btn: e.Buttons(),
309                         mod: e.Modifiers(),
310                 }
311                 h.DoMouseEvent(me, e)
312         }
313         h.Buf.MergeCursors()
314
315         if h.IsActive() {
316                 // Display any gutter messages for this line
317                 c := h.Buf.GetActiveCursor()
318                 none := true
319                 for _, m := range h.Buf.Messages {
320                         if c.Y == m.Start.Y || c.Y == m.End.Y {
321                                 InfoBar.GutterMessage(m.Msg)
322                                 none = false
323                                 break
324                         }
325                 }
326                 if none && InfoBar.HasGutter {
327                         InfoBar.ClearGutter()
328                 }
329         }
330 }
331
332 // DoKeyEvent executes a key event by finding the action it is bound
333 // to and executing it (possibly multiple times for multiple cursors)
334 func (h *BufPane) DoKeyEvent(e Event) bool {
335         if action, ok := BufKeyBindings[e]; ok {
336                 return action(h)
337         }
338         return false
339 }
340
341 func (h *BufPane) execAction(action func(*BufPane) bool, name string, cursor int) bool {
342         if name != "Autocomplete" {
343                 h.Buf.HasSuggestions = false
344         }
345
346         _, isMulti := MultiActions[name]
347         if (!isMulti && cursor == 0) || isMulti {
348                 if h.PluginCB("pre" + name) {
349                         asuccess := action(h)
350                         psuccess := h.PluginCB("on" + name)
351
352                         if isMulti {
353                                 if recording_macro {
354                                         if name != "ToggleMacro" && name != "PlayMacro" {
355                                                 curmacro = append(curmacro, action)
356                                         }
357                                 }
358                         }
359
360                         return asuccess && psuccess
361                 }
362         }
363
364         return false
365 }
366
367 func (h *BufPane) HasKeyEvent(e Event) bool {
368         _, ok := BufKeyBindings[e]
369         return ok
370 }
371
372 // DoMouseEvent executes a mouse event by finding the action it is bound
373 // to and executing it
374 func (h *BufPane) DoMouseEvent(e MouseEvent, te *tcell.EventMouse) bool {
375         if action, ok := BufMouseBindings[e]; ok {
376                 if action(h, te) {
377                         h.Relocate()
378                 }
379                 return true
380         } else if h.HasKeyEvent(e) {
381                 return h.DoKeyEvent(e)
382         }
383         return false
384 }
385
386 // DoRuneInsert inserts a given rune into the current buffer
387 // (possibly multiple times for multiple cursors)
388 func (h *BufPane) DoRuneInsert(r rune) {
389         cursors := h.Buf.GetCursors()
390         for _, c := range cursors {
391                 // Insert a character
392                 h.Buf.SetCurCursor(c.Num)
393                 h.Cursor = c
394                 if !h.PluginCBRune("preRune", r) {
395                         continue
396                 }
397                 if c.HasSelection() {
398                         c.DeleteSelection()
399                         c.ResetSelection()
400                 }
401
402                 if h.isOverwriteMode {
403                         next := c.Loc
404                         next.X++
405                         h.Buf.Replace(c.Loc, next, string(r))
406                 } else {
407                         h.Buf.Insert(c.Loc, string(r))
408                 }
409                 if recording_macro {
410                         curmacro = append(curmacro, r)
411                 }
412                 h.PluginCBRune("onRune", r)
413         }
414 }
415
416 func (h *BufPane) VSplitBuf(buf *buffer.Buffer) *BufPane {
417         e := NewBufPaneFromBuf(buf)
418         e.splitID = MainTab().GetNode(h.splitID).VSplit(h.Buf.Settings["splitright"].(bool))
419         MainTab().Panes = append(MainTab().Panes, e)
420         MainTab().Resize()
421         MainTab().SetActive(len(MainTab().Panes) - 1)
422         return e
423 }
424 func (h *BufPane) HSplitBuf(buf *buffer.Buffer) *BufPane {
425         e := NewBufPaneFromBuf(buf)
426         e.splitID = MainTab().GetNode(h.splitID).HSplit(h.Buf.Settings["splitbottom"].(bool))
427         MainTab().Panes = append(MainTab().Panes, e)
428         MainTab().Resize()
429         MainTab().SetActive(len(MainTab().Panes) - 1)
430         return e
431 }
432 func (h *BufPane) Close() {
433         h.Buf.Close()
434 }
435
436 func (h *BufPane) SetActive(b bool) {
437         h.BWindow.SetActive(b)
438         if b {
439                 // Display any gutter messages for this line
440                 c := h.Buf.GetActiveCursor()
441                 none := true
442                 for _, m := range h.Buf.Messages {
443                         if c.Y == m.Start.Y || c.Y == m.End.Y {
444                                 InfoBar.GutterMessage(m.Msg)
445                                 none = false
446                                 break
447                         }
448                 }
449                 if none && InfoBar.HasGutter {
450                         InfoBar.ClearGutter()
451                 }
452         }
453
454 }
455
456 // BufKeyActions contains the list of all possible key actions the bufhandler could execute
457 var BufKeyActions = map[string]BufKeyAction{
458         "CursorUp":               (*BufPane).CursorUp,
459         "CursorDown":             (*BufPane).CursorDown,
460         "CursorPageUp":           (*BufPane).CursorPageUp,
461         "CursorPageDown":         (*BufPane).CursorPageDown,
462         "CursorLeft":             (*BufPane).CursorLeft,
463         "CursorRight":            (*BufPane).CursorRight,
464         "CursorStart":            (*BufPane).CursorStart,
465         "CursorEnd":              (*BufPane).CursorEnd,
466         "SelectToStart":          (*BufPane).SelectToStart,
467         "SelectToEnd":            (*BufPane).SelectToEnd,
468         "SelectUp":               (*BufPane).SelectUp,
469         "SelectDown":             (*BufPane).SelectDown,
470         "SelectLeft":             (*BufPane).SelectLeft,
471         "SelectRight":            (*BufPane).SelectRight,
472         "WordRight":              (*BufPane).WordRight,
473         "WordLeft":               (*BufPane).WordLeft,
474         "SelectWordRight":        (*BufPane).SelectWordRight,
475         "SelectWordLeft":         (*BufPane).SelectWordLeft,
476         "DeleteWordRight":        (*BufPane).DeleteWordRight,
477         "DeleteWordLeft":         (*BufPane).DeleteWordLeft,
478         "SelectLine":             (*BufPane).SelectLine,
479         "SelectToStartOfLine":    (*BufPane).SelectToStartOfLine,
480         "SelectToEndOfLine":      (*BufPane).SelectToEndOfLine,
481         "ParagraphPrevious":      (*BufPane).ParagraphPrevious,
482         "ParagraphNext":          (*BufPane).ParagraphNext,
483         "InsertNewline":          (*BufPane).InsertNewline,
484         "Backspace":              (*BufPane).Backspace,
485         "Delete":                 (*BufPane).Delete,
486         "InsertTab":              (*BufPane).InsertTab,
487         "Save":                   (*BufPane).Save,
488         "SaveAll":                (*BufPane).SaveAll,
489         "SaveAs":                 (*BufPane).SaveAs,
490         "Find":                   (*BufPane).Find,
491         "FindNext":               (*BufPane).FindNext,
492         "FindPrevious":           (*BufPane).FindPrevious,
493         "Center":                 (*BufPane).Center,
494         "Undo":                   (*BufPane).Undo,
495         "Redo":                   (*BufPane).Redo,
496         "Copy":                   (*BufPane).Copy,
497         "Cut":                    (*BufPane).Cut,
498         "CutLine":                (*BufPane).CutLine,
499         "DuplicateLine":          (*BufPane).DuplicateLine,
500         "DeleteLine":             (*BufPane).DeleteLine,
501         "MoveLinesUp":            (*BufPane).MoveLinesUp,
502         "MoveLinesDown":          (*BufPane).MoveLinesDown,
503         "IndentSelection":        (*BufPane).IndentSelection,
504         "OutdentSelection":       (*BufPane).OutdentSelection,
505         "Autocomplete":           (*BufPane).Autocomplete,
506         "OutdentLine":            (*BufPane).OutdentLine,
507         "Paste":                  (*BufPane).Paste,
508         "PastePrimary":           (*BufPane).PastePrimary,
509         "SelectAll":              (*BufPane).SelectAll,
510         "OpenFile":               (*BufPane).OpenFile,
511         "Start":                  (*BufPane).Start,
512         "End":                    (*BufPane).End,
513         "PageUp":                 (*BufPane).PageUp,
514         "PageDown":               (*BufPane).PageDown,
515         "SelectPageUp":           (*BufPane).SelectPageUp,
516         "SelectPageDown":         (*BufPane).SelectPageDown,
517         "HalfPageUp":             (*BufPane).HalfPageUp,
518         "HalfPageDown":           (*BufPane).HalfPageDown,
519         "StartOfLine":            (*BufPane).StartOfLine,
520         "EndOfLine":              (*BufPane).EndOfLine,
521         "ToggleHelp":             (*BufPane).ToggleHelp,
522         "ToggleKeyMenu":          (*BufPane).ToggleKeyMenu,
523         "ToggleRuler":            (*BufPane).ToggleRuler,
524         "ClearStatus":            (*BufPane).ClearStatus,
525         "ShellMode":              (*BufPane).ShellMode,
526         "CommandMode":            (*BufPane).CommandMode,
527         "ToggleOverwriteMode":    (*BufPane).ToggleOverwriteMode,
528         "Escape":                 (*BufPane).Escape,
529         "Quit":                   (*BufPane).Quit,
530         "QuitAll":                (*BufPane).QuitAll,
531         "AddTab":                 (*BufPane).AddTab,
532         "PreviousTab":            (*BufPane).PreviousTab,
533         "NextTab":                (*BufPane).NextTab,
534         "NextSplit":              (*BufPane).NextSplit,
535         "PreviousSplit":          (*BufPane).PreviousSplit,
536         "Unsplit":                (*BufPane).Unsplit,
537         "VSplit":                 (*BufPane).VSplitAction,
538         "HSplit":                 (*BufPane).HSplitAction,
539         "ToggleMacro":            (*BufPane).ToggleMacro,
540         "PlayMacro":              (*BufPane).PlayMacro,
541         "Suspend":                (*BufPane).Suspend,
542         "ScrollUp":               (*BufPane).ScrollUpAction,
543         "ScrollDown":             (*BufPane).ScrollDownAction,
544         "SpawnMultiCursor":       (*BufPane).SpawnMultiCursor,
545         "SpawnMultiCursorSelect": (*BufPane).SpawnMultiCursorSelect,
546         "RemoveMultiCursor":      (*BufPane).RemoveMultiCursor,
547         "RemoveAllMultiCursors":  (*BufPane).RemoveAllMultiCursors,
548         "SkipMultiCursor":        (*BufPane).SkipMultiCursor,
549         "JumpToMatchingBrace":    (*BufPane).JumpToMatchingBrace,
550         "None":                   (*BufPane).None,
551
552         // This was changed to InsertNewline but I don't want to break backwards compatibility
553         "InsertEnter": (*BufPane).InsertNewline,
554 }
555
556 // BufMouseActions contains the list of all possible mouse actions the bufhandler could execute
557 var BufMouseActions = map[string]BufMouseAction{
558         "MousePress":       (*BufPane).MousePress,
559         "MouseMultiCursor": (*BufPane).MouseMultiCursor,
560 }
561
562 // MultiActions is a list of actions that should be executed multiple
563 // times if there are multiple cursors (one per cursor)
564 // Generally actions that modify global editor state like quitting or
565 // saving should not be included in this list
566 var MultiActions = map[string]bool{
567         "CursorUp":            true,
568         "CursorDown":          true,
569         "CursorPageUp":        true,
570         "CursorPageDown":      true,
571         "CursorLeft":          true,
572         "CursorRight":         true,
573         "CursorStart":         true,
574         "CursorEnd":           true,
575         "SelectToStart":       true,
576         "SelectToEnd":         true,
577         "SelectUp":            true,
578         "SelectDown":          true,
579         "SelectLeft":          true,
580         "SelectRight":         true,
581         "WordRight":           true,
582         "WordLeft":            true,
583         "SelectWordRight":     true,
584         "SelectWordLeft":      true,
585         "DeleteWordRight":     true,
586         "DeleteWordLeft":      true,
587         "SelectLine":          true,
588         "SelectToStartOfLine": true,
589         "SelectToEndOfLine":   true,
590         "ParagraphPrevious":   true,
591         "ParagraphNext":       true,
592         "InsertNewline":       true,
593         "Backspace":           true,
594         "Delete":              true,
595         "InsertTab":           true,
596         "FindNext":            true,
597         "FindPrevious":        true,
598         "Cut":                 true,
599         "CutLine":             true,
600         "DuplicateLine":       true,
601         "DeleteLine":          true,
602         "MoveLinesUp":         true,
603         "MoveLinesDown":       true,
604         "IndentSelection":     true,
605         "OutdentSelection":    true,
606         "OutdentLine":         true,
607         "Paste":               true,
608         "PastePrimary":        true,
609         "SelectPageUp":        true,
610         "SelectPageDown":      true,
611         "StartOfLine":         true,
612         "EndOfLine":           true,
613         "JumpToMatchingBrace": true,
614 }