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