input_stack: wrap an array instead of inherit from Array
[conkeror.git] / modules / keymap.js
blob7bbdea0939ab2b8fd09a5b65e3deef419dd95991
1 /**
2  * (C) Copyright 2004-2007 Shawn Betts
3  * (C) Copyright 2007-2010 John J. Foerch
4  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
5  *
6  * Use, modification, and distribution are subject to the terms specified in the
7  * COPYING file.
8 **/
10 in_module(null);
12 /* Generate vk name table  */
13 var keycode_to_vk_name = [];
14 var vk_name_to_keycode = {};
15 let (KeyEvent = Ci.nsIDOMKeyEvent,
16      prefix = "DOM_VK_") {
17     for (var i in KeyEvent) {
18         /* Check if this is a key binding */
19         if (i.substr(0, prefix.length) == prefix) {
20             let name = i.substr(prefix.length).toLowerCase();
21             let code = KeyEvent[i];
22             keycode_to_vk_name[code] = name;
23             vk_name_to_keycode[name] = code;
24         }
25     }
30  * Modifiers
31  */
33 function modifier (in_event_p, set_in_event) {
34     this.in_event_p = in_event_p;
35     this.set_in_event = set_in_event;
38 var modifiers = {
39     A: new modifier(function (event) { return event.altKey; },
40                     function (event) { event.altKey = true; }),
41     C: new modifier(function (event) { return event.ctrlKey; },
42                     function (event) { event.ctrlKey = true; }),
43     M: new modifier(function (event) { return event.metaKey; },
44                     function (event) { event.metaKey = true; }),
45     S: new modifier(function (event) {
46                         if (event.shiftKey) {
47                             var name;
48                             if (event.keyCode)
49                                 name = keycode_to_vk_name[event.keyCode];
50                             return ((name && name.length > 1) ||
51                                     (event.charCode == 32) ||
52                                     (event.button != null));
53                         }
54                         return false;
55                     },
56                     function (event) { event.shiftKey = true; })
58 var modifier_order = ['C', 'M', 'S'];
60 // check the platform and guess whether we should treat Alt as Meta
61 if (get_os() == 'Darwin') {
62     // In OS X, alt is a shift-like modifier, in that we
63     // only care about it for non-character events.
64     modifiers.A = new modifier(
65         function (event) {
66             if (event.altKey) {
67                 var name;
68                 if (event.keyCode)
69                     name = keycode_to_vk_name[event.keyCode];
70                 return ((name && name.length > 1) ||
71                         (event.charCode == 32) ||
72                         (event.button != null));
73             }
74             return false;
75         },
76         function (event) { event.altKey = true; });
77     modifier_order = ['C', 'M', 'A', 'S'];
78 } else {
79     modifiers.M = modifiers.A;
85  * Combos
86  */
88 function format_key_combo (event) {
89     var combo = '';
90     for each (var M in modifier_order) {
91         if (modifiers[M].in_event_p(event) ||
92             (event.sticky_modifiers &&
93              event.sticky_modifiers.indexOf(M) != -1))
94         {
95             combo += (M + '-');
96         }
97     }
98     if (event.charCode) {
99         if (event.charCode == 32)
100             combo += 'space';
101         else
102             combo += String.fromCharCode(event.charCode);
103     } else if (event.keyCode) {
104         combo += keycode_to_vk_name[event.keyCode];
105     } else if (event.button != null) {
106         combo += "mouse" + (event.button + 1);
107     }
108     return combo;
111 function unformat_key_combo (combo) {
112     var event = {
113         keyCode: 0,
114         charCode: 0,
115         altKey: false,
116         ctrlKey: false,
117         metaKey: false,
118         shiftKey: false
119     };
120     var M;
121     var i = 0;
122     var len = combo.length - 2;
123     var res;
124     while (i < len && combo[i+1] == '-') {
125         M = combo[i];
126         modifiers[M].set_in_event(event);
127         i+=2;
128     }
129     var key = combo.substring(i);
130     if (key.length == 1)
131         event.charCode = key.charCodeAt(0);
132     else if (key == 'space')
133         event.charCode = 32;
134     else if (vk_name_to_keycode[key])
135         event.keyCode = vk_name_to_keycode[key];
136     else if (key.substring(0, 5) == 'mouse')
137         event.button = parseInt(key.substring(5));
138     return event;
144  * Keymap datatype
145  */
147 define_keywords("$parent", "$help", "$name", "$anonymous",
148                 "$display_name", "$notify");
149 function keymap () {
150     keywords(arguments);
151     this.parent = arguments.$parent;
152     this.bindings = {};
153     this.predicate_bindings = [];
154     this.fallthrough = [];
155     this.help = arguments.$help;
156     this.name = arguments.$name;
157     this.display_name = arguments.$display_name;
158     this.notify = arguments.$notify;
159     this.anonymous = arguments.$anonymous;
162 function define_keymap (name) {
163     keywords(arguments);
164     this[name] = new keymap($name = name, forward_keywords(arguments));
170  * Key Match Predicates.
171  */
173 function define_key_match_predicate (name, description, predicate) {
174     conkeror[name] = predicate;
175     conkeror[name].name = name;
176     conkeror[name].description = description;
177     return conkeror[name];
180 define_key_match_predicate('match_any_key', 'any key',
181     function (event) true);
183 // should be renamed to match_any_unmodified_character
184 define_key_match_predicate('match_any_unmodified_character', 'any unmodified character',
185     function (event) {
186         // this predicate can be used for both keypress and keydown
187         // fallthroughs.
188         try {
189             return ((event.type == 'keypress' && event.charCode)
190                     || event.keyCode > 31)
191                 && !modifiers.A.in_event_p(event)
192                 && !event.metaKey
193                 && !event.ctrlKey
194                 && !event.sticky_modifiers;
195         } catch (e) { return false; }
196     });
198 define_key_match_predicate('match_checkbox_keys', 'checkbox keys',
199     function (event) {
200         return event.keyCode == 32
201             && !event.shiftKey
202             && !event.metaKey
203             && !event.altKey
204             && !event.ctrlKey;
205         //XXX: keycode fallthroughs don't support sticky modifiers
206     });
208 define_key_match_predicate('match_text_keys', 'text editing keys',
209     function (event) {
210         return ((event.type == 'keypress' && event.charCode)
211                 || event.keyCode == 13 || event.keyCode > 31)
212             && !event.ctrlKey
213             && !event.metaKey
214             && !modifiers.A.in_event_p(event);
215         //XXX: keycode fallthroughs don't support sticky modifiers
216     });
218 define_key_match_predicate('match_not_escape_key', 'any key but escape',
219     function (event) {
220         return event.keyCode != 27 ||
221              event.shiftKey ||
222              event.altKey ||
223              event.metaKey || // M-escape can also leave this mode, so we
224                               // need to use an accurate determination of
225                               // whether the "M" modifier was pressed,
226                               // which is not necessarily the same as
227                               // event.metaKey.
228              event.ctrlKey;
229     });
233  */
235 function format_key_spec (key) {
236     if (key instanceof Function) {
237         if (key.description)
238             return "<"+key.description+">";
239         if (key.name)
240             return "<"+key.name+">";
241         return "<anonymous match function>";
242     }
243     return key;
246 function format_binding_sequence (seq) {
247     return seq.map(function (x) {
248             return format_key_spec(x.key);
249         }).join(" ");
253 function keymap_lookup (keymaps, combo, event) {
254     var i = keymaps.length - 1;
255     if (i < 0)
256         return null;
257     var kmap = keymaps[i];
258     var new_kmaps;
259     while (true) {
260         var bindings = kmap.bindings;
261         var bind = bindings[combo];
262         if (new_kmaps) {
263             if (bind) {
264                 if (bind.keymap)
265                     new_kmaps.unshift(bind.keymap);
266                 else
267                     return new_kmaps;
268             }
269         } else if (bind) {
270             if (bind.keymap)
271                 new_kmaps = [bind.keymap];
272             else
273                 return bind;
274         } else {
275             var pred_binds = kmap.predicate_bindings;
276             for (var j = 0, pblen = pred_binds.length; j < pblen; ++j) {
277                 bind = pred_binds[j];
278                 if (bind.key(event))
279                     return bind;
280             }
281         }
282         if (kmap.parent)
283             kmap = kmap.parent;
284         else if (i > 0)
285             kmap = keymaps[--i];
286         else if (new_kmaps)
287             return new_kmaps
288         else
289             return null;
290     }
294 function keymap_lookup_fallthrough (keymap, event) {
295     var predicates = keymap.fallthrough;
296     for (var i = 0, plen = predicates.length; i < plen; ++i) {
297         if (predicates[i](event))
298             return true;
299     }
300     return false;
304 function for_each_key_binding (keymaps, callback) {
305     var binding_sequence = [];
306     var in_keymaps = [];
307     function helper (keymap) {
308         if (in_keymaps.indexOf(keymap) >= 0)
309             return;
310         in_keymaps.push(keymap);
311         var binding;
312         for each (binding in keymap.bindings) {
313             binding_sequence.push(binding);
314             callback(binding_sequence);
315             if (binding.keymap)
316                 helper(binding.keymap);
317             binding_sequence.pop();
318         }
319         for each (binding in keymap.predicate_bindings) {
320             binding_sequence.push(binding);
321             callback(binding_sequence);
322             if (binding.keymap)
323                 helper(binding.keymap);
324             binding_sequence.pop();
325         }
326         in_keymaps.pop();
327     }
328     //outer loop is to go down the parent-chain of keymaps
329     var i = keymaps.length - 1;
330     var keymap = keymaps[i];
331     while (true) {
332         helper(keymap);
333         if (keymap.parent)
334             keymap = keymap.parent;
335         else if (i > 0)
336             keymap = keymaps[--i];
337         else
338             break;
339     }
343 function keymap_lookup_command (keymaps, command) {
344     var list = [];
345     for_each_key_binding(keymaps, function (bind_seq) {
346             var bind = bind_seq[bind_seq.length - 1];
347             if (bind.command == command)
348                 list.push(format_binding_sequence(bind_seq));
349         });
350     return list;
359  * $fallthrough, $repeat and $browser_object are as for define_key.
361  * ref is the source code reference of the call to define_key.
363  * kmap is the keymap in which the binding is to be defined.
365  * seq is the key sequence being bound.  it may be necessary
366  * to auto-generate new keymaps to accomodate the key sequence.
368  * only one of new_command and new_keymap will be given.
369  * the one that is given is the thing being bound to.
370  */
371 define_keywords("$fallthrough", "$repeat", "$browser_object");
372 function define_key_internal (ref, kmap, seq, new_command, new_keymap) {
373     keywords(arguments);
374     var args = arguments;
375     var last_in_sequence; // flag to indicate the final key combo in the sequence.
376     var key; // current key combo as we iterate through the sequence.
377     var undefine_key = (new_command == null) &&
378         (new_keymap == null) &&
379         (! args.$fallthrough);
381     /* Replace `bind' with the binding specified by (cmd, fallthrough) */
382     function replace_binding (bind) {
383         if (last_in_sequence) {
384             bind.command = new_command;
385             bind.keymap = new_keymap;
386             bind.fallthrough = args.$fallthrough;
387             bind.source_code_reference = ref;
388             bind.repeat = args.$repeat;
389             bind.browser_object = args.$browser_object;
390         } else {
391             if (!bind.keymap)
392                 throw new Error("Key sequence has a non-keymap in prefix");
393             kmap = bind.keymap;
394         }
395     }
397     function make_binding () {
398         if (last_in_sequence) {
399             return { key: key,
400                      fallthrough: args.$fallthrough,
401                      command: new_command,
402                      keymap: new_keymap,
403                      source_code_reference: ref,
404                      repeat: args.$repeat,
405                      browser_object: args.$browser_object,
406                      bound_in: kmap };
407         } else {
408             let old_kmap = kmap;
409             kmap = new keymap($anonymous,
410                               $name = old_kmap.name + " " + format_key_spec(key));
411             kmap.bound_in = old_kmap;
412             return { key: key,
413                      keymap: kmap,
414                      source_code_reference: ref,
415                      bound_in: old_kmap };
416         }
417     }
419 sequence:
420     for (var i = 0, slen = seq.length; i < slen; ++i) {
421         key = seq[i];
422         last_in_sequence = (i == slen - 1);
424         if (typeof key == "function") { // it's a match predicate
425             // Check if the binding is already present in the keymap
426             var pred_binds = kmap.predicate_bindings;
427             for (var j = 0, pblen = pred_binds.length; j < pblen; j++) {
428                 if (pred_binds[j].key == key) {
429                     if (last_in_sequence && undefine_key)
430                         pred_binds.splice(j, 1);
431                     else
432                         replace_binding(pred_binds[j]);
433                     continue sequence;
434                 }
435             }
436             if (! undefine_key)
437                 pred_binds.push(make_binding());
438         } else {
439             // Check if the binding is already present in the keymap
440             var bindings = kmap.bindings;
441             var binding = bindings[key];
442             if (binding) {
443                 if (last_in_sequence && undefine_key)
444                     delete bindings[key];
445                 else
446                     replace_binding(binding);
447                 continue sequence;
448             }
449             if (! undefine_key)
450                 bindings[key] = make_binding();
451         }
452     }
456  * bind SEQ to a keymap or command CMD in keymap KMAP.
458  *   If CMD is the special value `fallthrough', it will be bound as a
459  * fallthrough key.
461  * keywords:
463  *  $fallthrough: specifies that the keypress event will fall through
464  *      to gecko.  Note, by this method, only keypress will fall through.
465  *      Keyup and keydown will still be blocked.
467  *  $repeat: (command name) shortcut command to call if a prefix
468  *      command key is pressed twice in a row.
470  *  $browser_object: (browser object) Override the default
471  *      browser-object for the command.
472  */
473 define_keywords("$fallthrough", "$repeat", "$browser_object");
474 function define_key (kmap, seq, cmd) {
475     keywords(arguments);
476     var orig_seq = seq;
477     try {
478         var ref = get_caller_source_code_reference();
480         if (typeof seq == "string" && seq.length > 1)
481             seq = seq.split(" ");
483         if (!(typeof seq == "object") || !(seq instanceof Array))
484             seq = [seq];
486         // normalize the order of modifiers in key combos
487         seq = seq.map(
488             function (k) {
489                 if (typeof(k) == "string")
490                     return format_key_combo(unformat_key_combo(k));
491                 else
492                     return k;
493             });
495         var new_command = null;
496         var new_keymap = null;
497         if (typeof cmd == "string" || typeof cmd == "function")
498             new_command = cmd;
499         else if (cmd instanceof keymap)
500             new_keymap = cmd;
501         else if (cmd != null)
502             throw new Error("Invalid `cmd' argument: " + cmd);
504         define_key_internal(ref, kmap, seq, new_command, new_keymap,
505                             forward_keywords(arguments));
507     } catch (e if (typeof e == "string")) {
508         dumpln("Warning: Error occurred while binding sequence: " + orig_seq);
509         dumpln(e);
510     }
514 function undefine_key (kmap, seq) {
515     define_key(kmap, seq);
520  * define_fallthrough
522  *   Takes a keymap and a predicate on an event.  Fallthroughs defined by
523  * these means will cause all three of keydown, keypress, and keyup to
524  * fall through to gecko, whereas those defined by the $fallthrough
525  * keyword to define_key only affect keypress events.
527  *   The limitations of this method are that only the keyCode is available
528  * to the predicate, not the charCode, and keymap inheritance is not
529  * available for these "bindings".
530  */
531 function define_fallthrough (keymap, predicate) {
532     keymap.fallthrough.push(predicate);
537  * Minibuffer Read Key Binding
538  */
540 define_keymap("key_binding_reader_keymap");
541 define_key(key_binding_reader_keymap, match_any_key, "read-key-binding-key");
543 define_keywords("$keymap");
544 function key_binding_reader (minibuffer, continuation) {
545     keywords(arguments, $prompt = "Describe key:");
546     minibuffer_input_state.call(this, minibuffer, key_binding_reader_keymap, arguments.$prompt);
547     this.continuation = continuation;
548     if (arguments.$keymap)
549         this.target_keymap = arguments.$keymap;
550     else
551         this.target_keymap = get_current_keymaps(this.minibuffer.window).slice();
552     this.key_sequence = [];
554 key_binding_reader.prototype = {
555     constructor: key_binding_reader,
556     __proto__: minibuffer_input_state.prototype,
557     destroy: function () {
558         if (this.continuation)
559             this.continuation.throw(abort());
560         minibuffer_input_state.prototype.destroy.call(this);
561     }
564 function invalid_key_binding (seq) {
565     var e = new Error(seq.join(" ") + " is undefined");
566     e.key_sequence = seq;
567     e.__proto__ = invalid_key_binding.prototype;
568     return e;
570 invalid_key_binding.prototype = {
571     constructor: invalid_key_binding,
572     __proto__: interactive_error.prototype
575 function read_key_binding_key (window, state, event) {
576     var combo = format_key_combo(event);
577     var binding = keymap_lookup(state.target_keymap, combo, event);
579     state.key_sequence.push(combo);
581     if (binding == null) {
582         var c = state.continuation;
583         delete state.continuation;
584         window.minibuffer.pop_state();
585         c.throw(invalid_key_binding(state.key_sequence));
586         return;
587     }
589     if (binding.constructor == Array) { //keymaps stack
590         window.minibuffer._restore_normal_state();
591         window.minibuffer._input_text = state.key_sequence.join(" ") + " ";
592         state.target_keymap = binding;
593         return;
594     }
596     var c = state.continuation;
597     delete state.continuation;
599     window.minibuffer.pop_state();
601     if (c != null)
602         c([state.key_sequence, binding]);
604 interactive("read-key-binding-key",
605     "Handle a keystroke in the key binding reader minibuffer state.",
606      function (I) {
607          read_key_binding_key(I.window,
608                               I.minibuffer.check_state(key_binding_reader),
609                               I.event);
610      });
612 minibuffer.prototype.read_key_binding = function () {
613     keywords(arguments);
614     var s = new key_binding_reader(this, (yield CONTINUATION), forward_keywords(arguments));
615     this.push_state(s);
616     var result = yield SUSPEND;
617     yield co_return(result);
620 provide("keymap");