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