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