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