]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/commands.jsm
0e0d58fc8b6468f2961eea1c7e50d6f96feef2e5
[dactyl.git] / common / modules / commands.jsm
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-2013 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 try {
10
11 defineModule("commands", {
12     exports: ["ArgType", "Command", "Commands", "CommandOption", "Ex", "commands"],
13     require: ["contexts", "messages", "util"]
14 });
15
16 lazyRequire("help", ["help"]);
17 lazyRequire("options", ["Option"]);
18 lazyRequire("template", ["template"]);
19
20 /**
21  * A structure representing the options available for a command.
22  *
23  * Do NOT create instances of this class yourself, use the helper method
24  * {@see Commands#add} instead
25  *
26  * @property {[string]} names An array of option names. The first name
27  *     is the canonical option name.
28  * @property {number} type The option's value type. This is one of:
29  *         (@link CommandOption.NOARG),
30  *         (@link CommandOption.STRING),
31  *         (@link CommandOption.STRINGMAP),
32  *         (@link CommandOption.BOOL),
33  *         (@link CommandOption.INT),
34  *         (@link CommandOption.FLOAT),
35  *         (@link CommandOption.LIST),
36  *         (@link CommandOption.ANY)
37  * @property {function} validator A validator function
38  * @property {function (CompletionContext, object)} completer A list of
39  *    completions, or a completion function which will be passed a
40  *    {@link CompletionContext} and an object like that returned by
41  *    {@link commands.parseArgs} with the following additional keys:
42  *      completeOpt - The name of the option currently being completed.
43  * @property {boolean} multiple Whether this option can be specified multiple times
44  * @property {string} description A description of the option
45  * @property {object} default The option's default value
46  */
47
48 var CommandOption = Struct("names", "type", "validator", "completer", "multiple", "description", "default");
49 CommandOption.defaultValue("description", () => "");
50 CommandOption.defaultValue("type", () => CommandOption.NOARG);
51 CommandOption.defaultValue("multiple", () => false);
52
53 var ArgType = Struct("description", "parse");
54 update(CommandOption, {
55     /**
56      * @property {object} The option argument is unspecified. Any argument
57      *     is accepted and caller is responsible for parsing the return
58      *     value.
59      * @final
60      */
61     ANY: 0,
62
63     /**
64      * @property {object} The option doesn't accept an argument.
65      * @final
66      */
67     NOARG: ArgType("no arg",  arg => !arg || null),
68     /**
69      * @property {object} The option accepts a boolean argument.
70      * @final
71      */
72     BOOL: ArgType("boolean", function parseBoolArg(val) Commands.parseBool(val)),
73     /**
74      * @property {object} The option accepts a string argument.
75      * @final
76      */
77     STRING: ArgType("string", val => val),
78     /**
79      * @property {object} The option accepts a stringmap argument.
80      * @final
81      */
82     STRINGMAP: ArgType("stringmap", (val, quoted) => Option.parse.stringmap(quoted)),
83     /**
84      * @property {object} The option accepts an integer argument.
85      * @final
86      */
87     INT: ArgType("int", function parseIntArg(val) parseInt(val)),
88     /**
89      * @property {object} The option accepts a float argument.
90      * @final
91      */
92     FLOAT: ArgType("float", function parseFloatArg(val) parseFloat(val)),
93     /**
94      * @property {object} The option accepts a string list argument.
95      *     E.g. "foo,bar"
96      * @final
97      */
98     LIST: ArgType("list", function parseListArg(arg, quoted) Option.splitList(quoted))
99 });
100
101 /**
102  * A class representing Ex commands. Instances are created by
103  * the {@link Commands} class.
104  *
105  * @param {[string]} specs The names by which this command can be invoked.
106  *     These are specified in the form "com[mand]" where "com" is a unique
107  *     command name prefix.
108  * @param {string} description A short one line description of the command.
109  * @param {function} action The action invoked by this command when executed.
110  * @param {Object} extraInfo An optional extra configuration hash. The
111  *     following properties are supported.
112  *         always      - see {@link Command#always}
113  *         argCount    - see {@link Command#argCount}
114  *         bang        - see {@link Command#bang}
115  *         completer   - see {@link Command#completer}
116  *         count       - see {@link Command#count}
117  *         domains     - see {@link Command#domains}
118  *         heredoc     - see {@link Command#heredoc}
119  *         literal     - see {@link Command#literal}
120  *         options     - see {@link Command#options}
121  *         privateData - see {@link Command#privateData}
122  *         serialize   - see {@link Command#serialize}
123  *         subCommand  - see {@link Command#subCommand}
124  * @optional
125  * @private
126  */
127 var Command = Class("Command", {
128     init: function init(specs, description, action, extraInfo) {
129         specs = Array.concat(specs); // XXX
130
131         this.specs = specs;
132         this.description = description;
133         this.action = action;
134
135         if (extraInfo.options)
136             this._options = extraInfo.options;
137         delete extraInfo.options;
138
139         if (extraInfo)
140             this.update(extraInfo);
141     },
142
143     get toStringParams() [this.name, this.hive.name],
144
145     get identifier() this.hive.prefix + this.name,
146
147     get helpTag() ":" + this.name,
148
149     get lastCommand() this._lastCommand || this.modules.commandline.command,
150     set lastCommand(val) { this._lastCommand = val; },
151
152     /**
153      * Execute this command.
154      *
155      * @param {Args} args The Args object passed to {@link #action}.
156      * @param {Object} modifiers Any modifiers to be passed to {@link #action}.
157      */
158     execute: function execute(args, modifiers = {}) {
159         const { dactyl } = this.modules;
160
161         let context = args.context;
162         if (this.deprecated)
163             this.warn(context, "deprecated", _("warn.deprecated", ":" + this.name, this.deprecated));
164
165         if (args.count != null && !this.count)
166             throw FailedAssertion(_("command.noCount"));
167         if (args.bang && !this.bang)
168             throw FailedAssertion(_("command.noBang"));
169
170         args.doc = this.hive.group.lastDocument;
171
172         return !dactyl.trapErrors(function exec() {
173             let extra = this.hive.argsExtra(args);
174
175             for (let k in properties(extra))
176                 if (!(k in args))
177                     Object.defineProperty(args, k, Object.getOwnPropertyDescriptor(extra, k));
178
179             if (this.always)
180                 this.always(args, modifiers);
181
182             if (!context || !context.noExecute)
183                 this.action(args, modifiers);
184         }, this);
185     },
186
187     /**
188      * Returns whether this command may be invoked via *name*.
189      *
190      * @param {string} name The candidate name.
191      * @returns {boolean}
192      */
193     hasName: function hasName(name) Command.hasName(this.parsedSpecs, name),
194
195     /**
196      * A helper function to parse an argument string.
197      *
198      * @param {string} args The argument string to parse.
199      * @param {CompletionContext} complete A completion context.
200      *     Non-null when the arguments are being parsed for completion
201      *     purposes.
202      * @param {Object} extra Extra keys to be spliced into the
203      *     returned Args object.
204      * @returns {Args}
205      * @see Commands#parseArgs
206      */
207     parseArgs: function parseArgs(args, complete, extra) this.modules.commands.parseArgs(args, {
208         __proto__: this,
209         complete: complete,
210         extra: extra
211     }),
212
213     complained: Class.Memoize(function () ({})),
214
215     /**
216      * @property {[string]} All of this command's name specs. e.g., "com[mand]"
217      */
218     specs: null,
219     parsedSpecs: Class.Memoize(function () Command.parseSpecs(this.specs)),
220
221     /** @property {[string]} All of this command's short names, e.g., "com" */
222     shortNames: Class.Memoize(function () array.compact(this.parsedSpecs.map(n => n[1]))),
223
224     /**
225      * @property {[string]} All of this command's long names, e.g., "command"
226      */
227     longNames: Class.Memoize(function () this.parsedSpecs.map(n => n[0])),
228
229     /** @property {string} The command's canonical name. */
230     name: Class.Memoize(function () this.longNames[0]),
231
232     /** @property {[string]} All of this command's long and short names. */
233     names: Class.Memoize(function () this.names = array.flatten(this.parsedSpecs)),
234
235     /** @property {string} This command's description, as shown in :listcommands */
236     description: Messages.Localized(""),
237
238     /** @property {string|null} If set, the deprecation message for this command. */
239     deprecated: Messages.Localized(null),
240
241     /**
242      * @property {function (Args)} The function called to execute this command.
243      */
244     action: null,
245
246     /**
247      * @property {function (Args)} A function which is called when this
248      * command is encountered, even if we are ignoring commands. Used to
249      * implement control structures.
250      */
251     always: null,
252
253     /**
254      * @property {string} This command's argument count spec.
255      * @see Commands#parseArguments
256      */
257     argCount: 0,
258
259     /**
260      * @property {function (CompletionContext, Args)} This command's completer.
261      * @see CompletionContext
262      */
263     completer: null,
264
265     /** @property {boolean} Whether this command accepts a here document. */
266     hereDoc: false,
267
268     /**
269      * @property {boolean} Whether this command may be called with a bang,
270      *     e.g., :com!
271      */
272     bang: false,
273
274     /**
275      * @property {boolean} Whether this command may be called with a count,
276      *     e.g., :12bdel
277      */
278     count: false,
279
280     /**
281      * @property {function(args)} A function which should return a list
282      *     of domains referenced in the given args. Used in determining
283      *     whether to purge the command from history when clearing
284      *     private data.
285      */
286     domains: function (args) [],
287
288     /**
289      * @property {boolean} At what index this command's literal arguments
290      *     begin. For instance, with a value of 2, all arguments starting with
291      *     the third are parsed as a single string, with all quoting characters
292      *     passed literally. This is especially useful for commands which take
293      *     key mappings or Ex command lines as arguments.
294      */
295     literal: null,
296
297     /**
298      * @property {Array} The options this command takes.
299      * @see Commands@parseArguments
300      */
301     options: Class.Memoize(function ()
302         this._options.map(function (opt) {
303             let option = CommandOption.fromArray(opt);
304             option.localeName = ["command", this.name, option.names[0]];
305             return option;
306         }, this)),
307     _options: [],
308
309     optionMap: Class.Memoize(function () array(this.options)
310                 .map(opt => opt.names.map(name => [name, opt]))
311                 .flatten().toObject()),
312
313     newArgs: function newArgs(base) {
314         let res = [];
315         update(res, base);
316         res.__proto__ = this.argsPrototype;
317         return res;
318     },
319
320     argsPrototype: Class.Memoize(function argsPrototype() {
321         let res = update([], {
322                 __iterator__: function AP__iterator__() array.iterItems(this),
323
324                 command: this,
325
326                 explicitOpts: Class.Memoize(function () ({})),
327
328                 has: function AP_has(opt) Set.has(this.explicitOpts, opt) || typeof opt === "number" && Set.has(this, opt),
329
330                 get literalArg() this.command.literal != null && this[this.command.literal] || "",
331
332                 // TODO: string: Class.Memoize(function () { ... }),
333
334                 verify: function verify() {
335                     if (this.command.argCount) {
336                         util.assert((this.length > 0 || !/^[1+]$/.test(this.command.argCount)) &&
337                                     (this.literal == null || !/[1+]/.test(this.command.argCount) || /\S/.test(this.literalArg || "")),
338                                      _("error.argumentRequired"));
339
340                         util.assert((this.length == 0 || this.command.argCount !== "0") &&
341                                     (this.length <= 1 || !/^[01?]$/.test(this.command.argCount)),
342                                     _("error.trailingCharacters"));
343                     }
344                 }
345         });
346
347         this.options.forEach(function (opt) {
348             if (opt.default !== undefined) {
349                 let prop = Object.getOwnPropertyDescriptor(opt, "default") ||
350                     { configurable: true, enumerable: true, get: function () opt.default };
351
352                 if (prop.get && !prop.set)
353                     prop.set = function (val) { Class.replaceProperty(this, opt.names[0], val); };
354                 Object.defineProperty(res, opt.names[0], prop);
355             }
356         });
357
358         return res;
359     }),
360
361     /**
362      * @property {boolean|function(args)} When true, invocations of this
363      *     command may contain private data which should be purged from
364      *     saved histories when clearing private data. If a function, it
365      *     should return true if an invocation with the given args
366      *     contains private data
367      */
368     privateData: true,
369     /**
370      * @property {function} Should return an array of *Object*s suitable to be
371      *     passed to {@link Commands#commandToString}, one for each past
372      *     invocation which should be restored on subsequent @dactyl startups.
373      */
374     serialize: null,
375     serialGroup: 50,
376     /**
377      * @property {number} If this command takes another ex command as an
378      *     argument, the index of that argument. Used in determining whether to
379      *     purge the command from history when clearing private data.
380      */
381     subCommand: null,
382     /**
383      * @property {boolean} Specifies whether this is a user command. User
384      *     commands may be created by plugins, or directly by users, and,
385      *     unlike basic commands, may be overwritten. Users and plugin authors
386      *     should create only user commands.
387      */
388     user: false,
389     /**
390      * @property {string} For commands defined via :command, contains the Ex
391      *     command line to be executed upon invocation.
392      */
393     replacementText: null,
394
395     /**
396      * Warns of a misuse of this command once per warning type per file.
397      *
398      * @param {object} context The calling context.
399      * @param {string} type The type of warning.
400      * @param {string} warning The warning message.
401      */
402     warn: function warn(context, type, message) {
403         let loc = !context ? "" : [context.file, context.line, " "].join(":");
404
405         if (!Set.add(this.complained, type + ":" + (context ? context.file : "[Command Line]")))
406             this.modules.dactyl.warn(loc + message);
407     }
408 }, {
409     hasName: function hasName(specs, name)
410         specs.some(([long, short]) =>
411             name.indexOf(short) == 0 && long.indexOf(name) == 0),
412
413     // TODO: do we really need more than longNames as a convenience anyway?
414     /**
415      *  Converts command name abbreviation specs of the form
416      *  'shortname[optional-tail]' to short and long versions:
417      *      ["abc[def]", "ghijkl"] ->  [["abcdef", "abc"], ["ghijlk"]]
418      *
419      *  @param {Array} specs An array of command name specs to parse.
420      *  @returns {Array}
421      */
422     parseSpecs: function parseSpecs(specs) {
423         return specs.map(function (spec) {
424             let [, head, tail] = /([^[]+)(?:\[(.*)])?/.exec(spec);
425             return tail ? [head + tail, head] : [head];
426         });
427     }
428 });
429
430 // Prototype.
431 var Ex = Module("Ex", {
432     Local: function Local(dactyl, modules, window) ({
433         get commands() modules.commands,
434         get context() modules.contexts.context
435     }),
436
437     _args: function E_args(cmd, args) {
438         args = Array.slice(args);
439
440         let res = cmd.newArgs({ context: this.context });
441         if (isObject(args[0]))
442             for (let [k, v] in Iterator(args.shift()))
443                 if (k == "!")
444                     res.bang = v;
445                 else if (k == "#")
446                     res.count = v;
447                 else {
448                     let opt = cmd.optionMap["-" + k];
449                     let val = opt.type && opt.type.parse(v);
450
451                     util.assert(val != null && (typeof val !== "number" || !isNaN(val)),
452                                 _("option.noSuch", k));
453
454                     Class.replaceProperty(res, opt.names[0], val);
455                     res.explicitOpts[opt.names[0]] = val;
456                 }
457         for (let [i, val] in array.iterItems(args))
458             res[i] = String(val);
459         return res;
460     },
461
462     _complete: function E_complete(cmd) let (self = this)
463         function _complete(context, func, obj, args) {
464             args = self._args(cmd, args);
465             args.completeArg = args.length - 1;
466             if (cmd.completer && args.length)
467                 return cmd.completer(context, args);
468         },
469
470     _run: function E_run(name) {
471         const self = this;
472         let cmd = this.commands.get(name);
473         util.assert(cmd, _("command.noSuch"));
474
475         return update(function exCommand(options) {
476             let args = self._args(cmd, arguments);
477             args.verify();
478             return cmd.execute(args);
479         }, {
480             dactylCompleter: self._complete(cmd)
481         });
482     },
483
484     __noSuchMethod__: function __noSuchMethod__(meth, args) this._run(meth).apply(this, args)
485 });
486
487 var CommandHive = Class("CommandHive", Contexts.Hive, {
488     init: function init(group) {
489         init.supercall(this, group);
490
491         this._map = {};
492         this._list = [];
493         this._specs = [];
494     },
495
496     /**
497      * Caches this command hive.
498      */
499
500     cache: function cache() {
501         let self = this;
502         let { cache } = this.modules;
503         this.cached = true;
504
505         let cached = cache.get(this.cacheKey, function () {
506             self.cached = false;
507             this.modules.moduleManager.initDependencies("commands");
508
509             let map = {};
510             for (let [name, cmd] in Iterator(self._map))
511                 if (cmd.sourceModule)
512                     map[name] = { sourceModule: cmd.sourceModule, isPlaceholder: true };
513
514             let specs = [];
515             for (let cmd in values(self._list))
516                 for each (let spec in cmd.parsedSpecs)
517                     specs.push(spec.concat(cmd.name));
518
519             return { map: map, specs: specs };
520         });
521
522         let cached = cache.get(this.cacheKey);
523         if (this.cached) {
524             this._specs = cached.specs;
525             for (let [k, v] in Iterator(cached.map))
526                 this._map[k] = v;
527         }
528     },
529
530     get cacheKey() "commands/hives/" + this.name + ".json",
531
532     /** @property {Iterator(Command)} @private */
533     __iterator__: function __iterator__() {
534         if (this.cached)
535             this.modules.initDependencies("commands");
536         this.cached = false;
537         return array.iterValues(this._list.sort((a, b) => a.name > b.name));
538     },
539
540     /** @property {string} The last executed Ex command line. */
541     repeat: null,
542
543     /**
544      * Adds a new command to the builtin hive. Accessible only to core dactyl
545      * code. Plugins should use group.commands.add instead.
546      *
547      * @param {[string]} specs The names by which this command can be invoked.
548      *     The first name specified is the command's canonical name.
549      * @param {string} description A description of the command.
550      * @param {function} action The action invoked by this command.
551      * @param {Object} extra An optional extra configuration hash.
552      *     @optional
553      * @param {boolean} replace Replace an existing command of the same name.
554      *     @optional
555      */
556     add: function add(specs, description, action, extra = {}, replace = false) {
557         const { commands, contexts } = this.modules;
558
559         if (!extra.definedAt)
560             extra.definedAt = contexts.getCaller(Components.stack.caller);
561         if (!extra.sourceModule)
562             extra.sourceModule = commands.currentDependency;
563
564         extra.hive = this;
565         extra.parsedSpecs = Command.parseSpecs(specs);
566
567         let names = array.flatten(extra.parsedSpecs);
568         let name = names[0];
569
570         if (this.name != "builtin") {
571             util.assert(!names.some(name => name in commands.builtin._map),
572                         _("command.cantReplace", name));
573
574             util.assert(replace || names.every(name => !(name in this._map)),
575                         _("command.wontReplace", name));
576         }
577
578         for (let name in values(names)) {
579             ex.__defineGetter__(name, function () this._run(name));
580             if (name in this._map && !this._map[name].isPlaceholder)
581                 this.remove(name);
582         }
583
584         let closure = () => this._map[name];
585
586         memoize(this._map, name, () => commands.Command(specs, description, action, extra));
587         if (!extra.hidden)
588             memoize(this._list, this._list.length, closure);
589         for (let alias in values(names.slice(1)))
590             memoize(this._map, alias, closure);
591
592         return name;
593     },
594
595     _add: function _add(names, description, action, extra = {}, replace = false) {
596         const { contexts } = this.modules;
597         extra.definedAt = contexts.getCaller(Components.stack.caller.caller);
598         return this.add.apply(this, arguments);
599     },
600
601     /**
602      * Clear all commands.
603      * @returns {Command}
604      */
605     clear: function clear() {
606         util.assert(this.group.modifiable, _("command.cantDelete"));
607         this._map = {};
608         this._list = [];
609     },
610
611     /**
612      * Returns the command with matching *name*.
613      *
614      * @param {string} name The name of the command to return. This can be
615      *     any of the command's names.
616      * @param {boolean} full If true, only return a command if one of
617      *     its names matches *name* exactly.
618      * @returns {Command}
619      */
620     get: function get(name, full) {
621         let cmd = this._map[name]
622                || !full && array.nth(this._list, cmd => cmd.hasName(name), 0)
623                || null;
624
625         if (!cmd && full) {
626             let name = array.nth(this.specs, spec => Command.hasName(spec, name), 0);
627             return name && this.get(name);
628         }
629
630         if (cmd && cmd.isPlaceholder) {
631             this.modules.moduleManager.initDependencies("commands", [cmd.sourceModule]);
632             cmd = this._map[name];
633         }
634         return cmd;
635     },
636
637     /**
638      * Remove the user-defined command with matching *name*.
639      *
640      * @param {string} name The name of the command to remove. This can be
641      *     any of the command's names.
642      */
643     remove: function remove(name) {
644         util.assert(this.group.modifiable, _("command.cantDelete"));
645
646         let cmd = this.get(name);
647         this._list = this._list.filter(c => c !== cmd);
648         for (let name in values(cmd.names))
649             delete this._map[name];
650     }
651 });
652
653 /**
654  * @instance commands
655  */
656 var Commands = Module("commands", {
657     lazyInit: true,
658     lazyDepends: true,
659
660     Local: function Local(dactyl, modules, window) let ({ Group, contexts } = modules) ({
661         init: function init() {
662             this.Command = Class("Command", Command, { modules: modules });
663             update(this, {
664                 hives: contexts.Hives("commands", Class("CommandHive", CommandHive, { modules: modules })),
665                 user: contexts.hives.commands.user,
666                 builtin: contexts.hives.commands.builtin
667             });
668         },
669
670         reallyInit: function reallyInit() {
671             if (false)
672                 this.builtin.cache();
673             else
674                 this.modules.moduleManager.initDependencies("commands");
675         },
676
677         get context() contexts.context,
678
679         get readHeredoc() modules.io.readHeredoc,
680
681         get allHives() contexts.allGroups.commands,
682
683         get userHives() this.allHives.filter(h => h !== this.builtin),
684
685         /**
686          * Executes an Ex command script.
687          *
688          * @param {string} string A string containing the commands to execute.
689          * @param {object} tokens An optional object containing tokens to be
690          *      interpolated into the command string.
691          * @param {object} args Optional arguments object to be passed to
692          *      command actions.
693          * @param {object} context An object containing information about
694          *      the file that is being or has been sourced to obtain the
695          *      command string.
696          */
697         execute: function execute(string, tokens, silent, args, context) {
698             contexts.withContext(context || this.context || { file: "[Command Line]", line: 1 },
699                                  function (context) {
700                 modules.io.withSavedValues(["readHeredoc"], function () {
701                     this.readHeredoc = function readHeredoc(end) {
702                         let res = [];
703                         contexts.context.line++;
704                         while (++i < lines.length) {
705                             if (lines[i] === end)
706                                 return res.join("\n");
707                             res.push(lines[i]);
708                         }
709                         util.assert(false, _("command.eof", end));
710                     };
711
712                     args = update({}, args || {});
713
714                     if (tokens && !callable(string))
715                         string = util.compileMacro(string, true);
716                     if (callable(string))
717                         string = string(tokens || {});
718
719                     let lines = string.split(/\r\n|[\r\n]/);
720                     let startLine = context.line;
721
722                     for (var i = 0; i < lines.length && !context.finished; i++) {
723                         // Deal with editors from Silly OSs.
724                         let line = lines[i].replace(/\r$/, "");
725
726                         context.line = startLine + i;
727
728                         // Process escaped new lines
729                         while (i < lines.length && /^\s*\\/.test(lines[i + 1]))
730                             line += "\n" + lines[++i].replace(/^\s*\\/, "");
731
732                         try {
733                             dactyl.execute(line, args);
734                         }
735                         catch (e) {
736                             if (!silent) {
737                                 e.message = context.file + ":" + context.line + ": " + e.message;
738                                 dactyl.reportError(e, true);
739                             }
740                         }
741                     }
742                 });
743             });
744         },
745
746         /**
747          * Lists all user-defined commands matching *filter* and optionally
748          * *hives*.
749          *
750          * @param {string} filter Limits the list to those commands with a name
751          *     matching this anchored substring.
752          * @param {[Hive]} hives List of hives.
753          * @optional
754          */
755         list: function list(filter, hives) {
756             const { commandline, completion } = this.modules;
757             function completerToString(completer) {
758                 if (completer)
759                     return [k for ([k, v] in Iterator(config.completers)) if (completer == completion.closure[v])][0] || "custom";
760                 return "";
761             }
762             // TODO: allow matching of aliases?
763             function cmds(hive) hive._list.filter(cmd => cmd.name.indexOf(filter || "") == 0)
764
765             let hives = (hives || this.userHives).map(h => [h, cmds(h)])
766                                                  .filter(([h, c]) => c.length);
767
768             let list = ["table", {},
769                 ["tr", { highlight: "Title" },
770                     ["td"],
771                     ["td", { style: "padding-right: 1em;" }],
772                     ["td", { style: "padding-right: 1ex;" }, _("title.Name")],
773                     ["td", { style: "padding-right: 1ex;" }, _("title.Args")],
774                     ["td", { style: "padding-right: 1ex;" }, _("title.Range")],
775                     ["td", { style: "padding-right: 1ex;" }, _("title.Complete")],
776                     ["td", { style: "padding-right: 1ex;" }, _("title.Definition")]],
777                 ["col", { style: "min-width: 6em; padding-right: 1em;" }],
778                 hives.map(([hive, cmds]) => let (i = 0) [
779                     ["tr", { style: "height: .5ex;" }],
780                     cmds.map(cmd =>
781                         ["tr", {},
782                             ["td", { highlight: "Title" }, !i++ ? hive.name : ""],
783                             ["td", {}, cmd.bang ? "!" : " "],
784                             ["td", {}, cmd.name],
785                             ["td", {}, cmd.argCount],
786                             ["td", {}, cmd.count ? "0c" : ""],
787                             ["td", {}, completerToString(cmd.completer)],
788                             ["td", {}, cmd.replacementText || "function () { ... }"]]),
789                     ["tr", { style: "height: .5ex;" }]])];
790
791             // E4X-FIXME
792             // if (list.*.length() === list.text().length() + 2)
793             //     dactyl.echomsg(_("command.none"));
794             // else
795             commandline.commandOutput(list);
796         }
797     }),
798
799     /**
800      * @property Indicates that no count was specified for this
801      *     command invocation.
802      * @final
803      */
804     COUNT_NONE: null,
805     /**
806      * @property {number} Indicates that the full buffer range (1,$) was
807      *     specified for this command invocation.
808      * @final
809      */
810     // FIXME: this isn't a count at all
811     COUNT_ALL: -2, // :%...
812
813     /** @property {Iterator(Command)} @private */
814     iterator: function iterator() iter.apply(null, this.hives.array)
815                               .sort((a, b) => (a.serialGroup - b.serialGroup ||
816                                                a.name > b.name))
817                               .iterValues(),
818
819     /** @property {string} The last executed Ex command line. */
820     repeat: null,
821
822     add: function add() {
823         let group = this.builtin;
824         if (!util.isDactyl(Components.stack.caller)) {
825             deprecated.warn(add, "commands.add", "group.commands.add");
826             group = this.user;
827         }
828
829         return group._add.apply(group, arguments);
830     },
831     addUserCommand: deprecated("group.commands.add", { get: function addUserCommand() this.user.closure._add }),
832     getUserCommands: deprecated("iter(group.commands)", function getUserCommands() iter(this.user).toArray()),
833     removeUserCommand: deprecated("group.commands.remove", { get: function removeUserCommand() this.user.closure.remove }),
834
835     /**
836      * Returns the specified command invocation object serialized to
837      * an executable Ex command string.
838      *
839      * @param {Object} args The command invocation object.
840      * @returns {string}
841      */
842     commandToString: function commandToString(args) {
843         let res = [args.command + (args.bang ? "!" : "")];
844
845         let defaults = {};
846         if (args.ignoreDefaults)
847             defaults = array(this.options).map(opt => [opt.names[0], opt.default])
848                                           .toObject();
849
850         for (let [opt, val] in Iterator(args.options || {})) {
851             if (val === undefined)
852                 continue;
853             if (val != null && defaults[opt] === val)
854                 continue;
855
856             let chr = /^-.$/.test(opt) ? " " : "=";
857             if (isArray(val))
858                 opt += chr + Option.stringify.stringlist(val);
859             else if (val != null)
860                 opt += chr + Commands.quote(val);
861             res.push(opt);
862         }
863
864         for (let [, arg] in Iterator(args.arguments || []))
865             res.push(Commands.quote(arg));
866
867         let str = args.literalArg;
868         if (str)
869             res.push(!/\n/.test(str) ? str :
870                      this.serializeHereDoc ? "<<EOF\n" + String.replace(str, /\n$/, "") + "\nEOF"
871                                            : String.replace(str, /\n/g, "\n" + res[0].replace(/./g, " ").replace(/.$/, "\\")));
872         return res.join(" ");
873     },
874
875     /**
876      * Returns the command with matching *name*.
877      *
878      * @param {string} name The name of the command to return. This can be
879      *     any of the command's names.
880      * @returns {Command}
881      */
882     get: function get(name, full) iter(this.hives).map(([i, hive]) => hive.get(name, full))
883                                                   .nth(util.identity, 0),
884
885     /**
886      * Returns true if a command invocation contains a URL referring to the
887      * domain *host*.
888      *
889      * @param {string} command
890      * @param {string} host
891      * @returns {boolean}
892      */
893     hasDomain: function hasDomain(command, host) {
894         try {
895             for (let [cmd, args] in this.subCommands(command))
896                 if (Array.concat(cmd.domains(args)).some(domain => util.isSubdomain(domain, host)))
897                     return true;
898         }
899         catch (e) {
900             util.reportError(e);
901         }
902         return false;
903     },
904
905     /**
906      * Returns true if a command invocation contains private data which should
907      * be cleared when purging private data.
908      *
909      * @param {string} command
910      * @returns {boolean}
911      */
912     hasPrivateData: function hasPrivateData(command) {
913         for (let [cmd, args] in this.subCommands(command))
914             if (cmd.privateData)
915                 return !callable(cmd.privateData) ? cmd.privateData
916                                                   : cmd.privateData(args);
917         return false;
918     },
919
920     // TODO: should it handle comments?
921     //     : it might be nice to be able to specify that certain quoting
922     //     should be disabled E.g. backslash without having to resort to
923     //     using literal etc.
924     //     : error messages should be configurable or else we can ditch
925     //     Vim compatibility but it actually gives useful messages
926     //     sometimes rather than just "Invalid arg"
927     //     : I'm not sure documenting the returned object here, and
928     //     elsewhere, as type Args rather than simply Object makes sense,
929     //     especially since it is further augmented for use in
930     //     Command#action etc.
931     /**
932      * Parses *str* for options and plain arguments.
933      *
934      * The returned *Args* object is an augmented array of arguments.
935      * Any key/value pairs of *extra* will be available and the
936      * following additional properties:
937      *     -opt       - the value of the option -opt if specified
938      *     string     - the original argument string *str*
939      *     literalArg - any trailing literal argument
940      *
941      * Quoting rules:
942      *     '-quoted strings   - only ' and \ itself are escaped
943      *     "-quoted strings   - also ", \n and \t are translated
944      *     non-quoted strings - everything is taken literally apart from "\
945      *                          " and "\\"
946      *
947      * @param {string} str The Ex command-line string to parse. E.g.
948      *     "-x=foo -opt=bar arg1 arg2"
949      * @param {[CommandOption]} options The options accepted. These are specified
950      *      as an array of {@link CommandOption} structures.
951      * @param {string} argCount The number of arguments accepted.
952      *            "0": no arguments
953      *            "1": exactly one argument
954      *            "+": one or more arguments
955      *            "*": zero or more arguments (default if unspecified)
956      *            "?": zero or one arguments
957      * @param {boolean} allowUnknownOptions Whether unspecified options
958      *     should cause an error.
959      * @param {number} literal The index at which any literal arg begins.
960      *     See {@link Command#literal}.
961      * @param {CompletionContext} complete The relevant completion context
962      *     when the args are being parsed for completion.
963      * @param {Object} extra Extra keys to be spliced into the returned
964      *     Args object.
965      * @returns {Args}
966      */
967     parseArgs: function parseArgs(str, params = {}) {
968         const self = this;
969
970         function getNextArg(str, _keepQuotes=keepQuotes) {
971             if (str.substr(0, 2) === "<<" && hereDoc) {
972                 let arg = /^<<(\S*)/.exec(str)[1];
973                 let count = arg.length + 2;
974                 if (complete)
975                     return [count, "", ""];
976                 return [count, self.readHeredoc(arg), ""];
977             }
978
979             let [count, arg, quote] = Commands.parseArg(str, null, _keepQuotes);
980             if (quote == "\\" && !complete)
981                 return [, , , _("error.trailingCharacters", "\\")];
982             if (quote && !complete)
983                 return [, , , _("error.missingQuote", quote)];
984             return [count, arg, quote];
985         }
986
987         try {
988
989             var { allowUnknownOptions, argCount, complete, extra, hereDoc, literal, options, keepQuotes } = params;
990
991             if (!options)
992                 options = [];
993
994             if (!argCount)
995                 argCount = "*";
996
997             var args = params.newArgs ? params.newArgs() : [];
998             args.string = str; // for access to the unparsed string
999
1000             // FIXME!
1001             for (let [k, v] in Iterator(extra || []))
1002                 args[k] = v;
1003
1004             // FIXME: best way to specify these requirements?
1005             var onlyArgumentsRemaining = allowUnknownOptions || options.length == 0; // after a -- has been found
1006             var arg = null;
1007             var i = 0;
1008             var completeOpts;
1009
1010             // XXX
1011             let matchOpts = function matchOpts(arg) {
1012                 // Push possible option matches into completions
1013                 if (complete && !onlyArgumentsRemaining)
1014                     completeOpts = options.filter(opt => (opt.multiple || !Set.has(args, opt.names[0])));
1015             };
1016             let resetCompletions = function resetCompletions() {
1017                 completeOpts = null;
1018                 args.completeArg = null;
1019                 args.completeOpt = null;
1020                 args.completeFilter = null;
1021                 args.completeStart = i;
1022                 args.quote = Commands.complQuote[""];
1023             };
1024             if (complete) {
1025                 resetCompletions();
1026                 matchOpts("");
1027                 args.completeArg = 0;
1028             }
1029
1030             let fail = function fail(error) {
1031                 if (complete)
1032                     complete.message = error;
1033                 else
1034                     util.assert(false, error);
1035             };
1036
1037             outer:
1038             while (i < str.length || complete) {
1039                 var argStart = i;
1040                 let re = /\s*/gy;
1041                 re.lastIndex = i;
1042                 i += re.exec(str)[0].length;
1043
1044                 if (str[i] == "|") {
1045                     args.string = str.slice(0, i);
1046                     args.trailing = str.slice(i + 1);
1047                     break;
1048                 }
1049                 if (i == str.length && !complete)
1050                     break;
1051
1052                 if (complete)
1053                     resetCompletions();
1054
1055                 var sub = str.substr(i);
1056                 if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub)) {
1057                     onlyArgumentsRemaining = true;
1058                     i += 2;
1059                     continue;
1060                 }
1061
1062                 var optname = "";
1063                 if (!onlyArgumentsRemaining) {
1064                     for (let [, opt] in Iterator(options)) {
1065                         for (let [, optname] in Iterator(opt.names)) {
1066                             if (sub.indexOf(optname) == 0) {
1067                                 let count = 0;
1068                                 let invalid = false;
1069                                 let arg, quote, quoted;
1070
1071                                 let sep = sub[optname.length];
1072                                 let argString = sub.substr(optname.length + 1);
1073                                 if (sep == "=" || /\s/.test(sep) && opt.type != CommandOption.NOARG) {
1074                                     [count, quoted, quote, error] = getNextArg(argString, true);
1075                                     arg = Option.dequote(quoted);
1076                                     util.assert(!error, error);
1077
1078                                     // if we add the argument to an option after a space, it MUST not be empty
1079                                     if (sep != "=" && !quote && arg.length == 0 && !complete)
1080                                         arg = null;
1081
1082                                     count++; // to compensate the "=" character
1083                                 }
1084                                 else if (!/\s/.test(sep) && sep != undefined) // this isn't really an option as it has trailing characters, parse it as an argument
1085                                     invalid = true;
1086
1087                                 let context = null;
1088                                 if (!complete && quote)
1089                                     fail(_("command.invalidOptArg", optname, argString));
1090
1091                                 if (!invalid) {
1092                                     if (complete && !/[\s=]/.test(sep))
1093                                         matchOpts(sub);
1094
1095                                     if (complete && count > 0) {
1096                                         args.completeStart += optname.length + 1;
1097                                         args.completeOpt = opt;
1098                                         args.completeFilter = arg;
1099                                         args.quote = Commands.complQuote[quote] || Commands.complQuote[""];
1100                                     }
1101                                     if (!complete || arg != null) {
1102                                         if (opt.type) {
1103                                             let orig = arg;
1104                                             arg = opt.type.parse(arg, quoted);
1105
1106                                             if (complete && isArray(arg)) {
1107                                                 args.completeFilter = arg[arg.length - 1] || "";
1108                                                 args.completeStart += orig.length - args.completeFilter.length;
1109                                             }
1110
1111                                             if (arg == null || (typeof arg == "number" && isNaN(arg))) {
1112                                                 if (!complete || orig != "" || args.completeStart != str.length)
1113                                                     fail(_("command.invalidOptTypeArg", opt.type.description, optname, argString));
1114                                                 if (complete)
1115                                                     complete.highlight(args.completeStart, count - 1, "SPELLCHECK");
1116                                             }
1117                                         }
1118
1119                                         // we have a validator function
1120                                         if (typeof opt.validator == "function") {
1121                                             if (opt.validator(arg, quoted) == false && (arg || !complete)) {
1122                                                 fail(_("command.invalidOptArg", optname, argString));
1123                                                 if (complete) // Always true.
1124                                                     complete.highlight(args.completeStart, count - 1, "SPELLCHECK");
1125                                             }
1126                                         }
1127                                     }
1128
1129                                     if (arg != null || opt.type == CommandOption.NOARG) {
1130                                         // option allowed multiple times
1131                                         if (opt.multiple)
1132                                             args[opt.names[0]] = (args[opt.names[0]] || []).concat(arg);
1133                                         else
1134                                             Class.replaceProperty(args, opt.names[0], opt.type == CommandOption.NOARG || arg);
1135
1136                                         args.explicitOpts[opt.names[0]] = args[opt.names[0]];
1137                                     }
1138
1139                                     i += optname.length + count;
1140                                     if (i == str.length)
1141                                         break outer;
1142                                     continue outer;
1143                                 }
1144                                 // if it is invalid, just fall through and try the next argument
1145                             }
1146                         }
1147                     }
1148                 }
1149
1150                 matchOpts(sub);
1151
1152                 if (complete)
1153                     if (argCount == "0" || args.length > 0 && (/[1?]/.test(argCount)))
1154                         complete.highlight(i, sub.length, "SPELLCHECK");
1155
1156                 if (args.length === literal) {
1157                     if (complete)
1158                         args.completeArg = args.length;
1159
1160                     let re = /(?:\s*(?=\n)|\s*)([^]*)/gy;
1161                     re.lastIndex = argStart || 0;
1162                     sub = re.exec(str)[1];
1163
1164                     // Hack.
1165                     if (sub.substr(0, 2) === "<<" && hereDoc)
1166                         let ([count, arg] = getNextArg(sub)) {
1167                             sub = arg + sub.substr(count);
1168                         };
1169
1170                     args.push(sub);
1171                     args.quote = null;
1172                     break;
1173                 }
1174
1175                 // if not an option, treat this token as an argument
1176                 let [count, arg, quote, error] = getNextArg(sub);
1177                 util.assert(!error, error);
1178
1179                 if (complete) {
1180                     args.quote = Commands.complQuote[quote] || Commands.complQuote[""];
1181                     args.completeFilter = arg || "";
1182                 }
1183                 else if (count == -1)
1184                     fail(_("command.parsing", arg));
1185                 else if (!onlyArgumentsRemaining && sub[0] === "-")
1186                     fail(_("command.invalidOpt", arg));
1187
1188                 if (arg != null)
1189                     args.push(arg);
1190                 if (complete)
1191                     args.completeArg = args.length - 1;
1192
1193                 i += count;
1194                 if (count <= 0 || i == str.length)
1195                     break;
1196             }
1197
1198             if (complete && args.trailing == null) {
1199                 if (args.completeOpt) {
1200                     let opt = args.completeOpt;
1201                     let context = complete.fork(opt.names[0], args.completeStart);
1202                     let arg = args.explicitOpts[opt.names[0]];
1203                     context.filter = args.completeFilter;
1204
1205                     if (isArray(arg))
1206                         context.filters.push(item => arg.indexOf(item.text) === -1);
1207
1208                     if (typeof opt.completer == "function")
1209                         var compl = opt.completer(context, args);
1210                     else
1211                         compl = opt.completer || [];
1212
1213                     context.title = [opt.names[0]];
1214                     context.quote = args.quote;
1215                     if (compl)
1216                         context.completions = compl;
1217                 }
1218                 complete.advance(args.completeStart);
1219                 complete.keys = {
1220                     text: "names",
1221                     description: function (opt) messages.get(["command", params.name, "options", opt.names[0], "description"].join("."), opt.description)
1222                 };
1223                 complete.title = ["Options"];
1224                 if (completeOpts)
1225                     complete.completions = completeOpts;
1226             }
1227
1228             if (args.verify)
1229                 args.verify();
1230
1231             return args;
1232         }
1233         catch (e if complete && e instanceof FailedAssertion) {
1234             complete.message = e;
1235             return args;
1236         }
1237     },
1238
1239     nameRegexp: util.regexp(literal(/*
1240             [^
1241                 0-9
1242                 <forbid>
1243             ]
1244             [^ <forbid> ]*
1245         */), "gx", {
1246         forbid: util.regexp(String.replace(literal(/*
1247             U0000-U002c // U002d -
1248             U002e-U002f
1249             U003a-U0040 // U0041-U005a a-z
1250             U005b-U0060 // U0061-U007a A-Z
1251             U007b-U00bf
1252             U02b0-U02ff // Spacing Modifier Letters
1253             U0300-U036f // Combining Diacritical Marks
1254             U1dc0-U1dff // Combining Diacritical Marks Supplement
1255             U2000-U206f // General Punctuation
1256             U20a0-U20cf // Currency Symbols
1257             U20d0-U20ff // Combining Diacritical Marks for Symbols
1258             U2400-U243f // Control Pictures
1259             U2440-U245f // Optical Character Recognition
1260             U2500-U257f // Box Drawing
1261             U2580-U259f // Block Elements
1262             U2700-U27bf // Dingbats
1263             Ufe20-Ufe2f // Combining Half Marks
1264             Ufe30-Ufe4f // CJK Compatibility Forms
1265             Ufe50-Ufe6f // Small Form Variants
1266             Ufe70-Ufeff // Arabic Presentation Forms-B
1267             Uff00-Uffef // Halfwidth and Fullwidth Forms
1268             Ufff0-Uffff // Specials
1269         */), /U/g, "\\u"), "x")
1270     }),
1271
1272     validName: Class.Memoize(function validName() util.regexp("^" + this.nameRegexp.source + "$")),
1273
1274     commandRegexp: Class.Memoize(function commandRegexp() util.regexp(literal(/*
1275             ^
1276             (?P<spec>
1277                 (?P<prespace> [:\s]*)
1278                 (?P<count>    (?:\d+ | %)? )
1279                 (?P<fullCmd>
1280                     (?: (?P<group> <name>) : )?
1281                     (?P<cmd>      (?:-? [()] | <name> | !)? ))
1282                 (?P<bang>     !?)
1283                 (?P<space>    \s*)
1284             )
1285             (?P<args>
1286                 (?:. | \n)*?
1287             )?
1288             $
1289         */), "x", {
1290             name: this.nameRegexp
1291         })),
1292
1293     /**
1294      * Parses a complete Ex command.
1295      *
1296      * The parsed string is returned as an Array like
1297      * [count, command, bang, args]:
1298      *     count   - any count specified
1299      *     command - the Ex command name
1300      *     bang    - whether the special "bang" version was called
1301      *     args    - the commands full argument string
1302      * E.g. ":2foo! bar" -> [2, "foo", true, "bar"]
1303      *
1304      * @param {string} str The Ex command line string.
1305      * @returns {Array}
1306      */
1307     // FIXME: why does this return an Array rather than Object?
1308     parseCommand: function parseCommand(str) {
1309         // remove comments
1310         str.replace(/\s*".*$/, "");
1311
1312         let matches = this.commandRegexp.exec(str);
1313         if (!matches)
1314             return [];
1315
1316         let { spec, count, group, cmd, bang, space, args } = matches;
1317         if (!cmd && bang)
1318             [cmd, bang] = [bang, cmd];
1319
1320         if (!cmd || args && args[0] != "|" && !(space || cmd == "!"))
1321             return [];
1322
1323         // parse count
1324         if (count)
1325             count = count == "%" ? this.COUNT_ALL : parseInt(count, 10);
1326         else
1327             count = this.COUNT_NONE;
1328
1329         return [count, cmd, !!bang, args || "", spec.length, group];
1330     },
1331
1332     parseCommands: function parseCommands(str, complete) {
1333         const { contexts } = this.modules;
1334         do {
1335             let [count, cmd, bang, args, len, group] = commands.parseCommand(str);
1336             if (!group)
1337                 var command = this.get(cmd || "");
1338             else if (group = contexts.getGroup(group, "commands"))
1339                 command = group.get(cmd || "");
1340
1341             if (command == null) {
1342                 yield [null, { commandString: str }];
1343                 return;
1344             }
1345
1346             if (complete)
1347                 var context = complete.fork(command.name).fork("opts", len);;
1348
1349             if (!complete || /(\w|^)[!\s]/.test(str))
1350                 args = command.parseArgs(args, context, { count: count, bang: bang });
1351             else
1352                 args = this.parseArgs(args, { extra: { count: count, bang: bang } });
1353             args.context = this.context;
1354             args.commandName = cmd;
1355             args.commandString = str.substr(0, len) + args.string;
1356             str = args.trailing;
1357             yield [command, args];
1358             if (args.break)
1359                 break;
1360         }
1361         while (str);
1362     },
1363
1364     subCommands: function subCommands(command) {
1365         let commands = [command];
1366         while (command = commands.shift())
1367             try {
1368                 for (let [command, args] in this.parseCommands(command)) {
1369                     if (command) {
1370                         yield [command, args];
1371                         if (command.subCommand && args[command.subCommand])
1372                             commands.push(args[command.subCommand]);
1373                     }
1374                 }
1375             }
1376             catch (e) {}
1377     },
1378
1379     /** @property */
1380     get complQuote() Commands.complQuote,
1381
1382     /** @property */
1383     get quoteArg() Commands.quoteArg // XXX: better somewhere else?
1384
1385 }, {
1386     // returns [count, parsed_argument]
1387     parseArg: function parseArg(str, sep, keepQuotes) {
1388         let arg = "";
1389         let quote = null;
1390         let len = str.length;
1391
1392         function fixEscapes(str) str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4}|(.))/g,
1393                                              (m, n1) => n1 || m);
1394
1395         // Fix me.
1396         if (isString(sep))
1397             sep = RegExp(sep);
1398         sep = sep != null ? sep : /\s/;
1399         let re1 = RegExp("^" + (sep.source === "" ? "(?!)" : sep.source));
1400         let re2 = RegExp(/^()((?:[^\\S"']|\\.)+)((?:\\$)?)/.source.replace("S", sep.source));
1401
1402         while (str.length && !re1.test(str)) {
1403             let res;
1404             if ((res = re2.exec(str)))
1405                 arg += keepQuotes ? res[0] : res[2].replace(/\\(.)/g, "$1");
1406             else if ((res = /^(")((?:[^\\"]|\\.)*)("?)/.exec(str)))
1407                 arg += keepQuotes ? res[0] : JSON.parse(fixEscapes(res[0]) + (res[3] ? "" : '"'));
1408             else if ((res = /^(')((?:[^']|'')*)('?)/.exec(str)))
1409                 arg += keepQuotes ? res[0] : res[2].replace("''", "'", "g");
1410             else
1411                 break;
1412
1413             if (!res[3])
1414                 quote = res[1];
1415             if (!res[1])
1416                 quote = res[3];
1417             str = str.substr(res[0].length);
1418         }
1419
1420         return [len - str.length, arg, quote];
1421     },
1422
1423     quote: function quote(str) Commands.quoteArg[
1424         /[\b\f\n\r\t]/.test(str)   ? '"' :
1425         /[\s"'\\]|^$|^-/.test(str) ? "'"
1426                                    : ""](str)
1427 }, {
1428     completion: function initCompletion(dactyl, modules, window) {
1429         const { completion, contexts } = modules;
1430
1431         completion.command = function command(context, group) {
1432             context.title = ["Command"];
1433             context.keys = { text: "longNames", description: "description" };
1434             if (group)
1435                 context.generate = () => group._list;
1436             else
1437                 context.generate = () => modules.commands.hives.map(h => h._list).flatten();
1438         };
1439
1440         // provides completions for ex commands, including their arguments
1441         completion.ex = function ex(context) {
1442             const { commands } = modules;
1443
1444             // if there is no space between the command name and the cursor
1445             // then get completions of the command name
1446             for (var [command, args] in commands.parseCommands(context.filter, context))
1447                 if (args.trailing)
1448                     context.advance(args.commandString.length + 1);
1449             if (!args)
1450                 args = { commandString: context.filter };
1451
1452             let match = commands.commandRegexp.exec(args.commandString);
1453             if (!match)
1454                 return;
1455
1456             if (match.group)
1457                 context.advance(match.group.length + 1);
1458
1459             context.advance(match.prespace.length + match.count.length);
1460             if (!(match.bang || match.space)) {
1461                 context.fork("", 0, this, "command", match.group && contexts.getGroup(match.group, "commands"));
1462                 return;
1463             }
1464
1465             // dynamically get completions as specified with the command's completer function
1466             context.highlight();
1467             if (!command) {
1468                 context.message = _("command.noSuch", match.cmd);
1469                 context.highlight(0, match.cmd.length, "SPELLCHECK");
1470                 return;
1471             }
1472
1473             let cmdContext = context.fork(command.name + "/args", match.fullCmd.length + match.bang.length + match.space.length);
1474             try {
1475                 if (!cmdContext.waitingForTab) {
1476                     if (!args.completeOpt && command.completer && args.completeStart != null) {
1477                         cmdContext.advance(args.completeStart);
1478                         cmdContext.quote = args.quote;
1479                         cmdContext.filter = args.completeFilter;
1480                         command.completer.call(command, cmdContext, args);
1481                     }
1482                 }
1483             }
1484             catch (e) {
1485                 util.reportError(e);
1486                 cmdContext.message = _("error.error", e);
1487             }
1488         };
1489
1490         completion.exMacro = function exMacro(context, args, cmd) {
1491             if (!cmd.action.macro)
1492                 return;
1493             let { macro } = cmd.action;
1494
1495             let start = "«%-d-]'", end = "'[-d-%»";
1496
1497             let n = /^\d+$/.test(cmd.argCount) ? parseInt(cmd.argCount) : 12;
1498             for (let i = args.completeArg; i < n; i++)
1499                 args[i] = start + i + end;
1500
1501             let params = {
1502                 args: { __proto__: args, toString: function () this.join(" ") },
1503                 bang:  args.bang ? "!" : "",
1504                 count: args.count
1505             };
1506
1507             if (!macro.valid(params))
1508                 return;
1509
1510             let str = macro(params);
1511             let idx = str.indexOf(start);
1512             if (!~idx || !/^(')?(\d+)'/.test(str.substr(idx + start.length))
1513                     || RegExp.$2 != args.completeArg)
1514                 return;
1515
1516             let quote = RegExp.$2;
1517             context.quote = null;
1518             context.offset -= idx;
1519             context.filter = str.substr(0, idx) + (quote ? Option.quote : util.identity)(context.filter);
1520
1521             context.fork("ex", 0, completion, "ex");
1522         };
1523
1524         completion.userCommand = function userCommand(context, group) {
1525             context.title = ["User Command", "Definition"];
1526             context.keys = { text: "name", description: "replacementText" };
1527             context.completions = group || modules.commands.user;
1528         };
1529     },
1530
1531     commands: function initCommands(dactyl, modules, window) {
1532         const { commands, contexts } = modules;
1533
1534         commands.add(["(", "-("], "",
1535             function (args) { dactyl.echoerr(_("dactyl.cheerUp")); },
1536             { hidden: true });
1537         commands.add([")", "-)"], "",
1538             function (args) { dactyl.echoerr(_("dactyl.somberDown")); },
1539             { hidden: true });
1540
1541         commands.add(["com[mand]"],
1542             "List or define commands",
1543             function (args) {
1544                 let cmd = args[0];
1545
1546                 util.assert(!cmd || cmd.split(",").every(commands.validName.closure.test),
1547                             _("command.invalidName", cmd));
1548
1549                 if (args.length <= 1)
1550                     commands.list(cmd, args.explicitOpts["-group"] ? [args["-group"]] : null);
1551                 else {
1552                     util.assert(args["-group"].modifiable,
1553                                 _("group.cantChangeBuiltin", _("command.commands")));
1554
1555                     let completer = args["-complete"];
1556                     let completerFunc = function (context, args) modules.completion.exMacro(context, args, this);
1557
1558                     if (completer) {
1559                         if (/^custom,/.test(completer)) {
1560                             completer = completer.substr(7);
1561
1562                             if (contexts.context)
1563                                 var ctxt = update({}, contexts.context || {});
1564                             completerFunc = function (context) {
1565                                 var result = contexts.withSavedValues(["context"], function () {
1566                                     contexts.context = ctxt;
1567                                     return dactyl.userEval(completer);
1568                                 });
1569                                 if (callable(result))
1570                                     return result.apply(this, arguments);
1571                                 else
1572                                     return context.completions = result;
1573                             };
1574                         }
1575                         else
1576                             completerFunc = context => modules.completion.closure[config.completers[completer]](context);
1577                     }
1578
1579                     let added = args["-group"].add(cmd.split(","),
1580                                     args["-description"],
1581                                     contexts.bindMacro(args, "-ex",
1582                                         function makeParams(args, modifiers) ({
1583                                             args: {
1584                                                 __proto__: args,
1585                                                 toString: function () this.string
1586                                             },
1587                                             bang:  this.bang && args.bang ? "!" : "",
1588                                             count: this.count && args.count
1589                                         })),
1590                                     {
1591                                         argCount: args["-nargs"],
1592                                         bang: args["-bang"],
1593                                         count: args["-count"],
1594                                         completer: completerFunc,
1595                                         literal: args["-literal"],
1596                                         persist: !args["-nopersist"],
1597                                         replacementText: args.literalArg,
1598                                         context: contexts.context && update({}, contexts.context)
1599                                     }, args.bang);
1600
1601                     if (!added)
1602                         dactyl.echoerr(_("command.exists"));
1603                 }
1604             }, {
1605                 bang: true,
1606                 completer: function (context, args) {
1607                     const { completion } = modules;
1608                     if (args.completeArg == 0)
1609                         completion.userCommand(context, args["-group"]);
1610                     else
1611                         args["-javascript"] ? completion.javascript(context) : completion.ex(context);
1612                 },
1613                 hereDoc: true,
1614                 options: [
1615                     { names: ["-bang", "-b"],  description: "Command may be followed by a !" },
1616                     { names: ["-count", "-c"], description: "Command may be preceded by a count" },
1617                     {
1618                         // TODO: "E180: invalid complete value: " + arg
1619                         names: ["-complete", "-C"],
1620                         description: "The argument completion function",
1621                         completer: function (context) [[k, ""] for ([k, v] in Iterator(config.completers))],
1622                         type: CommandOption.STRING,
1623                         validator: function (arg) arg in config.completers || /^custom,/.test(arg),
1624                     },
1625                     {
1626                         names: ["-description", "-desc", "-d"],
1627                         description: "A user-visible description of the command",
1628                         default: "User-defined command",
1629                         type: CommandOption.STRING
1630                     },
1631                     contexts.GroupFlag("commands"),
1632                     {
1633                         names: ["-javascript", "-js", "-j"],
1634                         description: "Execute the definition as JavaScript rather than Ex commands"
1635                     },
1636                     {
1637                         names: ["-literal", "-l"],
1638                         description: "Process the specified argument ignoring any quoting or meta characters",
1639                         type: CommandOption.INT
1640                     },
1641                     {
1642                         names: ["-nargs", "-a"],
1643                         description: "The allowed number of arguments",
1644                         completer: [["0", "No arguments are allowed (default)"],
1645                                     ["1", "One argument is allowed"],
1646                                     ["*", "Zero or more arguments are allowed"],
1647                                     ["?", "Zero or one argument is allowed"],
1648                                     ["+", "One or more arguments are allowed"]],
1649                         default: "0",
1650                         type: CommandOption.STRING,
1651                         validator: bind("test", /^[01*?+]$/)
1652                     },
1653                     {
1654                         names: ["-nopersist", "-n"],
1655                         description: "Do not save this command to an auto-generated RC file"
1656                     }
1657                 ],
1658                 literal: 1,
1659
1660                 serialize: function () array(commands.userHives)
1661                     .filter(h => h.persist)
1662                     .map(hive => [
1663                         {
1664                             command: this.name,
1665                             bang: true,
1666                             options: iter([v, typeof cmd[k] == "boolean" ? null : cmd[k]]
1667                                           // FIXME: this map is expressed multiple times
1668                                           for ([k, v] in Iterator({
1669                                               argCount: "-nargs",
1670                                               bang: "-bang",
1671                                               count: "-count",
1672                                               description: "-description"
1673                                           }))
1674                                           if (cmd[k])).toObject(),
1675                             arguments: [cmd.name],
1676                             literalArg: cmd.action,
1677                             ignoreDefaults: true
1678                         }
1679                         for (cmd in hive) if (cmd.persist)
1680                     ])
1681                     .flatten().array
1682             });
1683
1684         commands.add(["delc[ommand]"],
1685             "Delete the specified user-defined command",
1686             function (args) {
1687                 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
1688                 let name = args[0];
1689
1690                 if (args.bang)
1691                     args["-group"].clear();
1692                 else if (args["-group"].get(name))
1693                     args["-group"].remove(name);
1694                 else
1695                     dactyl.echoerr(_("command.noSuchUser", name));
1696             }, {
1697                 argCount: "?",
1698                 bang: true,
1699                 completer: function (context, args) modules.completion.userCommand(context, args["-group"]),
1700                 options: [contexts.GroupFlag("commands")]
1701             });
1702
1703         commands.add(["comp[letions]"],
1704             "List the completion results for a given command substring",
1705             function (args) { modules.completion.listCompleter("ex", args[0]); },
1706             {
1707                 argCount: "1",
1708                 completer: function (context, args) modules.completion.ex(context),
1709                 literal: 0
1710             });
1711
1712         dactyl.addUsageCommand({
1713             name: ["listc[ommands]", "lc"],
1714             description: "List all Ex commands along with their short descriptions",
1715             index: "ex-cmd",
1716             iterate: function (args) commands.iterator().map(function (cmd) ({
1717                 __proto__: cmd,
1718                 columns: [
1719                     cmd.hive == commands.builtin ? "" : ["span", { highlight: "Object", style: "padding-right: 1em;" },
1720                                                             cmd.hive.name]
1721                 ]
1722             })),
1723             iterateIndex: function (args) let (tags = help.tags)
1724                 this.iterate(args).filter(cmd => (cmd.hive === commands.builtin || Set.has(tags, cmd.helpTag))),
1725             format: {
1726                 headings: ["Command", "Group", "Description"],
1727                 description: function (cmd) template.linkifyHelp(cmd.description + (cmd.replacementText ? ": " + cmd.action : "")),
1728                 help: function (cmd) ":" + cmd.name
1729             }
1730         });
1731
1732         commands.add(["y[ank]"],
1733             "Yank the output of the given command to the clipboard",
1734             function (args) {
1735                 let cmd = /^:/.test(args[0]) ? args[0] : ":echo " + args[0];
1736
1737                 let res = modules.commandline.withOutputToString(commands.execute, commands, cmd);
1738
1739                 dactyl.clipboardWrite(res);
1740
1741                 let lines = res.split("\n").length;
1742                 dactyl.echomsg(_("command.yank.yankedLine" + (lines == 1 ? "" : "s"), lines));
1743             },
1744             {
1745                 argCount: "1",
1746                 completer: function (context) modules.completion[/^:/.test(context.filter) ? "ex" : "javascript"](context),
1747                 literal: 0
1748             });
1749     },
1750     javascript: function initJavascript(dactyl, modules, window) {
1751         const { JavaScript, commands } = modules;
1752
1753         JavaScript.setCompleter([CommandHive.prototype.get, CommandHive.prototype.remove],
1754                                 [function () [[c.names, c.description] for (c in this)]]);
1755         JavaScript.setCompleter([Commands.prototype.get],
1756                                 [function () [[c.names, c.description] for (c in this.iterator())]]);
1757     },
1758     mappings: function initMappings(dactyl, modules, window) {
1759         const { commands, mappings, modes } = modules;
1760
1761         mappings.add([modes.COMMAND],
1762             ["@:"], "Repeat the last Ex command",
1763             function ({ count }) {
1764                 if (commands.repeat) {
1765                     for (let i in util.interruptibleRange(0, Math.max(count, 1), 100))
1766                         dactyl.execute(commands.repeat);
1767                 }
1768                 else
1769                     dactyl.echoerr(_("command.noPrevious"));
1770             },
1771             { count: true });
1772     }
1773 });
1774
1775 let quote = function quote(q, list, map = Commands.quoteMap) {
1776     let re = RegExp("[" + list + "]", "g");
1777     function quote(str) (q + String.replace(str, re, $0 => ($0 in map ? map[$0] : ("\\" + $0)))
1778                            + q);
1779     quote.list = list;
1780     return quote;
1781 };
1782
1783 Commands.quoteMap = {
1784     "\n": "\\n",
1785     "\t": "\\t"
1786 };
1787
1788 Commands.quoteArg = {
1789     '"': quote('"', '\n\t"\\\\'),
1790     "'": quote("'", "'", { "'": "''" }),
1791     "":  quote("",  "|\\\\\\s'\"")
1792 };
1793 Commands.complQuote = {
1794     '"': ['"', quote("", Commands.quoteArg['"'].list), '"'],
1795     "'": ["'", quote("", Commands.quoteArg["'"].list), "'"],
1796     "":  ["", Commands.quoteArg[""], ""]
1797 };
1798
1799 Commands.parseBool = function (arg) {
1800     if (/^(true|1|on)$/i.test(arg))
1801         return true;
1802     if (/^(false|0|off)$/i.test(arg))
1803         return false;
1804     return NaN;
1805 };
1806
1807 endModule();
1808
1809 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1810
1811 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: