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