]> git.lizzy.rs Git - micro.git/blob - cmd/micro/bindings.go
Add ability to add cursors with Ctrl-MouseLeft
[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         "Tab":            tcell.KeyTab,
241         "Esc":            tcell.KeyEsc,
242         "Escape":         tcell.KeyEscape,
243         "Enter":          tcell.KeyEnter,
244         "Backspace":      tcell.KeyBackspace2,
245
246         // I renamed these keys to PageUp and PageDown but I don't want to break someone's keybindings
247         "PgUp":   tcell.KeyPgUp,
248         "PgDown": tcell.KeyPgDn,
249 }
250
251 // The Key struct holds the data for a keypress (keycode + modifiers)
252 type Key struct {
253         keyCode   tcell.Key
254         modifiers tcell.ModMask
255         buttons   tcell.ButtonMask
256         r         rune
257 }
258
259 // InitBindings initializes the keybindings for micro
260 func InitBindings() {
261         bindings = make(map[Key][]func(*View, bool) bool)
262         mouseBindings = make(map[Key][]func(*View, bool, *tcell.EventMouse) bool)
263
264         var parsed map[string]string
265         defaults := DefaultBindings()
266
267         filename := configDir + "/bindings.json"
268         if _, e := os.Stat(filename); e == nil {
269                 input, err := ioutil.ReadFile(filename)
270                 if err != nil {
271                         TermMessage("Error reading bindings.json file: " + err.Error())
272                         return
273                 }
274
275                 err = json5.Unmarshal(input, &parsed)
276                 if err != nil {
277                         TermMessage("Error reading bindings.json:", err.Error())
278                 }
279         }
280
281         parseBindings(defaults)
282         parseBindings(parsed)
283 }
284
285 func parseBindings(userBindings map[string]string) {
286         for k, v := range userBindings {
287                 BindKey(k, v)
288         }
289 }
290
291 // findKey will find binding Key 'b' using string 'k'
292 func findKey(k string) (b Key, ok bool) {
293         modifiers := tcell.ModNone
294
295         // First, we'll strip off all the modifiers in the name and add them to the
296         // ModMask
297 modSearch:
298         for {
299                 switch {
300                 case strings.HasPrefix(k, "-"):
301                         // We optionally support dashes between modifiers
302                         k = k[1:]
303                 case strings.HasPrefix(k, "Ctrl") && k != "CtrlH":
304                         // CtrlH technically does not have a 'Ctrl' modifier because it is really backspace
305                         k = k[4:]
306                         modifiers |= tcell.ModCtrl
307                 case strings.HasPrefix(k, "Alt"):
308                         k = k[3:]
309                         modifiers |= tcell.ModAlt
310                 case strings.HasPrefix(k, "Shift"):
311                         k = k[5:]
312                         modifiers |= tcell.ModShift
313                 default:
314                         break modSearch
315                 }
316         }
317
318         // Control is handled specially, since some character codes in bindingKeys
319         // are different when Control is depressed. We should check for Control keys
320         // first.
321         if modifiers&tcell.ModCtrl != 0 {
322                 // see if the key is in bindingKeys with the Ctrl prefix.
323                 if code, ok := bindingKeys["Ctrl"+k]; ok {
324                         // It is, we're done.
325                         return Key{
326                                 keyCode:   code,
327                                 modifiers: modifiers,
328                                 buttons:   -1,
329                                 r:         0,
330                         }, true
331                 }
332         }
333
334         // See if we can find the key in bindingKeys
335         if code, ok := bindingKeys[k]; ok {
336                 return Key{
337                         keyCode:   code,
338                         modifiers: modifiers,
339                         buttons:   -1,
340                         r:         0,
341                 }, true
342         }
343
344         // See if we can find the key in bindingMouse
345         if code, ok := bindingMouse[k]; ok {
346                 return Key{
347                         modifiers: modifiers,
348                         buttons:   code,
349                         r:         0,
350                 }, true
351         }
352
353         // If we were given one character, then we've got a rune.
354         if len(k) == 1 {
355                 return Key{
356                         keyCode:   tcell.KeyRune,
357                         modifiers: modifiers,
358                         buttons:   -1,
359                         r:         rune(k[0]),
360                 }, true
361         }
362
363         // We don't know what happened.
364         return Key{buttons: -1}, false
365 }
366
367 // findAction will find 'action' using string 'v'
368 func findAction(v string) (action func(*View, bool) bool) {
369         action, ok := bindingActions[v]
370         if !ok {
371                 // If the user seems to be binding a function that doesn't exist
372                 // We hope that it's a lua function that exists and bind it to that
373                 action = LuaFunctionBinding(v)
374         }
375         return action
376 }
377
378 func findMouseAction(v string) func(*View, bool, *tcell.EventMouse) bool {
379         action, ok := mouseBindingActions[v]
380         if !ok {
381                 // If the user seems to be binding a function that doesn't exist
382                 // We hope that it's a lua function that exists and bind it to that
383                 action = LuaFunctionMouseBinding(v)
384         }
385         return action
386 }
387
388 // BindKey takes a key and an action and binds the two together
389 func BindKey(k, v string) {
390         key, ok := findKey(k)
391         if !ok {
392                 TermMessage("Unknown keybinding: " + k)
393                 return
394         }
395         if v == "ToggleHelp" {
396                 helpBinding = k
397         }
398         if helpBinding == k && v != "ToggleHelp" {
399                 helpBinding = ""
400         }
401
402         actionNames := strings.Split(v, ",")
403         if actionNames[0] == "UnbindKey" {
404                 delete(bindings, key)
405                 delete(mouseBindings, key)
406                 if len(actionNames) == 1 {
407                         return
408                 }
409                 actionNames = append(actionNames[:0], actionNames[1:]...)
410         }
411         actions := make([]func(*View, bool) bool, 0, len(actionNames))
412         mouseActions := make([]func(*View, bool, *tcell.EventMouse) bool, 0, len(actionNames))
413         for _, actionName := range actionNames {
414                 if strings.HasPrefix(actionName, "Mouse") {
415                         mouseActions = append(mouseActions, findMouseAction(actionName))
416                 } else {
417                         actions = append(actions, findAction(actionName))
418                 }
419         }
420
421         if len(actions) > 0 {
422                 // Can't have a binding be both mouse and normal
423                 delete(mouseBindings, key)
424                 bindings[key] = actions
425         } else if len(mouseActions) > 0 {
426                 // Can't have a binding be both mouse and normal
427                 delete(bindings, key)
428                 mouseBindings[key] = mouseActions
429         }
430 }
431
432 // DefaultBindings returns a map containing micro's default keybindings
433 func DefaultBindings() map[string]string {
434         return map[string]string{
435                 "Up":             "CursorUp",
436                 "Down":           "CursorDown",
437                 "Right":          "CursorRight",
438                 "Left":           "CursorLeft",
439                 "ShiftUp":        "SelectUp",
440                 "ShiftDown":      "SelectDown",
441                 "ShiftLeft":      "SelectLeft",
442                 "ShiftRight":     "SelectRight",
443                 "AltLeft":        "WordLeft",
444                 "AltRight":       "WordRight",
445                 "AltUp":          "MoveLinesUp",
446                 "AltDown":        "MoveLinesDown",
447                 "AltShiftRight":  "SelectWordRight",
448                 "AltShiftLeft":   "SelectWordLeft",
449                 "CtrlLeft":       "StartOfLine",
450                 "CtrlRight":      "EndOfLine",
451                 "CtrlShiftLeft":  "SelectToStartOfLine",
452                 "ShiftHome":      "SelectToStartOfLine",
453                 "CtrlShiftRight": "SelectToEndOfLine",
454                 "ShiftEnd":       "SelectToEndOfLine",
455                 "CtrlUp":         "CursorStart",
456                 "CtrlDown":       "CursorEnd",
457                 "CtrlShiftUp":    "SelectToStart",
458                 "CtrlShiftDown":  "SelectToEnd",
459                 "Enter":          "InsertNewline",
460                 "CtrlH":          "Backspace",
461                 "Backspace":      "Backspace",
462                 "Alt-CtrlH":      "DeleteWordLeft",
463                 "Alt-Backspace":  "DeleteWordLeft",
464                 "Tab":            "IndentSelection,InsertTab",
465                 "Backtab":        "OutdentSelection,OutdentLine",
466                 "CtrlO":          "OpenFile",
467                 "CtrlS":          "Save",
468                 "CtrlF":          "Find",
469                 "CtrlN":          "FindNext",
470                 "CtrlP":          "FindPrevious",
471                 "CtrlZ":          "Undo",
472                 "CtrlY":          "Redo",
473                 "CtrlC":          "Copy",
474                 "CtrlX":          "Cut",
475                 "CtrlK":          "CutLine",
476                 "CtrlD":          "DuplicateLine",
477                 "CtrlV":          "Paste",
478                 "CtrlA":          "SelectAll",
479                 "CtrlT":          "AddTab",
480                 "Alt,":           "PreviousTab",
481                 "Alt.":           "NextTab",
482                 "Home":           "StartOfLine",
483                 "End":            "EndOfLine",
484                 "CtrlHome":       "CursorStart",
485                 "CtrlEnd":        "CursorEnd",
486                 "PageUp":         "CursorPageUp",
487                 "PageDown":       "CursorPageDown",
488                 "CtrlG":          "ToggleHelp",
489                 "CtrlR":          "ToggleRuler",
490                 "CtrlL":          "JumpLine",
491                 "Delete":         "Delete",
492                 "CtrlB":          "ShellMode",
493                 "CtrlQ":          "Quit",
494                 "CtrlE":          "CommandMode",
495                 "CtrlW":          "NextSplit",
496                 "CtrlU":          "ToggleMacro",
497                 "CtrlJ":          "PlayMacro",
498
499                 // Emacs-style keybindings
500                 "Alt-f": "WordRight",
501                 "Alt-b": "WordLeft",
502                 "Alt-a": "StartOfLine",
503                 "Alt-e": "EndOfLine",
504                 // "Alt-p": "CursorUp",
505                 // "Alt-n": "CursorDown",
506
507                 // Integration with file managers
508                 "F1":  "ToggleHelp",
509                 "F2":  "Save",
510                 "F3":  "Find",
511                 "F4":  "Quit",
512                 "F7":  "Find",
513                 "F10": "Quit",
514                 "Esc": "Escape",
515
516                 // Mouse bindings
517                 "MouseWheelUp":   "ScrollUp",
518                 "MouseWheelDown": "ScrollDown",
519                 "MouseLeft":      "MousePress",
520                 "MouseMiddle":    "PastePrimary",
521                 "Ctrl-MouseLeft": "MouseMultiCursor",
522
523                 "Alt-n": "SpawnMultiCursor",
524                 "Alt-p": "RemoveMultiCursor",
525                 "Alt-c": "RemoveAllMultiCursors",
526                 "Alt-x": "SkipMultiCursor",
527         }
528 }