]> git.lizzy.rs Git - micro.git/blob - cmd/micro/bindings.go
Merge pull request #850 from nitsakh/feat-809
[micro.git] / cmd / micro / bindings.go
1 package main
2
3 import (
4         "io/ioutil"
5         "os"
6         "strings"
7
8         "github.com/flynn/json5"
9         "github.com/zyedidia/tcell"
10 )
11
12 var bindings map[Key][]func(*View, bool) bool
13 var mouseBindings map[Key][]func(*View, bool, *tcell.EventMouse) bool
14 var helpBinding string
15 var kmenuBinding string
16
17 var mouseBindingActions = map[string]func(*View, bool, *tcell.EventMouse) bool{
18         "MousePress":       (*View).MousePress,
19         "MouseMultiCursor": (*View).MouseMultiCursor,
20 }
21
22 var bindingActions = map[string]func(*View, bool) bool{
23         "CursorUp":              (*View).CursorUp,
24         "CursorDown":            (*View).CursorDown,
25         "CursorPageUp":          (*View).CursorPageUp,
26         "CursorPageDown":        (*View).CursorPageDown,
27         "CursorLeft":            (*View).CursorLeft,
28         "CursorRight":           (*View).CursorRight,
29         "CursorStart":           (*View).CursorStart,
30         "CursorEnd":             (*View).CursorEnd,
31         "SelectToStart":         (*View).SelectToStart,
32         "SelectToEnd":           (*View).SelectToEnd,
33         "SelectUp":              (*View).SelectUp,
34         "SelectDown":            (*View).SelectDown,
35         "SelectLeft":            (*View).SelectLeft,
36         "SelectRight":           (*View).SelectRight,
37         "WordRight":             (*View).WordRight,
38         "WordLeft":              (*View).WordLeft,
39         "SelectWordRight":       (*View).SelectWordRight,
40         "SelectWordLeft":        (*View).SelectWordLeft,
41         "DeleteWordRight":       (*View).DeleteWordRight,
42         "DeleteWordLeft":        (*View).DeleteWordLeft,
43         "SelectToStartOfLine":   (*View).SelectToStartOfLine,
44         "SelectToEndOfLine":     (*View).SelectToEndOfLine,
45         "ParagraphPrevious":     (*View).ParagraphPrevious,
46         "ParagraphNext":         (*View).ParagraphNext,
47         "InsertNewline":         (*View).InsertNewline,
48         "InsertSpace":           (*View).InsertSpace,
49         "Backspace":             (*View).Backspace,
50         "Delete":                (*View).Delete,
51         "InsertTab":             (*View).InsertTab,
52         "Save":                  (*View).Save,
53         "SaveAll":               (*View).SaveAll,
54         "SaveAs":                (*View).SaveAs,
55         "Find":                  (*View).Find,
56         "FindNext":              (*View).FindNext,
57         "FindPrevious":          (*View).FindPrevious,
58         "Center":                (*View).Center,
59         "Undo":                  (*View).Undo,
60         "Redo":                  (*View).Redo,
61         "Copy":                  (*View).Copy,
62         "Cut":                   (*View).Cut,
63         "CutLine":               (*View).CutLine,
64         "DuplicateLine":         (*View).DuplicateLine,
65         "DeleteLine":            (*View).DeleteLine,
66         "MoveLinesUp":           (*View).MoveLinesUp,
67         "MoveLinesDown":         (*View).MoveLinesDown,
68         "IndentSelection":       (*View).IndentSelection,
69         "OutdentSelection":      (*View).OutdentSelection,
70         "OutdentLine":           (*View).OutdentLine,
71         "Paste":                 (*View).Paste,
72         "PastePrimary":          (*View).PastePrimary,
73         "SelectAll":             (*View).SelectAll,
74         "OpenFile":              (*View).OpenFile,
75         "Start":                 (*View).Start,
76         "End":                   (*View).End,
77         "PageUp":                (*View).PageUp,
78         "PageDown":              (*View).PageDown,
79         "HalfPageUp":            (*View).HalfPageUp,
80         "HalfPageDown":          (*View).HalfPageDown,
81         "StartOfLine":           (*View).StartOfLine,
82         "EndOfLine":             (*View).EndOfLine,
83         "ToggleHelp":            (*View).ToggleHelp,
84         "ToggleKeyMenu":         (*View).ToggleKeyMenu,
85         "ToggleRuler":           (*View).ToggleRuler,
86         "JumpLine":              (*View).JumpLine,
87         "ClearStatus":           (*View).ClearStatus,
88         "ShellMode":             (*View).ShellMode,
89         "CommandMode":           (*View).CommandMode,
90         "Escape":                (*View).Escape,
91         "Quit":                  (*View).Quit,
92         "QuitAll":               (*View).QuitAll,
93         "AddTab":                (*View).AddTab,
94         "PreviousTab":           (*View).PreviousTab,
95         "NextTab":               (*View).NextTab,
96         "NextSplit":             (*View).NextSplit,
97         "PreviousSplit":         (*View).PreviousSplit,
98         "Unsplit":               (*View).Unsplit,
99         "VSplit":                (*View).VSplitBinding,
100         "HSplit":                (*View).HSplitBinding,
101         "ToggleMacro":           (*View).ToggleMacro,
102         "PlayMacro":             (*View).PlayMacro,
103         "Suspend":               (*View).Suspend,
104         "ScrollUp":              (*View).ScrollUpAction,
105         "ScrollDown":            (*View).ScrollDownAction,
106         "SpawnMultiCursor":      (*View).SpawnMultiCursor,
107         "RemoveMultiCursor":     (*View).RemoveMultiCursor,
108         "RemoveAllMultiCursors": (*View).RemoveAllMultiCursors,
109         "SkipMultiCursor":       (*View).SkipMultiCursor,
110
111         // This was changed to InsertNewline but I don't want to break backwards compatibility
112         "InsertEnter": (*View).InsertNewline,
113 }
114
115 var bindingMouse = map[string]tcell.ButtonMask{
116         "MouseLeft":       tcell.Button1,
117         "MouseMiddle":     tcell.Button2,
118         "MouseRight":      tcell.Button3,
119         "MouseWheelUp":    tcell.WheelUp,
120         "MouseWheelDown":  tcell.WheelDown,
121         "MouseWheelLeft":  tcell.WheelLeft,
122         "MouseWheelRight": tcell.WheelRight,
123 }
124
125 var bindingKeys = map[string]tcell.Key{
126         "Up":             tcell.KeyUp,
127         "Down":           tcell.KeyDown,
128         "Right":          tcell.KeyRight,
129         "Left":           tcell.KeyLeft,
130         "UpLeft":         tcell.KeyUpLeft,
131         "UpRight":        tcell.KeyUpRight,
132         "DownLeft":       tcell.KeyDownLeft,
133         "DownRight":      tcell.KeyDownRight,
134         "Center":         tcell.KeyCenter,
135         "PageUp":         tcell.KeyPgUp,
136         "PageDown":       tcell.KeyPgDn,
137         "Home":           tcell.KeyHome,
138         "End":            tcell.KeyEnd,
139         "Insert":         tcell.KeyInsert,
140         "Delete":         tcell.KeyDelete,
141         "Help":           tcell.KeyHelp,
142         "Exit":           tcell.KeyExit,
143         "Clear":          tcell.KeyClear,
144         "Cancel":         tcell.KeyCancel,
145         "Print":          tcell.KeyPrint,
146         "Pause":          tcell.KeyPause,
147         "Backtab":        tcell.KeyBacktab,
148         "F1":             tcell.KeyF1,
149         "F2":             tcell.KeyF2,
150         "F3":             tcell.KeyF3,
151         "F4":             tcell.KeyF4,
152         "F5":             tcell.KeyF5,
153         "F6":             tcell.KeyF6,
154         "F7":             tcell.KeyF7,
155         "F8":             tcell.KeyF8,
156         "F9":             tcell.KeyF9,
157         "F10":            tcell.KeyF10,
158         "F11":            tcell.KeyF11,
159         "F12":            tcell.KeyF12,
160         "F13":            tcell.KeyF13,
161         "F14":            tcell.KeyF14,
162         "F15":            tcell.KeyF15,
163         "F16":            tcell.KeyF16,
164         "F17":            tcell.KeyF17,
165         "F18":            tcell.KeyF18,
166         "F19":            tcell.KeyF19,
167         "F20":            tcell.KeyF20,
168         "F21":            tcell.KeyF21,
169         "F22":            tcell.KeyF22,
170         "F23":            tcell.KeyF23,
171         "F24":            tcell.KeyF24,
172         "F25":            tcell.KeyF25,
173         "F26":            tcell.KeyF26,
174         "F27":            tcell.KeyF27,
175         "F28":            tcell.KeyF28,
176         "F29":            tcell.KeyF29,
177         "F30":            tcell.KeyF30,
178         "F31":            tcell.KeyF31,
179         "F32":            tcell.KeyF32,
180         "F33":            tcell.KeyF33,
181         "F34":            tcell.KeyF34,
182         "F35":            tcell.KeyF35,
183         "F36":            tcell.KeyF36,
184         "F37":            tcell.KeyF37,
185         "F38":            tcell.KeyF38,
186         "F39":            tcell.KeyF39,
187         "F40":            tcell.KeyF40,
188         "F41":            tcell.KeyF41,
189         "F42":            tcell.KeyF42,
190         "F43":            tcell.KeyF43,
191         "F44":            tcell.KeyF44,
192         "F45":            tcell.KeyF45,
193         "F46":            tcell.KeyF46,
194         "F47":            tcell.KeyF47,
195         "F48":            tcell.KeyF48,
196         "F49":            tcell.KeyF49,
197         "F50":            tcell.KeyF50,
198         "F51":            tcell.KeyF51,
199         "F52":            tcell.KeyF52,
200         "F53":            tcell.KeyF53,
201         "F54":            tcell.KeyF54,
202         "F55":            tcell.KeyF55,
203         "F56":            tcell.KeyF56,
204         "F57":            tcell.KeyF57,
205         "F58":            tcell.KeyF58,
206         "F59":            tcell.KeyF59,
207         "F60":            tcell.KeyF60,
208         "F61":            tcell.KeyF61,
209         "F62":            tcell.KeyF62,
210         "F63":            tcell.KeyF63,
211         "F64":            tcell.KeyF64,
212         "CtrlSpace":      tcell.KeyCtrlSpace,
213         "CtrlA":          tcell.KeyCtrlA,
214         "CtrlB":          tcell.KeyCtrlB,
215         "CtrlC":          tcell.KeyCtrlC,
216         "CtrlD":          tcell.KeyCtrlD,
217         "CtrlE":          tcell.KeyCtrlE,
218         "CtrlF":          tcell.KeyCtrlF,
219         "CtrlG":          tcell.KeyCtrlG,
220         "CtrlH":          tcell.KeyCtrlH,
221         "CtrlI":          tcell.KeyCtrlI,
222         "CtrlJ":          tcell.KeyCtrlJ,
223         "CtrlK":          tcell.KeyCtrlK,
224         "CtrlL":          tcell.KeyCtrlL,
225         "CtrlM":          tcell.KeyCtrlM,
226         "CtrlN":          tcell.KeyCtrlN,
227         "CtrlO":          tcell.KeyCtrlO,
228         "CtrlP":          tcell.KeyCtrlP,
229         "CtrlQ":          tcell.KeyCtrlQ,
230         "CtrlR":          tcell.KeyCtrlR,
231         "CtrlS":          tcell.KeyCtrlS,
232         "CtrlT":          tcell.KeyCtrlT,
233         "CtrlU":          tcell.KeyCtrlU,
234         "CtrlV":          tcell.KeyCtrlV,
235         "CtrlW":          tcell.KeyCtrlW,
236         "CtrlX":          tcell.KeyCtrlX,
237         "CtrlY":          tcell.KeyCtrlY,
238         "CtrlZ":          tcell.KeyCtrlZ,
239         "CtrlLeftSq":     tcell.KeyCtrlLeftSq,
240         "CtrlBackslash":  tcell.KeyCtrlBackslash,
241         "CtrlRightSq":    tcell.KeyCtrlRightSq,
242         "CtrlCarat":      tcell.KeyCtrlCarat,
243         "CtrlUnderscore": tcell.KeyCtrlUnderscore,
244         "CtrlPageUp":     tcell.KeyCtrlPgUp,
245         "CtrlPageDown":   tcell.KeyCtrlPgDn,
246         "Tab":            tcell.KeyTab,
247         "Esc":            tcell.KeyEsc,
248         "Escape":         tcell.KeyEscape,
249         "Enter":          tcell.KeyEnter,
250         "Backspace":      tcell.KeyBackspace2,
251
252         // I renamed these keys to PageUp and PageDown but I don't want to break someone's keybindings
253         "PgUp":   tcell.KeyPgUp,
254         "PgDown": tcell.KeyPgDn,
255 }
256
257 // The Key struct holds the data for a keypress (keycode + modifiers)
258 type Key struct {
259         keyCode   tcell.Key
260         modifiers tcell.ModMask
261         buttons   tcell.ButtonMask
262         r         rune
263 }
264
265 // InitBindings initializes the keybindings for micro
266 func InitBindings() {
267         bindings = make(map[Key][]func(*View, bool) bool)
268         mouseBindings = make(map[Key][]func(*View, bool, *tcell.EventMouse) bool)
269
270         var parsed map[string]string
271         defaults := DefaultBindings()
272
273         filename := configDir + "/bindings.json"
274         if _, e := os.Stat(filename); e == nil {
275                 input, err := ioutil.ReadFile(filename)
276                 if err != nil {
277                         TermMessage("Error reading bindings.json file: " + err.Error())
278                         return
279                 }
280
281                 err = json5.Unmarshal(input, &parsed)
282                 if err != nil {
283                         TermMessage("Error reading bindings.json:", err.Error())
284                 }
285         }
286
287         parseBindings(defaults)
288         parseBindings(parsed)
289 }
290
291 func parseBindings(userBindings map[string]string) {
292         for k, v := range userBindings {
293                 BindKey(k, v)
294         }
295 }
296
297 // findKey will find binding Key 'b' using string 'k'
298 func findKey(k string) (b Key, ok bool) {
299         modifiers := tcell.ModNone
300
301         // First, we'll strip off all the modifiers in the name and add them to the
302         // ModMask
303 modSearch:
304         for {
305                 switch {
306                 case strings.HasPrefix(k, "-"):
307                         // We optionally support dashes between modifiers
308                         k = k[1:]
309                 case strings.HasPrefix(k, "Ctrl") && k != "CtrlH":
310                         // CtrlH technically does not have a 'Ctrl' modifier because it is really backspace
311                         k = k[4:]
312                         modifiers |= tcell.ModCtrl
313                 case strings.HasPrefix(k, "Alt"):
314                         k = k[3:]
315                         modifiers |= tcell.ModAlt
316                 case strings.HasPrefix(k, "Shift"):
317                         k = k[5:]
318                         modifiers |= tcell.ModShift
319                 default:
320                         break modSearch
321                 }
322         }
323
324         // Control is handled specially, since some character codes in bindingKeys
325         // are different when Control is depressed. We should check for Control keys
326         // first.
327         if modifiers&tcell.ModCtrl != 0 {
328                 // see if the key is in bindingKeys with the Ctrl prefix.
329                 if code, ok := bindingKeys["Ctrl"+k]; ok {
330                         // It is, we're done.
331                         return Key{
332                                 keyCode:   code,
333                                 modifiers: modifiers,
334                                 buttons:   -1,
335                                 r:         0,
336                         }, true
337                 }
338         }
339
340         // See if we can find the key in bindingKeys
341         if code, ok := bindingKeys[k]; ok {
342                 return Key{
343                         keyCode:   code,
344                         modifiers: modifiers,
345                         buttons:   -1,
346                         r:         0,
347                 }, true
348         }
349
350         // See if we can find the key in bindingMouse
351         if code, ok := bindingMouse[k]; ok {
352                 return Key{
353                         modifiers: modifiers,
354                         buttons:   code,
355                         r:         0,
356                 }, true
357         }
358
359         // If we were given one character, then we've got a rune.
360         if len(k) == 1 {
361                 return Key{
362                         keyCode:   tcell.KeyRune,
363                         modifiers: modifiers,
364                         buttons:   -1,
365                         r:         rune(k[0]),
366                 }, true
367         }
368
369         // We don't know what happened.
370         return Key{buttons: -1}, false
371 }
372
373 // findAction will find 'action' using string 'v'
374 func findAction(v string) (action func(*View, bool) bool) {
375         action, ok := bindingActions[v]
376         if !ok {
377                 // If the user seems to be binding a function that doesn't exist
378                 // We hope that it's a lua function that exists and bind it to that
379                 action = LuaFunctionBinding(v)
380         }
381         return action
382 }
383
384 func findMouseAction(v string) func(*View, bool, *tcell.EventMouse) bool {
385         action, ok := mouseBindingActions[v]
386         if !ok {
387                 // If the user seems to be binding a function that doesn't exist
388                 // We hope that it's a lua function that exists and bind it to that
389                 action = LuaFunctionMouseBinding(v)
390         }
391         return action
392 }
393
394 // BindKey takes a key and an action and binds the two together
395 func BindKey(k, v string) {
396         key, ok := findKey(k)
397         if !ok {
398                 TermMessage("Unknown keybinding: " + k)
399                 return
400         }
401         if v == "ToggleHelp" {
402                 helpBinding = k
403         }
404         if v == "ToggleKeyMenu" {
405                 kmenuBinding = k
406         }
407         if helpBinding == k && v != "ToggleHelp" {
408                 helpBinding = ""
409         }
410         if kmenuBinding == k && v != "ToggleKeyMenu" {
411                 kmenuBinding = ""
412         }
413
414         actionNames := strings.Split(v, ",")
415         if actionNames[0] == "UnbindKey" {
416                 delete(bindings, key)
417                 delete(mouseBindings, key)
418                 if len(actionNames) == 1 {
419                         return
420                 }
421                 actionNames = append(actionNames[:0], actionNames[1:]...)
422         }
423         actions := make([]func(*View, bool) bool, 0, len(actionNames))
424         mouseActions := make([]func(*View, bool, *tcell.EventMouse) bool, 0, len(actionNames))
425         for _, actionName := range actionNames {
426                 if strings.HasPrefix(actionName, "Mouse") {
427                         mouseActions = append(mouseActions, findMouseAction(actionName))
428                 } else {
429                         actions = append(actions, findAction(actionName))
430                 }
431         }
432
433         if len(actions) > 0 {
434                 // Can't have a binding be both mouse and normal
435                 delete(mouseBindings, key)
436                 bindings[key] = actions
437         } else if len(mouseActions) > 0 {
438                 // Can't have a binding be both mouse and normal
439                 delete(bindings, key)
440                 mouseBindings[key] = mouseActions
441         }
442 }
443
444 // DefaultBindings returns a map containing micro's default keybindings
445 func DefaultBindings() map[string]string {
446         return map[string]string{
447                 "Up":             "CursorUp",
448                 "Down":           "CursorDown",
449                 "Right":          "CursorRight",
450                 "Left":           "CursorLeft",
451                 "ShiftUp":        "SelectUp",
452                 "ShiftDown":      "SelectDown",
453                 "ShiftLeft":      "SelectLeft",
454                 "ShiftRight":     "SelectRight",
455                 "AltLeft":        "WordLeft",
456                 "AltRight":       "WordRight",
457                 "AltUp":          "MoveLinesUp",
458                 "AltDown":        "MoveLinesDown",
459                 "AltShiftRight":  "SelectWordRight",
460                 "AltShiftLeft":   "SelectWordLeft",
461                 "CtrlLeft":       "StartOfLine",
462                 "CtrlRight":      "EndOfLine",
463                 "CtrlShiftLeft":  "SelectToStartOfLine",
464                 "ShiftHome":      "SelectToStartOfLine",
465                 "CtrlShiftRight": "SelectToEndOfLine",
466                 "ShiftEnd":       "SelectToEndOfLine",
467                 "CtrlUp":         "CursorStart",
468                 "CtrlDown":       "CursorEnd",
469                 "CtrlShiftUp":    "SelectToStart",
470                 "CtrlShiftDown":  "SelectToEnd",
471                 "Alt-{":          "ParagraphPrevious",
472                 "Alt-}":          "ParagraphNext",
473                 "Enter":          "InsertNewline",
474                 "CtrlH":          "Backspace",
475                 "Backspace":      "Backspace",
476                 "Alt-CtrlH":      "DeleteWordLeft",
477                 "Alt-Backspace":  "DeleteWordLeft",
478                 "Tab":            "IndentSelection,InsertTab",
479                 "Backtab":        "OutdentSelection,OutdentLine",
480                 "CtrlO":          "OpenFile",
481                 "CtrlS":          "Save",
482                 "CtrlF":          "Find",
483                 "CtrlN":          "FindNext",
484                 "CtrlP":          "FindPrevious",
485                 "CtrlZ":          "Undo",
486                 "CtrlY":          "Redo",
487                 "CtrlC":          "Copy",
488                 "CtrlX":          "Cut",
489                 "CtrlK":          "CutLine",
490                 "CtrlD":          "DuplicateLine",
491                 "CtrlV":          "Paste",
492                 "CtrlA":          "SelectAll",
493                 "CtrlT":          "AddTab",
494                 "Alt,":           "PreviousTab",
495                 "Alt.":           "NextTab",
496                 "Home":           "StartOfLine",
497                 "End":            "EndOfLine",
498                 "CtrlHome":       "CursorStart",
499                 "CtrlEnd":        "CursorEnd",
500                 "PageUp":         "CursorPageUp",
501                 "PageDown":       "CursorPageDown",
502                 "CtrlPageUp":     "PreviousTab",
503                 "CtrlPageDown":   "NextTab",
504                 "CtrlG":          "ToggleHelp",
505                 "Alt-g":          "ToggleKeyMenu",
506                 "CtrlR":          "ToggleRuler",
507                 "CtrlL":          "JumpLine",
508                 "Delete":         "Delete",
509                 "CtrlB":          "ShellMode",
510                 "CtrlQ":          "Quit",
511                 "CtrlE":          "CommandMode",
512                 "CtrlW":          "NextSplit",
513                 "CtrlU":          "ToggleMacro",
514                 "CtrlJ":          "PlayMacro",
515
516                 // Emacs-style keybindings
517                 "Alt-f": "WordRight",
518                 "Alt-b": "WordLeft",
519                 "Alt-a": "StartOfLine",
520                 "Alt-e": "EndOfLine",
521                 // "Alt-p": "CursorUp",
522                 // "Alt-n": "CursorDown",
523
524                 // Integration with file managers
525                 "F2":  "Save",
526                 "F3":  "Find",
527                 "F4":  "Quit",
528                 "F7":  "Find",
529                 "F10": "Quit",
530                 "Esc": "Escape",
531
532                 // Mouse bindings
533                 "MouseWheelUp":   "ScrollUp",
534                 "MouseWheelDown": "ScrollDown",
535                 "MouseLeft":      "MousePress",
536                 "MouseMiddle":    "PastePrimary",
537                 "Ctrl-MouseLeft": "MouseMultiCursor",
538
539                 "Alt-n": "SpawnMultiCursor",
540                 "Alt-p": "RemoveMultiCursor",
541                 "Alt-c": "RemoveAllMultiCursors",
542                 "Alt-x": "SkipMultiCursor",
543         }
544 }