]> git.donarmstrong.com Git - dactyl.git/blob - common/content/mappings.js
c272eb5f8d9c50b26bccb33de0a33207af9f9f2c
[dactyl.git] / common / content / mappings.js
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2012 Kris Maglione <maglione.k at Gmail>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 /** @scope modules */
10
11 /**
12  * A class representing key mappings. Instances are created by the
13  * {@link Mappings} class.
14  *
15  * @param {[Modes.Mode]} modes The modes in which this mapping is active.
16  * @param {[string]} keys The key sequences which are bound to
17  *     *action*.
18  * @param {string} description A short one line description of the key mapping.
19  * @param {function} action The action invoked by each key sequence.
20  * @param {Object} info An optional extra configuration hash. The
21  *     following properties are supported.
22  *         arg     - see {@link Map#arg}
23  *         count   - see {@link Map#count}
24  *         motion  - see {@link Map#motion}
25  *         noremap - see {@link Map#noremap}
26  *         rhs     - see {@link Map#rhs}
27  *         silent  - see {@link Map#silent}
28  * @optional
29  * @private
30  */
31 var Map = Class("Map", {
32     init: function (modes, keys, description, action, info) {
33         this.id = ++Map.id;
34         this.modes = modes;
35         this._keys = keys;
36         this.action = action;
37         this.description = description;
38
39         Object.freeze(this.modes);
40
41         if (info) {
42             if (Set.has(Map.types, info.type))
43                 this.update(Map.types[info.type]);
44             this.update(info);
45         }
46     },
47
48     name: Class.Memoize(function () this.names[0]),
49
50     /** @property {[string]} All of this mapping's names (key sequences). */
51     names: Class.Memoize(function () this._keys.map(function (k) DOM.Event.canonicalKeys(k))),
52
53     get toStringParams() [this.modes.map(function (m) m.name), this.names.map(String.quote)],
54
55     get identifier() [this.modes[0].name, this.hive.prefix + this.names[0]].join("."),
56
57     /** @property {number} A unique ID for this mapping. */
58     id: null,
59     /** @property {[Modes.Mode]} All of the modes for which this mapping applies. */
60     modes: null,
61     /** @property {function (number)} The function called to execute this mapping. */
62     action: null,
63     /** @property {string} This mapping's description, as shown in :listkeys. */
64     description: Messages.Localized(""),
65
66     /** @property {boolean} Whether this mapping accepts an argument. */
67     arg: false,
68     /** @property {boolean} Whether this mapping accepts a count. */
69     count: false,
70     /**
71      * @property {boolean} Whether the mapping accepts a motion mapping
72      *     as an argument.
73      */
74     motion: false,
75
76     /** @property {boolean} Whether the RHS of the mapping should expand mappings recursively. */
77     noremap: false,
78
79     /** @property {function(object)} A function to be executed before this mapping. */
80     preExecute: function preExecute(args) {},
81     /** @property {function(object)} A function to be executed after this mapping. */
82     postExecute: function postExecute(args) {},
83
84     /** @property {boolean} Whether any output from the mapping should be echoed on the command line. */
85     silent: false,
86
87     /** @property {string} The literal RHS expansion of this mapping. */
88     rhs: null,
89
90     /** @property {string} The type of this mapping. */
91     type: "",
92
93     /**
94      * @property {boolean} Specifies whether this is a user mapping. User
95      *     mappings may be created by plugins, or directly by users. Users and
96      *     plugin authors should create only user mappings.
97      */
98     user: false,
99
100     /**
101      * Returns whether this mapping can be invoked by a key sequence matching
102      * *name*.
103      *
104      * @param {string} name The name to query.
105      * @returns {boolean}
106      */
107     hasName: function (name) this.keys.indexOf(name) >= 0,
108
109     get keys() array.flatten(this.names.map(mappings.closure.expand)),
110
111     /**
112      * Execute the action for this mapping.
113      *
114      * @param {object} args The arguments object for the given mapping.
115      */
116     execute: function (args) {
117         if (!isObject(args)) // Backwards compatibility :(
118             args = iter(["motion", "count", "arg", "command"])
119                 .map(function ([i, prop]) [prop, this[i]], arguments)
120                 .toObject();
121
122         args = this.hive.makeArgs(this.hive.group.lastDocument,
123                                   contexts.context,
124                                   args);
125
126         let self = this;
127         function repeat() self.action(args)
128         if (this.names[0] != ".") // FIXME: Kludge.
129             mappings.repeat = repeat;
130
131         if (this.executing)
132             util.assert(!args.keypressEvents[0].isMacro,
133                         _("map.recursive", args.command),
134                         false);
135
136         try {
137             dactyl.triggerObserver("mappings.willExecute", this, args);
138             mappings.pushCommand();
139             this.preExecute(args);
140             this.executing = true;
141             var res = repeat();
142         }
143         catch (e) {
144             events.feedingKeys = false;
145             dactyl.reportError(e, true);
146         }
147         finally {
148             this.executing = false;
149             mappings.popCommand();
150             this.postExecute(args);
151             dactyl.triggerObserver("mappings.executed", this, args);
152         }
153         return res;
154     }
155
156 }, {
157     id: 0,
158
159     types: {}
160 });
161
162 var MapHive = Class("MapHive", Contexts.Hive, {
163     init: function init(group) {
164         init.supercall(this, group);
165         this.stacks = {};
166     },
167
168     /**
169      * Iterates over all mappings present in all of the given *modes*.
170      *
171      * @param {[Modes.Mode]} modes The modes for which to return mappings.
172      */
173     iterate: function (modes) {
174         let stacks = Array.concat(modes).map(this.closure.getStack);
175         return values(stacks.shift().sort(function (m1, m2) String.localeCompare(m1.name, m2.name))
176             .filter(function (map) map.rhs &&
177                 stacks.every(function (stack) stack.some(function (m) m.rhs && m.rhs === map.rhs && m.name === map.name))));
178     },
179
180     /**
181      * Adds a new key mapping.
182      *
183      * @param {[Modes.Mode]} modes The modes that this mapping applies to.
184      * @param {[string]} keys The key sequences which are bound to *action*.
185      * @param {string} description A description of the key mapping.
186      * @param {function} action The action invoked by each key sequence.
187      * @param {Object} extra An optional extra configuration hash.
188      * @optional
189      */
190     add: function (modes, keys, description, action, extra) {
191         extra = extra || {};
192
193         modes = Array.concat(modes);
194         if (!modes.every(util.identity))
195             throw TypeError(/*L*/"Invalid modes: " + modes);
196
197         let map = Map(modes, keys, description, action, extra);
198         map.definedAt = contexts.getCaller(Components.stack.caller);
199         map.hive = this;
200
201         if (this.name !== "builtin")
202             for (let [, name] in Iterator(map.names))
203                 for (let [, mode] in Iterator(map.modes))
204                     this.remove(mode, name);
205
206         for (let mode in values(map.modes))
207             this.getStack(mode).add(map);
208         return map;
209     },
210
211     /**
212      * Returns the mapping stack for the given mode.
213      *
214      * @param {Modes.Mode} mode The mode to search.
215      * @returns {[Map]}
216      */
217     getStack: function getStack(mode) {
218         if (!(mode in this.stacks))
219             return this.stacks[mode] = MapHive.Stack();
220         return this.stacks[mode];
221     },
222
223     /**
224      * Returns the map from *mode* named *cmd*.
225      *
226      * @param {Modes.Mode} mode The mode to search.
227      * @param {string} cmd The map name to match.
228      * @returns {Map|null}
229      */
230     get: function (mode, cmd) this.getStack(mode).mappings[cmd],
231
232     /**
233      * Returns a count of maps with names starting with but not equal to
234      * *prefix*.
235      *
236      * @param {Modes.Mode} mode The mode to search.
237      * @param {string} prefix The map prefix string to match.
238      * @returns {number)
239      */
240     getCandidates: function (mode, prefix) this.getStack(mode).candidates[prefix] || 0,
241
242     /**
243      * Returns whether there is a user-defined mapping *cmd* for the specified
244      * *mode*.
245      *
246      * @param {Modes.Mode} mode The mode to search.
247      * @param {string} cmd The candidate key mapping.
248      * @returns {boolean}
249      */
250     has: function (mode, cmd) this.getStack(mode).mappings[cmd] != null,
251
252     /**
253      * Remove the mapping named *cmd* for *mode*.
254      *
255      * @param {Modes.Mode} mode The mode to search.
256      * @param {string} cmd The map name to match.
257      */
258     remove: function (mode, cmd) {
259         let stack = this.getStack(mode);
260         for (let [i, map] in array.iterItems(stack)) {
261             let j = map.names.indexOf(cmd);
262             if (j >= 0) {
263                 delete stack.states;
264                 map.names.splice(j, 1);
265                 if (map.names.length == 0) // FIX ME.
266                     for (let [mode, stack] in Iterator(this.stacks))
267                         this.stacks[mode] = MapHive.Stack(stack.filter(function (m) m != map));
268                 return;
269             }
270         }
271     },
272
273     /**
274      * Remove all user-defined mappings for *mode*.
275      *
276      * @param {Modes.Mode} mode The mode to remove all mappings from.
277      */
278     clear: function (mode) {
279         this.stacks[mode] = MapHive.Stack([]);
280     }
281 }, {
282     Stack: Class("Stack", Array, {
283         init: function (ary) {
284             let self = ary || [];
285             self.__proto__ = this.__proto__;
286             return self;
287         },
288
289         __iterator__: function () array.iterValues(this),
290
291         get candidates() this.states.candidates,
292         get mappings() this.states.mappings,
293
294         add: function (map) {
295             this.push(map);
296             delete this.states;
297         },
298
299         states: Class.Memoize(function () {
300             var states = {
301                 candidates: {},
302                 mappings: {}
303             };
304
305             for (let map in this)
306                 for (let name in values(map.keys)) {
307                     states.mappings[name] = map;
308                     let state = "";
309                     for (let key in DOM.Event.iterKeys(name)) {
310                         state += key;
311                         if (state !== name)
312                             states.candidates[state] = (states.candidates[state] || 0) + 1;
313                     }
314                 }
315             return states;
316         })
317     })
318 });
319
320 /**
321  * @instance mappings
322  */
323 var Mappings = Module("mappings", {
324     init: function () {
325         this.watches = [];
326         this._watchStack = 0;
327         this._yielders = 0;
328     },
329
330     afterCommands: function afterCommands(count, cmd, self) {
331         this.watches.push([cmd, self, Math.max(this._watchStack - 1, 0), count || 1]);
332     },
333
334     pushCommand: function pushCommand(cmd) {
335         this._watchStack++;
336         this._yielders = util.yielders;
337     },
338     popCommand: function popCommand(cmd) {
339         this._watchStack = Math.max(this._watchStack - 1, 0);
340         if (util.yielders > this._yielders)
341             this._watchStack = 0;
342
343         this.watches = this.watches.filter(function (elem) {
344             if (this._watchStack <= elem[2])
345                 elem[3]--;
346             if (elem[3] <= 0)
347                 elem[0].call(elem[1] || null);
348             return elem[3] > 0;
349         }, this);
350     },
351
352     repeat: Modes.boundProperty(),
353
354     get allHives() contexts.allGroups.mappings,
355
356     get userHives() this.allHives.filter(function (h) h !== this.builtin, this),
357
358     expandLeader: deprecated("your brain", function expandLeader(keyString) keyString),
359
360     prefixes: Class.Memoize(function () {
361         let list = Array.map("CASM", function (s) s + "-");
362
363         return iter(util.range(0, 1 << list.length)).map(function (mask)
364             list.filter(function (p, i) mask & (1 << i)).join("")).toArray().concat("*-");
365     }),
366
367     expand: function expand(keys) {
368         if (!/<\*-/.test(keys))
369             var res = keys;
370         else
371             res = util.debrace(DOM.Event.iterKeys(keys).map(function (key) {
372                 if (/^<\*-/.test(key))
373                     return ["<", this.prefixes, key.slice(3)];
374                 return key;
375             }, this).flatten().array).map(function (k) DOM.Event.canonicalKeys(k));
376
377         if (keys != arguments[0])
378             return [arguments[0]].concat(keys);
379         return keys;
380     },
381
382     iterate: function (mode) {
383         let seen = {};
384         for (let hive in this.hives.iterValues())
385             for (let map in array(hive.getStack(mode)).iterValues())
386                 if (!Set.add(seen, map.name))
387                     yield map;
388     },
389
390     // NOTE: just normal mode for now
391     /** @property {Iterator(Map)} */
392     __iterator__: function () this.iterate(modes.NORMAL),
393
394     getDefault: deprecated("mappings.builtin.get", function getDefault(mode, cmd) this.builtin.get(mode, cmd)),
395     getUserIterator: deprecated("mappings.user.iterator", function getUserIterator(modes) this.user.iterator(modes)),
396     hasMap: deprecated("group.mappings.has", function hasMap(mode, cmd) this.user.has(mode, cmd)),
397     remove: deprecated("group.mappings.remove", function remove(mode, cmd) this.user.remove(mode, cmd)),
398     removeAll: deprecated("group.mappings.clear", function removeAll(mode) this.user.clear(mode)),
399
400     /**
401      * Adds a new default key mapping.
402      *
403      * @param {[Modes.Mode]} modes The modes that this mapping applies to.
404      * @param {[string]} keys The key sequences which are bound to *action*.
405      * @param {string} description A description of the key mapping.
406      * @param {function} action The action invoked by each key sequence.
407      * @param {Object} extra An optional extra configuration hash.
408      * @optional
409      */
410     add: function add() {
411         let group = this.builtin;
412         if (!util.isDactyl(Components.stack.caller)) {
413             deprecated.warn(add, "mappings.add", "group.mappings.add");
414             group = this.user;
415         }
416
417         let map = group.add.apply(group, arguments);
418         map.definedAt = contexts.getCaller(Components.stack.caller);
419         return map;
420     },
421
422     /**
423      * Adds a new user-defined key mapping.
424      *
425      * @param {[Modes.Mode]} modes The modes that this mapping applies to.
426      * @param {[string]} keys The key sequences which are bound to *action*.
427      * @param {string} description A description of the key mapping.
428      * @param {function} action The action invoked by each key sequence.
429      * @param {Object} extra An optional extra configuration hash (see
430      *     {@link Map#extraInfo}).
431      * @optional
432      */
433     addUserMap: deprecated("group.mappings.add", function addUserMap() {
434         let map = this.user.add.apply(this.user, arguments);
435         map.definedAt = contexts.getCaller(Components.stack.caller);
436         return map;
437     }),
438
439     /**
440      * Returns the map from *mode* named *cmd*.
441      *
442      * @param {Modes.Mode} mode The mode to search.
443      * @param {string} cmd The map name to match.
444      * @returns {Map}
445      */
446     get: function get(mode, cmd) this.hives.map(function (h) h.get(mode, cmd)).compact()[0] || null,
447
448     /**
449      * Returns a count of maps with names starting with but not equal to
450      * *prefix*.
451      *
452      * @param {Modes.Mode} mode The mode to search.
453      * @param {string} prefix The map prefix string to match.
454      * @returns {[Map]}
455      */
456     getCandidates: function (mode, prefix)
457         this.hives.map(function (h) h.getCandidates(mode, prefix))
458                   .reduce(function (a, b) a + b, 0),
459
460     /**
461      * Lists all user-defined mappings matching *filter* for the specified
462      * *modes* in the specified *hives*.
463      *
464      * @param {[Modes.Mode]} modes An array of modes to search.
465      * @param {string} filter The filter string to match. @optional
466      * @param {[MapHive]} hives The map hives to list. @optional
467      */
468     list: function (modes, filter, hives) {
469         let modeSign = modes.map(function (m) m.char || "").join("")
470                      + modes.map(function (m) !m.char ? " " + m.name : "").join("");
471         modeSign = modeSign.replace(/^ /, "");
472
473         hives = (hives || mappings.userHives).map(function (h) [h, maps(h)])
474                                              .filter(function ([h, m]) m.length);
475
476         function maps(hive) {
477             let maps = iter.toArray(hive.iterate(modes));
478             if (filter)
479                 maps = maps.filter(function (m) m.names[0] === filter);
480             return maps;
481         }
482
483         let list = ["table", {},
484                 ["tr", { highlight: "Title" },
485                     ["td", {}],
486                     ["td", { style: "padding-right: 1em;" }, _("title.Mode")],
487                     ["td", { style: "padding-right: 1em;" }, _("title.Command")],
488                     ["td", { style: "padding-right: 1em;" }, _("title.Action")]],
489                 ["col", { style: "min-width: 6em; padding-right: 1em;" }],
490                 hives.map(function ([hive, maps]) let (i = 0) [
491                     ["tr", { style: "height: .5ex;" }],
492                     maps.map(function (map)
493                         map.names.map(function (name)
494                         ["tr", {},
495                             ["td", { highlight: "Title" }, !i++ ? hive.name : ""],
496                             ["td", {}, modeSign],
497                             ["td", {}, name],
498                             ["td", {}, map.rhs || map.action.toSource()]])),
499                     ["tr", { style: "height: .5ex;" }]])]
500
501         // E4X-FIXME
502         // // TODO: Move this to an ItemList to show this automatically
503         // if (list.*.length() === list.text().length() + 2)
504         //     dactyl.echomsg(_("map.none"));
505         // else
506         commandline.commandOutput(list);
507     }
508 }, {
509 }, {
510     contexts: function initContexts(dactyl, modules, window) {
511         update(Mappings.prototype, {
512             hives: contexts.Hives("mappings", MapHive),
513             user: contexts.hives.mappings.user,
514             builtin: contexts.hives.mappings.builtin
515         });
516     },
517     commands: function initCommands(dactyl, modules, window) {
518         function addMapCommands(ch, mapmodes, modeDescription) {
519             function map(args, noremap) {
520                 let mapmodes = array.uniq(args["-modes"].map(findMode));
521                 let hives = args.explicitOpts["-group"] ? [args["-group"]] : null;
522
523                 if (!args.length) {
524                     mappings.list(mapmodes, null, hives);
525                     return;
526                 }
527
528                 if (args[1] && !/^<nop>$/i.test(args[1])
529                     && !args["-count"] && !args["-ex"] && !args["-javascript"]
530                     && mapmodes.every(function (m) m.count))
531                     args[1] = "<count>" + args[1];
532
533                 let [lhs, rhs] = args;
534                 if (noremap)
535                     args["-builtin"] = true;
536
537                 if (!rhs) // list the mapping
538                     mappings.list(mapmodes, lhs, hives);
539                 else {
540                     util.assert(args["-group"].modifiable,
541                                 _("map.builtinImmutable"));
542
543                     args["-group"].add(mapmodes, [lhs],
544                         args["-description"],
545                         contexts.bindMacro(args, "-keys", function (params) params),
546                         {
547                             arg: args["-arg"],
548                             count: args["-count"] || !(args["-ex"] || args["-javascript"]),
549                             noremap: args["-builtin"],
550                             persist: !args["-nopersist"],
551                             get rhs() String(this.action),
552                             silent: args["-silent"]
553                         });
554                 }
555             }
556
557             const opts = {
558                 identifier: "map",
559                 completer: function (context, args) {
560                     let mapmodes = array.uniq(args["-modes"].map(findMode));
561                     if (args.length == 1)
562                         return completion.userMapping(context, mapmodes, args["-group"]);
563                     if (args.length == 2) {
564                         if (args["-javascript"])
565                             return completion.javascript(context);
566                         if (args["-ex"])
567                             return completion.ex(context);
568                     }
569                 },
570                 hereDoc: true,
571                 literal: 1,
572                 options: [
573                     {
574                         names: ["-arg", "-a"],
575                         description: "Accept an argument after the requisite key press",
576                     },
577                     {
578                         names: ["-builtin", "-b"],
579                         description: "Execute this mapping as if there were no user-defined mappings"
580                     },
581                     {
582                         names: ["-count", "-c"],
583                         description: "Accept a count before the requisite key press"
584                     },
585                     {
586                         names: ["-description", "-desc", "-d"],
587                         description: "A description of this mapping",
588                         default: /*L*/"User-defined mapping",
589                         type: CommandOption.STRING
590                     },
591                     {
592                         names: ["-ex", "-e"],
593                         description: "Execute this mapping as an Ex command rather than keys"
594                     },
595                     contexts.GroupFlag("mappings"),
596                     {
597                         names: ["-javascript", "-js", "-j"],
598                         description: "Execute this mapping as JavaScript rather than keys"
599                     },
600                     update({}, modeFlag, {
601                         names: ["-modes", "-mode", "-m"],
602                         type: CommandOption.LIST,
603                         description: "Create this mapping in the given modes",
604                         default: mapmodes || ["n", "v"]
605                     }),
606                     {
607                         names: ["-nopersist", "-n"],
608                         description: "Do not save this mapping to an auto-generated RC file"
609                     },
610                     {
611                         names: ["-silent", "-s", "<silent>", "<Silent>"],
612                         description: "Do not echo any generated keys to the command line"
613                     }
614                 ],
615                 serialize: function () {
616                     return this.name != "map" ? [] :
617                         array(mappings.userHives)
618                             .filter(function (h) h.persist)
619                             .map(function (hive) [
620                                 {
621                                     command: "map",
622                                     options: {
623                                         "-count": map.count ? null : undefined,
624                                         "-description": map.description,
625                                         "-group": hive.name == "user" ? undefined : hive.name,
626                                         "-modes": uniqueModes(map.modes),
627                                         "-silent": map.silent ? null : undefined
628                                     },
629                                     arguments: [map.names[0]],
630                                     literalArg: map.rhs,
631                                     ignoreDefaults: true
632                                 }
633                                 for (map in userMappings(hive))
634                                 if (map.persist)
635                             ])
636                             .flatten().array;
637                 }
638             };
639             function userMappings(hive) {
640                 let seen = {};
641                 for (let stack in values(hive.stacks))
642                     for (let map in array.iterValues(stack))
643                         if (!Set.add(seen, map.id))
644                             yield map;
645             }
646
647             modeDescription = modeDescription ? " in " + modeDescription + " mode" : "";
648             commands.add([ch ? ch + "m[ap]" : "map"],
649                 "Map a key sequence" + modeDescription,
650                 function (args) { map(args, false); },
651                 update({}, opts));
652
653             commands.add([ch + "no[remap]"],
654                 "Map a key sequence without remapping keys" + modeDescription,
655                 function (args) { map(args, true); },
656                 update({ deprecated: ":" + ch + "map -builtin" }, opts));
657
658             commands.add([ch + "unm[ap]"],
659                 "Remove a mapping" + modeDescription,
660                 function (args) {
661                     util.assert(args["-group"].modifiable, _("map.builtinImmutable"));
662
663                     util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
664
665                     let mapmodes = array.uniq(args["-modes"].map(findMode));
666
667                     let found = 0;
668                     for (let mode in values(mapmodes))
669                         if (args.bang)
670                             args["-group"].clear(mode);
671                         else if (args["-group"].has(mode, args[0])) {
672                             args["-group"].remove(mode, args[0]);
673                             found++;
674                         }
675
676                     if (!found && !args.bang)
677                         dactyl.echoerr(_("map.noSuch", args[0]));
678                 },
679                 {
680                     identifier: "unmap",
681                     argCount: "?",
682                     bang: true,
683                     completer: opts.completer,
684                     options: [
685                         contexts.GroupFlag("mappings"),
686                         update({}, modeFlag, {
687                             names: ["-modes", "-mode", "-m"],
688                             type: CommandOption.LIST,
689                             description: "Remove mapping from the given modes",
690                             default: mapmodes || ["n", "v"]
691                         })
692                     ]
693                 });
694         }
695
696         let modeFlag = {
697             names: ["-mode", "-m"],
698             type: CommandOption.STRING,
699             validator: function (value) Array.concat(value).every(findMode),
700             completer: function () [[array.compact([mode.name.toLowerCase().replace(/_/g, "-"), mode.char]), mode.description]
701                                     for (mode in values(modes.all))
702                                     if (!mode.hidden)]
703         };
704
705         function findMode(name) {
706             if (name)
707                 for (let mode in values(modes.all))
708                     if (name == mode || name == mode.char
709                         || String.toLowerCase(name).replace(/-/g, "_") == mode.name.toLowerCase())
710                         return mode;
711             return null;
712         }
713         function uniqueModes(modes) {
714             let chars = [k for ([k, v] in Iterator(modules.modes.modeChars))
715                          if (v.every(function (mode) modes.indexOf(mode) >= 0))];
716             return array.uniq(modes.filter(function (m) chars.indexOf(m.char) < 0)
717                                    .map(function (m) m.name.toLowerCase())
718                                    .concat(chars));
719         }
720
721         commands.add(["feedkeys", "fk"],
722             "Fake key events",
723             function (args) { events.feedkeys(args[0] || "", args.bang, false, findMode(args["-mode"])); },
724             {
725                 argCount: "1",
726                 bang: true,
727                 literal: 0,
728                 options: [
729                     update({}, modeFlag, {
730                         description: "The mode in which to feed the keys"
731                     })
732                 ]
733             });
734
735         addMapCommands("", [modes.NORMAL, modes.VISUAL], "");
736
737         for (let mode in modes.mainModes)
738             if (mode.char && !commands.get(mode.char + "map", true))
739                 addMapCommands(mode.char,
740                                [m.mask for (m in modes.mainModes) if (m.char == mode.char)],
741                                mode.displayName);
742
743         let args = {
744             getMode: function (args) findMode(args["-mode"]),
745             iterate: function (args, mainOnly) {
746                 let modes = [this.getMode(args)];
747                 if (!mainOnly)
748                     modes = modes[0].allBases;
749
750                 let seen = {};
751                 // Bloody hell. --Kris
752                 for (let [i, mode] in Iterator(modes))
753                     for (let hive in mappings.hives.iterValues())
754                         for (let map in array.iterValues(hive.getStack(mode)))
755                             for (let name in values(map.names))
756                                 if (!Set.add(seen, name)) {
757                                     yield {
758                                         name: name,
759                                         columns: [
760                                             i === 0 ? "" : ["span", { highlight: "Object", style: "padding-right: 1em;" },
761                                                                 mode.name],
762                                             hive == mappings.builtin ? "" : ["span", { highlight: "Object", style: "padding-right: 1em;" },
763                                                                                  hive.name]
764                                         ],
765                                         __proto__: map
766                                     };
767                                 }
768             },
769             format: {
770                 description: function (map) [
771                         options.get("passkeys").has(map.name)
772                             ? ["span", { highlight: "URLExtra" },
773                                 "(", template.linkifyHelp(_("option.passkeys.passedBy")), ")"]
774                             : [],
775                         template.linkifyHelp(map.description + (map.rhs ? ": " + map.rhs : ""))
776                 ],
777                 help: function (map) let (char = array.compact(map.modes.map(function (m) m.char))[0])
778                     char === "n" ? map.name : char ? char + "_" + map.name : "",
779                 headings: ["Command", "Mode", "Group", "Description"]
780             }
781         };
782
783         dactyl.addUsageCommand({
784             __proto__: args,
785             name: ["listk[eys]", "lk"],
786             description: "List all mappings along with their short descriptions",
787             options: [
788                 update({}, modeFlag, {
789                     default: "n",
790                     description: "The mode for which to list mappings"
791                 })
792             ]
793         });
794
795         iter.forEach(modes.mainModes, function (mode) {
796             if (mode.char && !commands.get(mode.char + "listkeys", true))
797                 dactyl.addUsageCommand({
798                     __proto__: args,
799                     name: [mode.char + "listk[eys]", mode.char + "lk"],
800                     iterateIndex: function (args)
801                             let (self = this, prefix = /^[bCmn]$/.test(mode.char) ? "" : mode.char + "_",
802                                  haveTag = Set.has(help.tags))
803                                     ({ helpTag: prefix + map.name, __proto__: map }
804                                      for (map in self.iterate(args, true))
805                                      if (map.hive === mappings.builtin || haveTag(prefix + map.name))),
806                     description: "List all " + mode.displayName + " mode mappings along with their short descriptions",
807                     index: mode.char + "-map",
808                     getMode: function (args) mode,
809                     options: []
810                 });
811         });
812     },
813     completion: function initCompletion(dactyl, modules, window) {
814         completion.userMapping = function userMapping(context, modes_, hive) {
815             hive = hive || mappings.user;
816             modes_ = modes_ || [modes.NORMAL];
817             context.keys = { text: function (m) m.names[0], description: function (m) m.description + ": " + m.action };
818             context.completions = hive.iterate(modes_);
819         };
820     },
821     javascript: function initJavascript(dactyl, modules, window) {
822         JavaScript.setCompleter([Mappings.prototype.get, MapHive.prototype.get],
823             [
824                 null,
825                 function (context, obj, args) [[m.names, m.description] for (m in this.iterate(args[0]))]
826             ]);
827     },
828     mappings: function initMappings(dactyl, modules, window) {
829         mappings.add([modes.COMMAND],
830              ["\\"], "Emits <Leader> pseudo-key",
831              function () { events.feedkeys("<Leader>") });
832     }
833 });
834
835 // vim: set fdm=marker sw=4 ts=4 et: