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>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
11 defineModule("commands", {
12 exports: ["ArgType", "Command", "Commands", "CommandOption", "Ex", "commands"],
13 require: ["contexts", "messages", "util"]
16 lazyRequire("help", ["help"]);
17 lazyRequire("options", ["Option"]);
18 lazyRequire("template", ["template"]);
21 * A structure representing the options available for a command.
23 * Do NOT create instances of this class yourself, use the helper method
24 * {@see Commands#add} instead
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
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);
53 var ArgType = Struct("description", "parse");
54 update(CommandOption, {
56 * @property {object} The option argument is unspecified. Any argument
57 * is accepted and caller is responsible for parsing the return
64 * @property {object} The option doesn't accept an argument.
67 NOARG: ArgType("no arg", arg => !arg || null),
69 * @property {object} The option accepts a boolean argument.
72 BOOL: ArgType("boolean", function parseBoolArg(val) Commands.parseBool(val)),
74 * @property {object} The option accepts a string argument.
77 STRING: ArgType("string", val => val),
79 * @property {object} The option accepts a stringmap argument.
82 STRINGMAP: ArgType("stringmap", (val, quoted) => Option.parse.stringmap(quoted)),
84 * @property {object} The option accepts an integer argument.
87 INT: ArgType("int", function parseIntArg(val) parseInt(val)),
89 * @property {object} The option accepts a float argument.
92 FLOAT: ArgType("float", function parseFloatArg(val) parseFloat(val)),
94 * @property {object} The option accepts a string list argument.
98 LIST: ArgType("list", function parseListArg(arg, quoted) Option.splitList(quoted))
102 * A class representing Ex commands. Instances are created by
103 * the {@link Commands} class.
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}
127 var Command = Class("Command", {
128 init: function init(specs, description, action, extraInfo) {
129 specs = Array.concat(specs); // XXX
132 this.description = description;
133 this.action = action;
135 if (extraInfo.options)
136 this._options = extraInfo.options;
137 delete extraInfo.options;
140 this.update(extraInfo);
143 get toStringParams() [this.name, this.hive.name],
145 get identifier() this.hive.prefix + this.name,
147 get helpTag() ":" + this.name,
149 get lastCommand() this._lastCommand || this.modules.commandline.command,
150 set lastCommand(val) { this._lastCommand = val; },
153 * Execute this command.
155 * @param {Args} args The Args object passed to {@link #action}.
156 * @param {Object} modifiers Any modifiers to be passed to {@link #action}.
158 execute: function execute(args, modifiers = {}) {
159 const { dactyl } = this.modules;
161 let context = args.context;
163 this.warn(context, "deprecated", _("warn.deprecated", ":" + this.name, this.deprecated));
165 if (args.count != null && !this.count)
166 throw FailedAssertion(_("command.noCount"));
167 if (args.bang && !this.bang)
168 throw FailedAssertion(_("command.noBang"));
170 args.doc = this.hive.group.lastDocument;
172 return !dactyl.trapErrors(function exec() {
173 let extra = this.hive.argsExtra(args);
175 for (let k in properties(extra))
177 Object.defineProperty(args, k, Object.getOwnPropertyDescriptor(extra, k));
180 this.always(args, modifiers);
182 if (!context || !context.noExecute)
183 this.action(args, modifiers);
188 * Returns whether this command may be invoked via *name*.
190 * @param {string} name The candidate name.
193 hasName: function hasName(name) Command.hasName(this.parsedSpecs, name),
196 * A helper function to parse an argument string.
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
202 * @param {Object} extra Extra keys to be spliced into the
203 * returned Args object.
205 * @see Commands#parseArgs
207 parseArgs: function parseArgs(args, complete, extra) this.modules.commands.parseArgs(args, {
213 complained: Class.Memoize(function () ({})),
216 * @property {[string]} All of this command's name specs. e.g., "com[mand]"
219 parsedSpecs: Class.Memoize(function () Command.parseSpecs(this.specs)),
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]))),
225 * @property {[string]} All of this command's long names, e.g., "command"
227 longNames: Class.Memoize(function () this.parsedSpecs.map(n => n[0])),
229 /** @property {string} The command's canonical name. */
230 name: Class.Memoize(function () this.longNames[0]),
232 /** @property {[string]} All of this command's long and short names. */
233 names: Class.Memoize(function () this.names = array.flatten(this.parsedSpecs)),
235 /** @property {string} This command's description, as shown in :listcommands */
236 description: Messages.Localized(""),
238 /** @property {string|null} If set, the deprecation message for this command. */
239 deprecated: Messages.Localized(null),
242 * @property {function (Args)} The function called to execute this command.
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.
254 * @property {string} This command's argument count spec.
255 * @see Commands#parseArguments
260 * @property {function (CompletionContext, Args)} This command's completer.
261 * @see CompletionContext
265 /** @property {boolean} Whether this command accepts a here document. */
269 * @property {boolean} Whether this command may be called with a bang,
275 * @property {boolean} Whether this command may be called with a count,
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
286 domains: function (args) [],
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.
298 * @property {Array} The options this command takes.
299 * @see Commands@parseArguments
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]];
309 optionMap: Class.Memoize(function () array(this.options)
310 .map(opt => opt.names.map(name => [name, opt]))
311 .flatten().toObject()),
313 newArgs: function newArgs(base) {
316 res.__proto__ = this.argsPrototype;
320 argsPrototype: Class.Memoize(function argsPrototype() {
321 let res = update([], {
322 __iterator__: function AP__iterator__() array.iterItems(this),
326 explicitOpts: Class.Memoize(function () ({})),
328 has: function AP_has(opt) Set.has(this.explicitOpts, opt) || typeof opt === "number" && Set.has(this, opt),
330 get literalArg() this.command.literal != null && this[this.command.literal] || "",
332 // TODO: string: Class.Memoize(function () { ... }),
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"));
340 util.assert((this.length == 0 || this.command.argCount !== "0") &&
341 (this.length <= 1 || !/^[01?]$/.test(this.command.argCount)),
342 _("error.trailingCharacters"));
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 };
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);
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
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.
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.
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.
390 * @property {string} For commands defined via :command, contains the Ex
391 * command line to be executed upon invocation.
393 replacementText: null,
396 * Warns of a misuse of this command once per warning type per file.
398 * @param {object} context The calling context.
399 * @param {string} type The type of warning.
400 * @param {string} warning The warning message.
402 warn: function warn(context, type, message) {
403 let loc = !context ? "" : [context.file, context.line, " "].join(":");
405 if (!Set.add(this.complained, type + ":" + (context ? context.file : "[Command Line]")))
406 this.modules.dactyl.warn(loc + message);
409 hasName: function hasName(specs, name)
410 specs.some(([long, short]) =>
411 name.indexOf(short) == 0 && long.indexOf(name) == 0),
413 // TODO: do we really need more than longNames as a convenience anyway?
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"]]
419 * @param {Array} specs An array of command name specs to parse.
422 parseSpecs: function parseSpecs(specs) {
423 return specs.map(function (spec) {
424 let [, head, tail] = /([^[]+)(?:\[(.*)])?/.exec(spec);
425 return tail ? [head + tail, head] : [head];
431 var Ex = Module("Ex", {
432 Local: function Local(dactyl, modules, window) ({
433 get commands() modules.commands,
434 get context() modules.contexts.context
437 _args: function E_args(cmd, args) {
438 args = Array.slice(args);
440 let res = cmd.newArgs({ context: this.context });
441 if (isObject(args[0]))
442 for (let [k, v] in Iterator(args.shift()))
448 let opt = cmd.optionMap["-" + k];
449 let val = opt.type && opt.type.parse(v);
451 util.assert(val != null && (typeof val !== "number" || !isNaN(val)),
452 _("option.noSuch", k));
454 Class.replaceProperty(res, opt.names[0], val);
455 res.explicitOpts[opt.names[0]] = val;
457 for (let [i, val] in array.iterItems(args))
458 res[i] = String(val);
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);
470 _run: function E_run(name) {
472 let cmd = this.commands.get(name);
473 util.assert(cmd, _("command.noSuch"));
475 return update(function exCommand(options) {
476 let args = self._args(cmd, arguments);
478 return cmd.execute(args);
480 dactylCompleter: self._complete(cmd)
484 __noSuchMethod__: function __noSuchMethod__(meth, args) this._run(meth).apply(this, args)
487 var CommandHive = Class("CommandHive", Contexts.Hive, {
488 init: function init(group) {
489 init.supercall(this, group);
497 * Caches this command hive.
500 cache: function cache() {
502 let { cache } = this.modules;
505 let cached = cache.get(this.cacheKey, function () {
507 this.modules.moduleManager.initDependencies("commands");
510 for (let [name, cmd] in Iterator(self._map))
511 if (cmd.sourceModule)
512 map[name] = { sourceModule: cmd.sourceModule, isPlaceholder: true };
515 for (let cmd in values(self._list))
516 for each (let spec in cmd.parsedSpecs)
517 specs.push(spec.concat(cmd.name));
519 return { map: map, specs: specs };
522 let cached = cache.get(this.cacheKey);
524 this._specs = cached.specs;
525 for (let [k, v] in Iterator(cached.map))
530 get cacheKey() "commands/hives/" + this.name + ".json",
532 /** @property {Iterator(Command)} @private */
533 __iterator__: function __iterator__() {
535 this.modules.initDependencies("commands");
537 return array.iterValues(this._list.sort((a, b) => a.name > b.name));
540 /** @property {string} The last executed Ex command line. */
544 * Adds a new command to the builtin hive. Accessible only to core dactyl
545 * code. Plugins should use group.commands.add instead.
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.
553 * @param {boolean} replace Replace an existing command of the same name.
556 add: function add(specs, description, action, extra = {}, replace = false) {
557 const { commands, contexts } = this.modules;
559 if (!extra.definedAt)
560 extra.definedAt = contexts.getCaller(Components.stack.caller);
561 if (!extra.sourceModule)
562 extra.sourceModule = commands.currentDependency;
565 extra.parsedSpecs = Command.parseSpecs(specs);
567 let names = array.flatten(extra.parsedSpecs);
570 if (this.name != "builtin") {
571 util.assert(!names.some(name => name in commands.builtin._map),
572 _("command.cantReplace", name));
574 util.assert(replace || names.every(name => !(name in this._map)),
575 _("command.wontReplace", name));
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)
584 let closure = () => this._map[name];
586 memoize(this._map, name, () => commands.Command(specs, description, action, extra));
588 memoize(this._list, this._list.length, closure);
589 for (let alias in values(names.slice(1)))
590 memoize(this._map, alias, closure);
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);
602 * Clear all commands.
605 clear: function clear() {
606 util.assert(this.group.modifiable, _("command.cantDelete"));
612 * Returns the command with matching *name*.
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.
620 get: function get(name, full) {
621 let cmd = this._map[name]
622 || !full && array.nth(this._list, cmd => cmd.hasName(name), 0)
626 let name = array.nth(this.specs, spec => Command.hasName(spec, name), 0);
627 return name && this.get(name);
630 if (cmd && cmd.isPlaceholder) {
631 this.modules.moduleManager.initDependencies("commands", [cmd.sourceModule]);
632 cmd = this._map[name];
638 * Remove the user-defined command with matching *name*.
640 * @param {string} name The name of the command to remove. This can be
641 * any of the command's names.
643 remove: function remove(name) {
644 util.assert(this.group.modifiable, _("command.cantDelete"));
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];
656 var Commands = Module("commands", {
660 Local: function Local(dactyl, modules, window) let ({ Group, contexts } = modules) ({
661 init: function init() {
662 this.Command = Class("Command", Command, { modules: modules });
664 hives: contexts.Hives("commands", Class("CommandHive", CommandHive, { modules: modules })),
665 user: contexts.hives.commands.user,
666 builtin: contexts.hives.commands.builtin
670 reallyInit: function reallyInit() {
672 this.builtin.cache();
674 this.modules.moduleManager.initDependencies("commands");
677 get context() contexts.context,
679 get readHeredoc() modules.io.readHeredoc,
681 get allHives() contexts.allGroups.commands,
683 get userHives() this.allHives.filter(h => h !== this.builtin),
686 * Executes an Ex command script.
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
693 * @param {object} context An object containing information about
694 * the file that is being or has been sourced to obtain the
697 execute: function execute(string, tokens, silent, args, context) {
698 contexts.withContext(context || this.context || { file: "[Command Line]", line: 1 },
700 modules.io.withSavedValues(["readHeredoc"], function () {
701 this.readHeredoc = function readHeredoc(end) {
703 contexts.context.line++;
704 while (++i < lines.length) {
705 if (lines[i] === end)
706 return res.join("\n");
709 util.assert(false, _("command.eof", end));
712 args = update({}, args || {});
714 if (tokens && !callable(string))
715 string = util.compileMacro(string, true);
716 if (callable(string))
717 string = string(tokens || {});
719 let lines = string.split(/\r\n|[\r\n]/);
720 let startLine = context.line;
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$/, "");
726 context.line = startLine + i;
728 // Process escaped new lines
729 while (i < lines.length && /^\s*\\/.test(lines[i + 1]))
730 line += "\n" + lines[++i].replace(/^\s*\\/, "");
733 dactyl.execute(line, args);
737 e.message = context.file + ":" + context.line + ": " + e.message;
738 dactyl.reportError(e, true);
747 * Lists all user-defined commands matching *filter* and optionally
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.
755 list: function list(filter, hives) {
756 const { commandline, completion } = this.modules;
757 function completerToString(completer) {
759 return [k for ([k, v] in Iterator(config.completers)) if (completer == completion.closure[v])][0] || "custom";
762 // TODO: allow matching of aliases?
763 function cmds(hive) hive._list.filter(cmd => cmd.name.indexOf(filter || "") == 0)
765 let hives = (hives || this.userHives).map(h => [h, cmds(h)])
766 .filter(([h, c]) => c.length);
768 let list = ["table", {},
769 ["tr", { highlight: "Title" },
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;" }],
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;" }]])];
792 // if (list.*.length() === list.text().length() + 2)
793 // dactyl.echomsg(_("command.none"));
795 commandline.commandOutput(list);
800 * @property Indicates that no count was specified for this
801 * command invocation.
806 * @property {number} Indicates that the full buffer range (1,$) was
807 * specified for this command invocation.
810 // FIXME: this isn't a count at all
811 COUNT_ALL: -2, // :%...
813 /** @property {Iterator(Command)} @private */
814 iterator: function iterator() iter.apply(null, this.hives.array)
815 .sort((a, b) => (a.serialGroup - b.serialGroup ||
819 /** @property {string} The last executed Ex command line. */
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");
829 return group._add.apply(group, arguments);
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 }),
836 * Returns the specified command invocation object serialized to
837 * an executable Ex command string.
839 * @param {Object} args The command invocation object.
842 commandToString: function commandToString(args) {
843 let res = [args.command + (args.bang ? "!" : "")];
846 if (args.ignoreDefaults)
847 defaults = array(this.options).map(opt => [opt.names[0], opt.default])
850 for (let [opt, val] in Iterator(args.options || {})) {
851 if (val === undefined)
853 if (val != null && defaults[opt] === val)
856 let chr = /^-.$/.test(opt) ? " " : "=";
858 opt += chr + Option.stringify.stringlist(val);
859 else if (val != null)
860 opt += chr + Commands.quote(val);
864 for (let [, arg] in Iterator(args.arguments || []))
865 res.push(Commands.quote(arg));
867 let str = args.literalArg;
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(" ");
876 * Returns the command with matching *name*.
878 * @param {string} name The name of the command to return. This can be
879 * any of the command's names.
882 get: function get(name, full) iter(this.hives).map(([i, hive]) => hive.get(name, full))
883 .nth(util.identity, 0),
886 * Returns true if a command invocation contains a URL referring to the
889 * @param {string} command
890 * @param {string} host
893 hasDomain: function hasDomain(command, host) {
895 for (let [cmd, args] in this.subCommands(command))
896 if (Array.concat(cmd.domains(args)).some(domain => util.isSubdomain(domain, host)))
906 * Returns true if a command invocation contains private data which should
907 * be cleared when purging private data.
909 * @param {string} command
912 hasPrivateData: function hasPrivateData(command) {
913 for (let [cmd, args] in this.subCommands(command))
915 return !callable(cmd.privateData) ? cmd.privateData
916 : cmd.privateData(args);
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.
932 * Parses *str* for options and plain arguments.
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
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 "\
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.
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
967 parseArgs: function parseArgs(str, params = {}) {
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;
975 return [count, "", ""];
976 return [count, self.readHeredoc(arg), ""];
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];
989 var { allowUnknownOptions, argCount, complete, extra, hereDoc, literal, options, keepQuotes } = params;
997 var args = params.newArgs ? params.newArgs() : [];
998 args.string = str; // for access to the unparsed string
1001 for (let [k, v] in Iterator(extra || []))
1004 // FIXME: best way to specify these requirements?
1005 var onlyArgumentsRemaining = allowUnknownOptions || options.length == 0; // after a -- has been found
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])));
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[""];
1027 args.completeArg = 0;
1030 let fail = function fail(error) {
1032 complete.message = error;
1034 util.assert(false, error);
1038 while (i < str.length || complete) {
1042 i += re.exec(str)[0].length;
1044 if (str[i] == "|") {
1045 args.string = str.slice(0, i);
1046 args.trailing = str.slice(i + 1);
1049 if (i == str.length && !complete)
1055 var sub = str.substr(i);
1056 if ((!onlyArgumentsRemaining) && /^--(\s|$)/.test(sub)) {
1057 onlyArgumentsRemaining = true;
1063 if (!onlyArgumentsRemaining) {
1064 for (let [, opt] in Iterator(options)) {
1065 for (let [, optname] in Iterator(opt.names)) {
1066 if (sub.indexOf(optname) == 0) {
1068 let invalid = false;
1069 let arg, quote, quoted;
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);
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)
1082 count++; // to compensate the "=" character
1084 else if (!/\s/.test(sep) && sep != undefined) // this isn't really an option as it has trailing characters, parse it as an argument
1088 if (!complete && quote)
1089 fail(_("command.invalidOptArg", optname, argString));
1092 if (complete && !/[\s=]/.test(sep))
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[""];
1101 if (!complete || arg != null) {
1104 arg = opt.type.parse(arg, quoted);
1106 if (complete && isArray(arg)) {
1107 args.completeFilter = arg[arg.length - 1] || "";
1108 args.completeStart += orig.length - args.completeFilter.length;
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));
1115 complete.highlight(args.completeStart, count - 1, "SPELLCHECK");
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");
1129 if (arg != null || opt.type == CommandOption.NOARG) {
1130 // option allowed multiple times
1132 args[opt.names[0]] = (args[opt.names[0]] || []).concat(arg);
1134 Class.replaceProperty(args, opt.names[0], opt.type == CommandOption.NOARG || arg);
1136 args.explicitOpts[opt.names[0]] = args[opt.names[0]];
1139 i += optname.length + count;
1140 if (i == str.length)
1144 // if it is invalid, just fall through and try the next argument
1153 if (argCount == "0" || args.length > 0 && (/[1?]/.test(argCount)))
1154 complete.highlight(i, sub.length, "SPELLCHECK");
1156 if (args.length === literal) {
1158 args.completeArg = args.length;
1160 let re = /(?:\s*(?=\n)|\s*)([^]*)/gy;
1161 re.lastIndex = argStart || 0;
1162 sub = re.exec(str)[1];
1165 if (sub.substr(0, 2) === "<<" && hereDoc)
1166 let ([count, arg] = getNextArg(sub)) {
1167 sub = arg + sub.substr(count);
1175 // if not an option, treat this token as an argument
1176 let [count, arg, quote, error] = getNextArg(sub);
1177 util.assert(!error, error);
1180 args.quote = Commands.complQuote[quote] || Commands.complQuote[""];
1181 args.completeFilter = arg || "";
1183 else if (count == -1)
1184 fail(_("command.parsing", arg));
1185 else if (!onlyArgumentsRemaining && sub[0] === "-")
1186 fail(_("command.invalidOpt", arg));
1191 args.completeArg = args.length - 1;
1194 if (count <= 0 || i == str.length)
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;
1206 context.filters.push(item => arg.indexOf(item.text) === -1);
1208 if (typeof opt.completer == "function")
1209 var compl = opt.completer(context, args);
1211 compl = opt.completer || [];
1213 context.title = [opt.names[0]];
1214 context.quote = args.quote;
1216 context.completions = compl;
1218 complete.advance(args.completeStart);
1221 description: function (opt) messages.get(["command", params.name, "options", opt.names[0], "description"].join("."), opt.description)
1223 complete.title = ["Options"];
1225 complete.completions = completeOpts;
1233 catch (e if complete && e instanceof FailedAssertion) {
1234 complete.message = e;
1239 nameRegexp: util.regexp(literal(/*
1246 forbid: util.regexp(String.replace(literal(/*
1247 U0000-U002c // U002d -
1249 U003a-U0040 // U0041-U005a a-z
1250 U005b-U0060 // U0061-U007a A-Z
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")
1272 validName: Class.Memoize(function validName() util.regexp("^" + this.nameRegexp.source + "$")),
1274 commandRegexp: Class.Memoize(function commandRegexp() util.regexp(literal(/*
1277 (?P<prespace> [:\s]*)
1278 (?P<count> (?:\d+ | %)? )
1280 (?: (?P<group> <name>) : )?
1281 (?P<cmd> (?:-? [()] | <name> | !)? ))
1290 name: this.nameRegexp
1294 * Parses a complete Ex command.
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"]
1304 * @param {string} str The Ex command line string.
1307 // FIXME: why does this return an Array rather than Object?
1308 parseCommand: function parseCommand(str) {
1310 str.replace(/\s*".*$/, "");
1312 let matches = this.commandRegexp.exec(str);
1316 let { spec, count, group, cmd, bang, space, args } = matches;
1318 [cmd, bang] = [bang, cmd];
1320 if (!cmd || args && args[0] != "|" && !(space || cmd == "!"))
1325 count = count == "%" ? this.COUNT_ALL : parseInt(count, 10);
1327 count = this.COUNT_NONE;
1329 return [count, cmd, !!bang, args || "", spec.length, group];
1332 parseCommands: function parseCommands(str, complete) {
1333 const { contexts } = this.modules;
1335 let [count, cmd, bang, args, len, group] = commands.parseCommand(str);
1337 var command = this.get(cmd || "");
1338 else if (group = contexts.getGroup(group, "commands"))
1339 command = group.get(cmd || "");
1341 if (command == null) {
1342 yield [null, { commandString: str }];
1347 var context = complete.fork(command.name).fork("opts", len);;
1349 if (!complete || /(\w|^)[!\s]/.test(str))
1350 args = command.parseArgs(args, context, { count: count, bang: bang });
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];
1364 subCommands: function subCommands(command) {
1365 let commands = [command];
1366 while (command = commands.shift())
1368 for (let [command, args] in this.parseCommands(command)) {
1370 yield [command, args];
1371 if (command.subCommand && args[command.subCommand])
1372 commands.push(args[command.subCommand]);
1380 get complQuote() Commands.complQuote,
1383 get quoteArg() Commands.quoteArg // XXX: better somewhere else?
1386 // returns [count, parsed_argument]
1387 parseArg: function parseArg(str, sep, keepQuotes) {
1390 let len = str.length;
1392 function fixEscapes(str) str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4}|(.))/g,
1393 (m, n1) => n1 || m);
1398 sep = sep != null ? sep : /\s/;
1399 let re1 = RegExp("^" + (sep.source === "" ? "(?!)" : sep.source));
1400 let re2 = RegExp(/^()((?:[^\\S"']|\\.)+)((?:\\$)?)/.source.replace("S", sep.source));
1402 while (str.length && !re1.test(str)) {
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");
1417 str = str.substr(res[0].length);
1420 return [len - str.length, arg, quote];
1423 quote: function quote(str) Commands.quoteArg[
1424 /[\b\f\n\r\t]/.test(str) ? '"' :
1425 /[\s"'\\]|^$|^-/.test(str) ? "'"
1428 completion: function initCompletion(dactyl, modules, window) {
1429 const { completion, contexts } = modules;
1431 completion.command = function command(context, group) {
1432 context.title = ["Command"];
1433 context.keys = { text: "longNames", description: "description" };
1435 context.generate = () => group._list;
1437 context.generate = () => modules.commands.hives.map(h => h._list).flatten();
1440 // provides completions for ex commands, including their arguments
1441 completion.ex = function ex(context) {
1442 const { commands } = modules;
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))
1448 context.advance(args.commandString.length + 1);
1450 args = { commandString: context.filter };
1452 let match = commands.commandRegexp.exec(args.commandString);
1457 context.advance(match.group.length + 1);
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"));
1465 // dynamically get completions as specified with the command's completer function
1466 context.highlight();
1468 context.message = _("command.noSuch", match.cmd);
1469 context.highlight(0, match.cmd.length, "SPELLCHECK");
1473 let cmdContext = context.fork(command.name + "/args", match.fullCmd.length + match.bang.length + match.space.length);
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);
1485 util.reportError(e);
1486 cmdContext.message = _("error.error", e);
1490 completion.exMacro = function exMacro(context, args, cmd) {
1491 if (!cmd.action.macro)
1493 let { macro } = cmd.action;
1495 let start = "«%-d-]'", end = "'[-d-%»";
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;
1502 args: { __proto__: args, toString: function () this.join(" ") },
1503 bang: args.bang ? "!" : "",
1507 if (!macro.valid(params))
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)
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);
1521 context.fork("ex", 0, completion, "ex");
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;
1531 commands: function initCommands(dactyl, modules, window) {
1532 const { commands, contexts } = modules;
1534 commands.add(["(", "-("], "",
1535 function (args) { dactyl.echoerr(_("dactyl.cheerUp")); },
1537 commands.add([")", "-)"], "",
1538 function (args) { dactyl.echoerr(_("dactyl.somberDown")); },
1541 commands.add(["com[mand]"],
1542 "List or define commands",
1546 util.assert(!cmd || cmd.split(",").every(commands.validName.closure.test),
1547 _("command.invalidName", cmd));
1549 if (args.length <= 1)
1550 commands.list(cmd, args.explicitOpts["-group"] ? [args["-group"]] : null);
1552 util.assert(args["-group"].modifiable,
1553 _("group.cantChangeBuiltin", _("command.commands")));
1555 let completer = args["-complete"];
1556 let completerFunc = function (context, args) modules.completion.exMacro(context, args, this);
1559 if (/^custom,/.test(completer)) {
1560 completer = completer.substr(7);
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);
1569 if (callable(result))
1570 return result.apply(this, arguments);
1572 return context.completions = result;
1576 completerFunc = context => modules.completion.closure[config.completers[completer]](context);
1579 let added = args["-group"].add(cmd.split(","),
1580 args["-description"],
1581 contexts.bindMacro(args, "-ex",
1582 function makeParams(args, modifiers) ({
1585 toString: function () this.string
1587 bang: this.bang && args.bang ? "!" : "",
1588 count: this.count && args.count
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)
1602 dactyl.echoerr(_("command.exists"));
1606 completer: function (context, args) {
1607 const { completion } = modules;
1608 if (args.completeArg == 0)
1609 completion.userCommand(context, args["-group"]);
1611 args["-javascript"] ? completion.javascript(context) : completion.ex(context);
1615 { names: ["-bang", "-b"], description: "Command may be followed by a !" },
1616 { names: ["-count", "-c"], description: "Command may be preceded by a count" },
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),
1626 names: ["-description", "-desc", "-d"],
1627 description: "A user-visible description of the command",
1628 default: "User-defined command",
1629 type: CommandOption.STRING
1631 contexts.GroupFlag("commands"),
1633 names: ["-javascript", "-js", "-j"],
1634 description: "Execute the definition as JavaScript rather than Ex commands"
1637 names: ["-literal", "-l"],
1638 description: "Process the specified argument ignoring any quoting or meta characters",
1639 type: CommandOption.INT
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"]],
1650 type: CommandOption.STRING,
1651 validator: bind("test", /^[01*?+]$/)
1654 names: ["-nopersist", "-n"],
1655 description: "Do not save this command to an auto-generated RC file"
1660 serialize: function () array(commands.userHives)
1661 .filter(h => h.persist)
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({
1672 description: "-description"
1674 if (cmd[k])).toObject(),
1675 arguments: [cmd.name],
1676 literalArg: cmd.action,
1677 ignoreDefaults: true
1679 for (cmd in hive) if (cmd.persist)
1684 commands.add(["delc[ommand]"],
1685 "Delete the specified user-defined command",
1687 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
1691 args["-group"].clear();
1692 else if (args["-group"].get(name))
1693 args["-group"].remove(name);
1695 dactyl.echoerr(_("command.noSuchUser", name));
1699 completer: function (context, args) modules.completion.userCommand(context, args["-group"]),
1700 options: [contexts.GroupFlag("commands")]
1703 commands.add(["comp[letions]"],
1704 "List the completion results for a given command substring",
1705 function (args) { modules.completion.listCompleter("ex", args[0]); },
1708 completer: function (context, args) modules.completion.ex(context),
1712 dactyl.addUsageCommand({
1713 name: ["listc[ommands]", "lc"],
1714 description: "List all Ex commands along with their short descriptions",
1716 iterate: function (args) commands.iterator().map(function (cmd) ({
1719 cmd.hive == commands.builtin ? "" : ["span", { highlight: "Object", style: "padding-right: 1em;" },
1723 iterateIndex: function (args) let (tags = help.tags)
1724 this.iterate(args).filter(cmd => (cmd.hive === commands.builtin || Set.has(tags, cmd.helpTag))),
1726 headings: ["Command", "Group", "Description"],
1727 description: function (cmd) template.linkifyHelp(cmd.description + (cmd.replacementText ? ": " + cmd.action : "")),
1728 help: function (cmd) ":" + cmd.name
1732 commands.add(["y[ank]"],
1733 "Yank the output of the given command to the clipboard",
1735 let cmd = /^:/.test(args[0]) ? args[0] : ":echo " + args[0];
1737 let res = modules.commandline.withOutputToString(commands.execute, commands, cmd);
1739 dactyl.clipboardWrite(res);
1741 let lines = res.split("\n").length;
1742 dactyl.echomsg(_("command.yank.yankedLine" + (lines == 1 ? "" : "s"), lines));
1746 completer: function (context) modules.completion[/^:/.test(context.filter) ? "ex" : "javascript"](context),
1750 javascript: function initJavascript(dactyl, modules, window) {
1751 const { JavaScript, commands } = modules;
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())]]);
1758 mappings: function initMappings(dactyl, modules, window) {
1759 const { commands, mappings, modes } = modules;
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);
1769 dactyl.echoerr(_("command.noPrevious"));
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)))
1783 Commands.quoteMap = {
1788 Commands.quoteArg = {
1789 '"': quote('"', '\n\t"\\\\'),
1790 "'": quote("'", "'", { "'": "''" }),
1791 "": quote("", "|\\\\\\s'\"")
1793 Commands.complQuote = {
1794 '"': ['"', quote("", Commands.quoteArg['"'].list), '"'],
1795 "'": ["'", quote("", Commands.quoteArg["'"].list), "'"],
1796 "": ["", Commands.quoteArg[""], ""]
1799 Commands.parseBool = function (arg) {
1800 if (/^(true|1|on)$/i.test(arg))
1802 if (/^(false|0|off)$/i.test(arg))
1809 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1811 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: