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-2011 by Kris Maglione <maglione.k@gmail.com>
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 Components.utils.import("resource://dactyl/bootstrap.jsm");
12 defineModule("options", {
13 exports: ["Option", "Options", "ValueError", "options"],
14 require: ["messages", "storage"],
15 use: ["commands", "completion", "config", "prefs", "services", "styles", "template", "util"]
20 let ValueError = Class("ValueError", ErrorBase);
22 // do NOT create instances of this class yourself, use the helper method
23 // options.add() instead
25 * A class representing configuration options. Instances are created by the
26 * {@link Options} class.
28 * @param {[string]} names The names by which this option is identified.
29 * @param {string} description A short one line description of the option.
30 * @param {string} type The option's value data type (see {@link Option#type}).
31 * @param {string} defaultValue The default value for this option.
32 * @param {Object} extraInfo An optional extra configuration hash. The
33 * following properties are supported.
34 * completer - see {@link Option#completer}
35 * domains - see {@link Option#domains}
36 * getter - see {@link Option#getter}
37 * initialValue - Initial value is loaded from getter
38 * persist - see {@link Option#persist}
39 * privateData - see {@link Option#privateData}
40 * scope - see {@link Option#scope}
41 * setter - see {@link Option#setter}
42 * validator - see {@link Option#validator}
46 var Option = Class("Option", {
47 init: function init(modules, names, description, defaultValue, extraInfo) {
48 this.modules = modules;
51 this.realNames = names;
52 this.description = description;
55 this.update(extraInfo);
57 if (Set.has(this.modules.config.defaults, this.name))
58 defaultValue = this.modules.config.defaults[this.name];
60 if (defaultValue !== undefined) {
61 if (this.type === "string")
62 defaultValue = Commands.quote(defaultValue);
64 if (isObject(defaultValue))
65 defaultValue = iter(defaultValue).map(function (val) val.map(Option.quote).join(":")).join(",");
67 if (isArray(defaultValue))
68 defaultValue = defaultValue.map(Option.quote).join(",");
70 this.defaultValue = this.parse(defaultValue);
73 // add no{option} variant of boolean {option} to this.names
74 if (this.type == "boolean")
75 this.names = array([name, "no" + name] for (name in values(names))).flatten().array;
77 if (this.globalValue == undefined && !this.initialValue)
78 this.globalValue = this.defaultValue;
81 magicalProperties: Set(["cleanupValue"]),
84 * @property {string} This option's description, as shown in :listoptions.
86 description: Messages.Localized(""),
88 get helpTag() "'" + this.name + "'",
90 initValue: function initValue() {
91 util.trapErrors(function () this.value = this.value, this);
94 get isDefault() this.stringValue === this.stringDefaultValue,
96 /** @property {value} The value to reset this option to at cleanup time. */
97 get cleanupValue() options.cleanupPrefs.get(this.name),
98 set cleanupValue(value) {
99 if (options.cleanupPrefs.get(this.name) == null)
100 options.cleanupPrefs.set(this.name, value);
103 /** @property {value} The option's global value. @see #scope */
104 get globalValue() { try { return options.store.get(this.name, {}).value; } catch (e) { util.reportError(e); throw e; } },
105 set globalValue(val) { options.store.set(this.name, { value: val, time: Date.now() }); },
108 * Returns *value* as an array of parsed values if the option type is
109 * "charlist" or "stringlist" or else unchanged.
111 * @param {value} value The option value.
112 * @returns {value|[string]}
114 parse: function parse(value) Option.dequote(value),
117 * Returns *values* packed in the appropriate format for the option type.
119 * @param {value|[string]} values The option value.
122 stringify: function stringify(vals) Commands.quote(vals),
125 * Returns the option's value as an array of parsed values if the option
126 * type is "charlist" or "stringlist" or else the simple value.
128 * @param {number} scope The scope to return these values from (see
129 * {@link Option#scope}).
130 * @returns {value|[string]}
132 get: function get(scope) {
134 if ((scope & this.scope) == 0) // option doesn't exist in this scope
143 if (config.has("tabs") && (scope & Option.SCOPE_LOCAL))
144 values = tabs.options[this.name];
146 if ((scope & Option.SCOPE_GLOBAL) && (values == undefined))
147 values = this.globalValue;
150 return util.trapErrors(this.getter, this, values);
156 * Sets the option's value from an array of values if the option type is
157 * "charlist" or "stringlist" or else the simple value.
159 * @param {number} scope The scope to apply these values to (see
160 * {@link Option#scope}).
162 set: function set(newValues, scope, skipGlobal) {
163 scope = scope || this.scope;
164 if ((scope & this.scope) == 0) // option doesn't exist in this scope
168 newValues = this.setter(newValues);
169 if (newValues === undefined)
173 if (config.has("tabs") && (scope & Option.SCOPE_LOCAL))
174 tabs.options[this.name] = newValues;
176 if ((scope & Option.SCOPE_GLOBAL) && !skipGlobal)
177 this.globalValue = newValues;
179 this.hasChanged = true;
182 // dactyl.triggerObserver("options." + this.name, newValues);
185 getValues: deprecated("Option#get", "get"),
186 setValues: deprecated("Option#set", "set"),
187 joinValues: deprecated("Option#stringify", "stringify"),
188 parseValues: deprecated("Option#parse", "parse"),
191 * @property {value} The option's current value. The option's local value,
192 * or if no local value is set, this is equal to the
193 * (@link #globalValue).
195 get value() this.get(),
196 set value(val) this.set(val),
198 get stringValue() this.stringify(this.value),
199 set stringValue(value) this.value = this.parse(value),
201 get stringDefaultValue() this.stringify(this.defaultValue),
202 set stringDefaultValue(val) this.defaultValue = this.parse(val),
204 getKey: function getKey(key) undefined,
207 * Returns whether the option value contains one or more of the specified
212 has: function has() Array.some(arguments, function (val) this.value.indexOf(val) >= 0, this),
215 * Returns whether this option is identified by *name*.
217 * @param {string} name
220 hasName: function hasName(name) this.names.indexOf(name) >= 0,
223 * Returns whether the specified *values* are valid for this option.
224 * @see Option#validator
226 isValidValue: function isValidValue(values) this.validator(values),
228 invalidArgument: function invalidArgument(arg, op) _("error.invalidArgument",
229 this.name + (op || "").replace(/=?$/, "=") + arg),
232 * Resets the option to its default value.
234 reset: function reset() {
235 this.value = this.defaultValue;
239 * Sets the option's value using the specified set *operator*.
241 * @param {string} operator The set operator.
242 * @param {value|[string]} values The value (or values) to apply.
243 * @param {number} scope The scope to apply this value to (see
245 * @param {boolean} invert Whether this is an invert boolean operation.
247 op: function op(operator, values, scope, invert, str) {
250 var newValues = this._op(operator, values, scope, invert);
251 if (newValues == null)
252 return _("option.operatorNotSupported", operator, this.type);
254 if (!this.isValidValue(newValues))
255 return this.invalidArgument(str || this.stringify(values), operator);
257 this.set(newValues, scope);
260 if (!(e instanceof ValueError))
262 return this.invalidArgument(str || this.stringify(values), operator) + ": " + e.message;
269 /** @property {string} The option's canonical name. */
271 /** @property {[string]} All names by which this option is identified. */
275 * @property {string} The option's data type. One of:
276 * "boolean" - Boolean, e.g., true
277 * "number" - Integer, e.g., 1
278 * "string" - String, e.g., "Pentadactyl"
279 * "charlist" - Character list, e.g., "rb"
280 * "regexplist" - Regexp list, e.g., "^foo,bar$"
281 * "stringmap" - String map, e.g., "key:v,foo:bar"
282 * "regexpmap" - Regexp map, e.g., "^key:v,foo$:bar"
287 * @property {number} The scope of the option. This can be local, global,
289 * @see Option#SCOPE_LOCAL
290 * @see Option#SCOPE_GLOBAL
291 * @see Option#SCOPE_BOTH
293 scope: 1, // Option.SCOPE_GLOBAL // XXX set to BOTH by default someday? - kstep
296 * @property {function(CompletionContext, Args)} This option's completer.
297 * @see CompletionContext
299 completer: function completer(context, extra) {
300 if (/map$/.test(this.type) && extra.value == null)
304 context.completions = this.values;
308 * @property {[[string, string]]} This option's possible values.
309 * @see CompletionContext
311 values: Messages.Localized(null),
314 * @property {function(host, values)} A function which should return a list
315 * of domains referenced in the given values. Used in determining whether
316 * to purge the command from history when clearing private data.
317 * @see Command#domains
322 * @property {function(host, values)} A function which should strip
323 * references to a given domain from the given values.
325 filterDomain: function filterDomain(host, values)
326 Array.filter(values, function (val) !this.domains([val]).some(function (val) util.isSubdomain(val, host)), this),
329 * @property {value} The option's default value. This value will be used
330 * unless the option is explicitly set either interactively or in an RC
336 * @property {function} The function called when the option value is read.
341 * @property {boolean} When true, this options values will be saved
342 * when generating a configuration file.
348 * @property {boolean|function(values)} When true, values of this
349 * option may contain private data which should be purged from
350 * saved histories when clearing private data. If a function, it
351 * should return true if an invocation with the given values
352 * contains private data
357 * @property {function} The function called when the option value is set.
361 testValues: function testValues(values, validator) validator(values),
364 * @property {function} The function called to validate the option's value
367 validator: function validator() {
368 if (this.values || this.completer !== Option.prototype.completer)
369 return Option.validateCompleter.apply(this, arguments);
374 * @property {boolean} Set to true whenever the option is first set. This
375 * is useful to see whether it was changed from its default value
376 * interactively or by some RC file.
381 * Returns the timestamp when the option's value was last changed.
383 get lastSet() options.store.get(this.name).time,
384 set lastSet(val) { options.store.set(this.name, { value: this.globalValue, time: Date.now() }); },
387 * @property {nsIFile} The script in which this option was last set. null
388 * implies an interactive command.
394 * @property {number} Global option scope.
400 * @property {number} Local option scope. Options in this scope only
401 * apply to the current tab/buffer.
407 * @property {number} Both local and global option scope.
413 toggleAll: function toggleAll() toggleAll.supercall(this, "all") ^ !!toggleAll.superapply(this, arguments),
416 parseRegexp: function parseRegexp(value, result, flags) {
417 let keepQuotes = this && this.keepQuotes;
418 if (isArray(flags)) // Called by Array.map
419 result = flags = undefined;
422 flags = this && this.regexpFlags || "";
424 let [, bang, val] = /^(!?)(.*)/.exec(value);
425 let re = util.regexp(Option.dequote(val), flags);
427 re.result = result !== undefined ? result : !bang;
428 re.toString = function () Option.unparseRegexp(this, keepQuotes);
432 unparseRegexp: function unparseRegexp(re, quoted) re.bang + Option.quote(util.regexp.getSource(re), /^!|:/) +
433 (typeof re.result === "boolean" ? "" : ":" + (quoted ? re.result : Option.quote(re.result))),
435 parseSite: function parseSite(pattern, result, rest) {
436 if (isArray(rest)) // Called by Array.map
439 let [, bang, filter] = /^(!?)(.*)/.exec(pattern);
440 filter = Option.dequote(filter);
442 let quote = this.keepQuotes ? util.identity : Option.quote;
444 return update(Styles.matchFilter(filter), {
447 result: result !== undefined ? result : !bang,
448 toString: function toString() this.bang + Option.quote(this.filter, /:/) +
449 (typeof this.result === "boolean" ? "" : ":" + quote(this.result)),
454 stringlist: function stringlist(k) this.value.indexOf(k) >= 0,
455 get charlist() this.stringlist,
457 regexplist: function regexplist(k, default_) {
458 for (let re in values(this.value))
459 if ((re.test || re).call(re, k))
461 return arguments.length > 1 ? default_ : null;
463 get regexpmap() this.regexplist,
464 get sitelist() this.regexplist,
465 get sitemap() this.regexplist
469 sitelist: function (vals) array.compact(vals.map(function (site) util.getHost(site.filter))),
470 get sitemap() this.sitelist
474 charlist: function (vals) Commands.quote(vals.join("")),
476 stringlist: function (vals) vals.map(Option.quote).join(","),
478 stringmap: function (vals) [Option.quote(k, /:/) + ":" + Option.quote(v) for ([k, v] in Iterator(vals))].join(","),
480 regexplist: function (vals) vals.join(","),
481 get regexpmap() this.regexplist,
482 get sitelist() this.regexplist,
483 get sitemap() this.regexplist
487 number: function (value) let (val = Option.dequote(value))
488 Option.validIf(Number(val) % 1 == 0, _("option.intRequired")) && parseInt(val),
490 boolean: function boolean(value) Option.dequote(value) == "true" || value == true ? true : false,
492 charlist: function charlist(value) Array.slice(Option.dequote(value)),
494 stringlist: function stringlist(value) (value === "") ? [] : Option.splitList(value),
496 regexplist: function regexplist(value) (value === "") ? [] :
497 Option.splitList(value, true)
498 .map(function (re) Option.parseRegexp(re, undefined, this.regexpFlags), this),
500 sitelist: function sitelist(value) {
504 value = Option.splitList(value, true);
505 return value.map(Option.parseSite, this);
508 stringmap: function stringmap(value) array.toObject(
509 Option.splitList(value, true).map(function (v) {
510 let [count, key, quote] = Commands.parseArg(v, /:/);
511 return [key, Option.dequote(v.substr(count + 1))];
514 regexpmap: function regexpmap(value) Option.parse.list.call(this, value, Option.parseRegexp),
516 sitemap: function sitemap(value) Option.parse.list.call(this, value, Option.parseSite),
518 list: function list(value, parse) let (prev = null)
519 array.compact(Option.splitList(value, true).map(function (v) {
520 let [count, filter, quote] = Commands.parseArg(v, /:/, true);
522 let val = v.substr(count + 1);
523 if (!this.keepQuotes)
524 val = Option.dequote(val);
526 if (v.length > count)
527 return prev = parse.call(this, filter, val);
529 util.assert(prev, _("error.syntaxError"), false);
530 prev.result += "," + v;
536 regexpmap: function regexpmap(vals, validator) vals.every(function (re) validator(re.result)),
537 get sitemap() this.regexpmap,
538 stringlist: function stringlist(vals, validator) vals.every(validator, this),
539 stringmap: function stringmap(vals, validator) values(vals).every(validator, this)
542 dequote: function dequote(value) {
544 [, arg, Option._quote] = Commands.parseArg(String(value), "");
549 splitList: function splitList(value, keepQuotes) {
552 while (value.length) {
553 if (count !== undefined)
554 value = value.slice(1);
555 var [count, arg, quote] = Commands.parseArg(value, /,/, keepQuotes);
556 Option._quote = quote; // FIXME
558 if (value.length > count)
559 Option._splitAt += count + 1;
560 value = value.slice(count);
565 quote: function quote(str, re) isArray(str) ? str.map(function (s) quote(s, re)).join(",") :
566 Commands.quoteArg[/[\s|"'\\,]|^$/.test(str) || re && re.test && re.test(str)
567 ? (/[\b\f\n\r\t]/.test(str) ? '"' : "'")
571 boolean: function boolean(operator, values, scope, invert) {
579 number: function number(operator, values, scope, invert) {
581 values = values[(values.indexOf(String(this.value)) + 1) % values.length];
583 let value = parseInt(values);
584 util.assert(Number(values) % 1 == 0,
585 _("command.set.numberRequired", this.name, values));
589 return this.value + value;
591 return this.value - value;
593 return this.value * value;
600 stringmap: function stringmap(operator, values, scope, invert) {
601 let res = update({}, this.value);
604 // The result is the same.
607 return update(res, values);
609 for (let [k, v] in Iterator(values))
615 for (let [k, v] in Iterator(values))
627 stringlist: function stringlist(operator, values, scope, invert) {
628 values = Array.concat(values);
632 return ary.filter(function (elem) !Set.add(seen, elem));
637 return uniq(Array.concat(this.value, values), true);
639 // NOTE: Vim doesn't prepend if there's a match in the current value
640 return uniq(Array.concat(values, this.value), true);
642 return this.value.filter(function (item) !Set.has(this, item), Set(values));
645 let keepValues = this.value.filter(function (item) !Set.has(this, item), Set(values));
646 let addValues = values.filter(function (item) !Set.has(this, item), Set(this.value));
647 return addValues.concat(keepValues);
653 get charlist() this.stringlist,
654 get regexplist() this.stringlist,
655 get regexpmap() this.stringlist,
656 get sitelist() this.stringlist,
657 get sitemap() this.stringlist,
659 string: function string(operator, values, scope, invert) {
661 return values[(values.indexOf(this.value) + 1) % values.length];
664 return this.value + values;
666 return this.value.replace(values, "");
668 return values + this.value;
676 validIf: function validIf(test, error) {
679 throw ValueError(error);
683 * Validates the specified *values* against values generated by the
684 * option's completer function.
686 * @param {value|[string]} values The value or array of values to validate.
689 validateCompleter: function validateCompleter(values) {
691 var acceptable = this.values.array || this.values;
693 let context = CompletionContext("");
694 acceptable = context.fork("", 0, this, this.completer);
696 acceptable = context.allItems.items.map(function (item) [item.text]);
699 if (isArray(acceptable))
700 acceptable = Set(acceptable.map(function ([k]) k));
702 if (this.type === "regexpmap" || this.type === "sitemap")
703 return Array.concat(values).every(function (re) Set.has(acceptable, re.result));
705 return Array.concat(values).every(Set.has(acceptable));
720 "StringMap"].forEach(function (name) {
721 let type = name.toLowerCase();
722 let class_ = Class(name + "Option", Option, {
725 _op: Option.ops[type]
728 if (type in Option.getKey)
729 class_.prototype.getKey = Option.getKey[type];
731 if (type in Option.parse)
732 class_.prototype.parse = Option.parse[type];
734 if (type in Option.stringify)
735 class_.prototype.stringify = Option.stringify[type];
737 if (type in Option.domains)
738 class_.prototype.domains = Option.domains[type];
740 if (type in Option.testValues)
741 class_.prototype.testValues = Option.testValues[type];
743 Option.types[type] = class_;
744 this[class_.className] = class_;
745 EXPORTED_SYMBOLS.push(class_.className);
751 var Options = Module("options", {
752 Local: function Local(dactyl, modules, window) let ({ contexts } = modules) ({
753 init: function init() {
757 this._optionMap = {};
759 storage.newMap("options", { store: false });
760 storage.addObserver("options", function optionObserver(key, event, option) {
761 // Trigger any setters.
762 let opt = self.get(option);
763 if (event == "change" && opt)
764 opt.set(opt.globalValue, Option.SCOPE_GLOBAL, true);
767 services["dactyl:"].pages["options.dtd"] = function () [null,
769 iter(([["option", o.name, "default"].join("."),
770 o.type === "string" ? o.defaultValue.replace(/'/g, "''") :
771 o.value === true ? "on" :
772 o.value === false ? "off" : o.stringDefaultValue]
775 ([["option", o.name, "type"].join("."), o.type] for (o in self)),
783 * Lists all options in *scope* or only those with changed values if
784 * *onlyNonDefault* is specified.
786 * @param {function(Option)} filter Limit the list
787 * @param {number} scope Only list options in this scope (see
788 * {@link Option#scope}).
790 list: function list(filter, scope) {
792 scope = Option.SCOPE_BOTH;
795 for (let opt in Iterator(this)) {
798 isDefault: opt.isDefault,
799 default: opt.stringDefaultValue,
800 pre: "\u00a0\u00a0", // Unicode nonbreaking space.
804 if (filter && !filter(opt))
806 if (!(opt.scope & scope))
809 if (opt.type == "boolean") {
812 option.default = (opt.defaultValue ? "" : "no") + opt.name;
814 else if (isArray(opt.value))
815 option.value = <>={template.map(opt.value, function (v) template.highlight(String(v)), <>,<span style="width: 0; display: inline-block"> </span></>)}</>;
817 option.value = <>={template.highlight(opt.stringValue)}</>;
822 modules.commandline.commandOutput(template.options("Options", opts.call(this), this["verbose"] > 0));
825 cleanup: function cleanup() {
826 for (let opt in this)
827 if (opt.cleanupValue != null)
828 opt.stringValue = opt.cleanupValue;
834 * @param {[string]} names All names for the option.
835 * @param {string} description A description of the option.
836 * @param {string} type The option type (see {@link Option#type}).
837 * @param {value} defaultValue The option's default value.
838 * @param {Object} extra An optional extra configuration hash (see
839 * {@link Map#extraInfo}).
842 add: function add(names, description, type, defaultValue, extraInfo) {
848 extraInfo.definedAt = contexts.getCaller(Components.stack.caller);
851 if (name in this._optionMap) {
852 this.dactyl.log(_("option.replaceExisting", name.quote()), 1);
856 let closure = function () self._optionMap[name];
858 memoize(this._optionMap, name, function () Option.types[type](modules, names, description, defaultValue, extraInfo));
859 for (let alias in values(names.slice(1)))
860 memoize(this._optionMap, alias, closure);
862 if (extraInfo.setter && (!extraInfo.scope || extraInfo.scope & Option.SCOPE_GLOBAL))
863 if (this.dactyl.initialized)
864 closure().initValue();
866 memoize(this.needInit, this.needInit.length, closure);
868 this._floptions = (this._floptions || []).concat(name);
869 memoize(this._options, this._options.length, closure);
871 // quickly access options with options["wildmode"]:
872 this.__defineGetter__(name, function () this._optionMap[name].value);
873 this.__defineSetter__(name, function (value) { this._optionMap[name].value = value; });
877 /** @property {Iterator(Option)} @private */
878 __iterator__: function __iterator__()
879 values(this._options.sort(function (a, b) String.localeCompare(a.name, b.name))),
881 allPrefs: deprecated("prefs.getNames", function allPrefs() prefs.getNames.apply(prefs, arguments)),
882 getPref: deprecated("prefs.get", function getPref() prefs.get.apply(prefs, arguments)),
883 invertPref: deprecated("prefs.invert", function invertPref() prefs.invert.apply(prefs, arguments)),
884 listPrefs: deprecated("prefs.list", function listPrefs() { this.modules.commandline.commandOutput(prefs.list.apply(prefs, arguments)); }),
885 observePref: deprecated("prefs.observe", function observePref() prefs.observe.apply(prefs, arguments)),
886 popContext: deprecated("prefs.popContext", function popContext() prefs.popContext.apply(prefs, arguments)),
887 pushContext: deprecated("prefs.pushContext", function pushContext() prefs.pushContext.apply(prefs, arguments)),
888 resetPref: deprecated("prefs.reset", function resetPref() prefs.reset.apply(prefs, arguments)),
889 safeResetPref: deprecated("prefs.safeReset", function safeResetPref() prefs.safeReset.apply(prefs, arguments)),
890 safeSetPref: deprecated("prefs.safeSet", function safeSetPref() prefs.safeSet.apply(prefs, arguments)),
891 setPref: deprecated("prefs.set", function setPref() prefs.set.apply(prefs, arguments)),
892 withContext: deprecated("prefs.withContext", function withContext() prefs.withContext.apply(prefs, arguments)),
894 cleanupPrefs: Class.memoize(function () localPrefs.Branch("cleanup.option.")),
896 cleanup: function cleanup(reason) {
897 if (~["disable", "uninstall"].indexOf(reason))
898 this.cleanupPrefs.resetBranch();
902 * Returns the option with *name* in the specified *scope*.
904 * @param {string} name The option's name.
905 * @param {number} scope The option's scope (see {@link Option#scope}).
907 * @returns {Option} The matching option.
909 get: function get(name, scope) {
911 scope = Option.SCOPE_BOTH;
913 if (this._optionMap[name] && (this._optionMap[name].scope & scope))
914 return this._optionMap[name];
919 * Parses a :set command's argument string.
921 * @param {string} args The :set command's argument string.
922 * @param {Object} modifiers A hash of parsing modifiers. These are:
923 * scope - see {@link Option#scope}
925 * @returns {Object} The parsed command object.
927 parseOpt: function parseOpt(args, modifiers) {
929 let matches, prefix, postfix;
931 [matches, prefix, res.name, postfix, res.valueGiven, res.operator, res.value] =
932 args.match(/^\s*(no|inv)?([^=]+?)([?&!])?\s*(([-+^]?)=(.*))?\s*$/) || [];
935 res.onlyNonDefault = false; // used for :set to print non-default options
938 res.onlyNonDefault = true;
942 if (res.option = this.get(res.name, res.scope)) {
943 if (prefix === "no" && res.option.type !== "boolean")
946 else if (res.option = this.get(prefix + res.name, res.scope)) {
947 res.name = prefix + res.name;
953 res.postfix = postfix;
955 res.all = (res.name == "all");
956 res.get = (res.all || postfix == "?" || (res.option && res.option.type != "boolean" && !res.valueGiven));
957 res.invert = (prefix == "inv" || postfix == "!");
958 res.reset = (postfix == "&");
959 res.unsetBoolean = (prefix == "no");
961 res.scope = modifiers && modifiers.scope;
966 if (res.value === undefined)
969 res.optionValue = res.option.get(res.scope);
972 res.values = res.option.parse(res.value);
982 * Remove the option with matching *name*.
984 * @param {string} name The name of the option to remove. This can be
985 * any of the option's names.
987 remove: function remove(name) {
988 let opt = this.get(name);
989 this._options = this._options.filter(function (o) o != opt);
990 for (let name in values(opt.names))
991 delete this._optionMap[name];
994 /** @property {Object} The options store. */
995 get store() storage.options
998 commands: function initCommands(dactyl, modules, window) {
999 const { commands, contexts, options } = modules;
1002 getMode: function (args) findMode(args["-mode"]),
1003 iterate: function (args) {
1004 for (let map in mappings.iterate(this.getMode(args)))
1005 for (let name in values(map.names))
1006 yield { name: name, __proto__: map };
1009 description: function (map) (XML.ignoreWhitespace = false, XML.prettyPrinting = false, <>
1010 {options.get("passkeys").has(map.name)
1011 ? <span highlight="URLExtra">({
1012 tempate.linkifyHelp(_("option.passkeys.passedBy"))
1015 {template.linkifyHelp(map.description)}
1020 dactyl.addUsageCommand({
1021 name: ["listo[ptions]", "lo"],
1022 description: "List all options along with their short descriptions",
1024 iterate: function (args) options,
1026 description: function (opt) (XML.ignoreWhitespace = false, XML.prettyPrinting = false, <>
1027 {opt.scope == Option.SCOPE_LOCAL
1028 ? <span highlight="URLExtra">({_("option.bufferLocal")})</span> : ""}
1029 {template.linkifyHelp(opt.description)}
1031 help: function (opt) "'" + opt.name + "'"
1035 function setAction(args, modifiers) {
1036 let bang = args.bang;
1041 function flushList() {
1042 let names = Set(list.map(function (opt) opt.option ? opt.option.name : ""));
1044 if (list.some(function (opt) opt.all))
1045 options.list(function (opt) !(list[0].onlyNonDefault && opt.isDefault), list[0].scope);
1047 options.list(function (opt) Set.has(names, opt.name), list[0].scope);
1051 for (let [, arg] in args) {
1053 let onlyNonDefault = false;
1055 let invertBoolean = false;
1057 if (args[0] == "") {
1059 onlyNonDefault = true;
1062 var [matches, name, postfix, valueGiven, operator, value] =
1063 arg.match(/^\s*?([^=]+?)([?&!])?\s*(([-+^]?)=(.*))?\s*$/);
1064 reset = (postfix == "&");
1065 invertBoolean = (postfix == "!");
1068 if (name == "all" && reset)
1069 modules.commandline.input(_("pref.prompt.resetAll", config.host) + " ",
1072 for (let pref in values(prefs.getNames()))
1075 { promptHighlight: "WarningMsg" });
1076 else if (name == "all")
1077 modules.commandline.commandOutput(prefs.list(onlyNonDefault, ""));
1080 else if (invertBoolean)
1082 else if (valueGiven) {
1083 if (value == undefined)
1085 else if (value == "true")
1087 else if (value == "false")
1089 else if (Number(value) % 1 == 0)
1090 value = parseInt(value);
1092 value = Option.dequote(value);
1095 value = Option.ops[typeof value].call({ value: prefs.get(name) }, operator, value);
1096 prefs.set(name, value);
1099 modules.commandline.commandOutput(prefs.list(onlyNonDefault, name));
1103 let opt = modules.options.parseOpt(arg, modifiers);
1104 util.assert(opt, _("command.set.errorParsing", arg));
1105 util.assert(!opt.error, _("command.set.errorParsing", opt.error));
1107 let option = opt.option;
1108 util.assert(option != null || opt.all, _("command.set.unknownOption", opt.name));
1110 // reset a variable to its default value
1114 for (let option in modules.options)
1127 if (opt.option.type === "boolean") {
1128 util.assert(!opt.valueGiven, _("error.invalidArgument", arg));
1129 opt.values = !opt.unsetBoolean;
1131 else if (/^(string|number)$/.test(opt.option.type) && opt.invert)
1132 opt.values = Option.splitList(opt.value);
1134 var res = opt.option.op(opt.operator || "=", opt.values, opt.scope, opt.invert,
1141 dactyl.echoerr(res);
1142 option.setFrom = contexts.getCaller(null);
1148 function setCompleter(context, args, modifiers) {
1149 const { completion } = modules;
1151 let filter = context.filter;
1153 if (args.bang) { // list completions for about:config entries
1154 if (filter[filter.length - 1] == "=") {
1155 context.advance(filter.length);
1156 filter = filter.substr(0, filter.length - 1);
1158 context.pushProcessor(0, function (item, text, next) next(item, text.substr(0, 100)));
1159 context.completions = [
1160 [prefs.get(filter), _("option.currentValue")],
1161 [prefs.defaults.get(filter), _("option.defaultValue")]
1162 ].filter(function (k) k[0] != null);
1166 return completion.preference(context);
1169 let opt = modules.options.parseOpt(filter, modifiers);
1170 let prefix = opt.prefix;
1172 context.highlight();
1173 if (context.filter.indexOf("=") == -1) {
1174 if (false && prefix)
1175 context.filters.push(function ({ item }) item.type == "boolean" || prefix == "inv" && isArray(item.values));
1176 return completion.option(context, opt.scope, opt.name == "inv" ? opt.name : prefix);
1179 function error(length, message) {
1180 context.message = message;
1181 context.highlight(0, length, "SPELLCHECK");
1184 let option = opt.option;
1186 return error(opt.name.length, _("option.noSuch", opt.name));
1188 context.advance(context.filter.indexOf("="));
1189 if (option.type == "boolean")
1190 return error(context.filter.length, _("error.trailingCharacters"));
1194 return error(context.filter.length, opt.error);
1196 if (opt.get || opt.reset || !option || prefix)
1199 if (!opt.value && !opt.operator && !opt.invert) {
1200 context.fork("default", 0, this, function (context) {
1201 context.title = ["Extra Completions"];
1202 context.pushProcessor(0, function (item, text, next) next(item, text.substr(0, 100)));
1203 context.completions = [
1204 [option.stringValue, _("option.currentValue")],
1205 [option.stringDefaultValue, _("option.defaultValue")]
1206 ].filter(function (f) f[0] !== "");
1207 context.quote = ["", util.identity, ""];
1211 let optcontext = context.fork("values");
1212 modules.completion.optionValue(optcontext, opt.name, opt.operator);
1214 // Fill in the current values if we're removing
1215 if (opt.operator == "-" && isArray(opt.values)) {
1216 let have = Set([i.text for (i in values(context.allItems.items))]);
1217 context = context.fork("current-values", 0);
1218 context.anchored = optcontext.anchored;
1219 context.maxItems = optcontext.maxItems;
1221 context.filters.push(function (i) !Set.has(have, i.text));
1222 modules.completion.optionValue(context, opt.name, opt.operator, null,
1223 function (context) {
1224 context.generate = function () option.value.map(function (o) [o, ""]);
1226 context.title = ["Current values"];
1230 // TODO: deprecated. This needs to support "g:"-prefixed globals at a
1231 // minimum for now. The coderepos plugins make extensive use of global
1233 commands.add(["let"],
1234 "Set or list a variable",
1236 let globalVariables = dactyl._globalVariables;
1237 args = (args[0] || "").trim();
1238 function fmt(value) (typeof value == "number" ? "#" :
1239 typeof value == "function" ? "*" :
1241 if (!args || args == "g:") {
1245 template.map(globalVariables, function ([i, value]) {
1247 <td style="width: 200px;">{i}</td>
1248 <td>{fmt(value)}</td>
1253 if (str.text().length() == str.*.length())
1254 dactyl.echomsg(_("variable.none"));
1256 dactyl.echo(str, modules.commandline.FORCE_MULTILINE);
1260 let matches = args.match(/^([a-z]:)?([\w]+)(?:\s*([-+.])?=\s*(.*)?)?$/);
1262 let [, scope, name, op, expr] = matches;
1263 let fullName = (scope || "") + name;
1265 util.assert(scope == "g:" || scope == null,
1266 _("command.let.illegalVar", scope + name));
1267 util.assert(Set.has(globalVariables, name) || (expr && !op),
1268 _("command.let.undefinedVar", fullName));
1271 dactyl.echo(fullName + "\t\t" + fmt(globalVariables[name]));
1274 var newValue = dactyl.userEval(expr);
1277 util.assert(newValue !== undefined,
1278 _("command.let.invalidExpression", expr));
1280 let value = newValue;
1282 value = globalVariables[name];
1288 value += String(newValue);
1290 globalVariables[name] = value;
1294 dactyl.echoerr(_("command.let.unexpectedChar"));
1297 deprecated: "the options system",
1304 names: ["setl[ocal]"],
1305 description: "Set local option",
1306 modifiers: { scope: Option.SCOPE_LOCAL }
1309 names: ["setg[lobal]"],
1310 description: "Set global option",
1311 modifiers: { scope: Option.SCOPE_GLOBAL }
1315 description: "Set an option",
1318 serialize: function () [
1321 literalArg: [opt.type == "boolean" ? (opt.value ? "" : "no") + opt.name
1322 : opt.name + "=" + opt.stringValue]
1324 for (opt in modules.options)
1325 if (!opt.getter && !opt.isDefault && (opt.scope & Option.SCOPE_GLOBAL))
1329 ].forEach(function (params) {
1330 commands.add(params.names, params.description,
1331 function (args, modifiers) {
1332 setAction(args, update(modifiers, params.modifiers));
1336 completer: setCompleter,
1337 domains: function domains(args) array.flatten(args.map(function (spec) {
1339 let opt = modules.options.parseOpt(spec);
1340 if (opt.option && opt.option.domains)
1341 return opt.option.domains(opt.values);
1344 util.reportError(e);
1349 privateData: function privateData(args) args.some(function (spec) {
1350 let opt = modules.options.parseOpt(spec);
1351 return opt.option && opt.option.privateData &&
1352 (!callable(opt.option.privateData) ||
1353 opt.option.privateData(opt.values));
1355 }, params.extra || {}));
1358 // TODO: deprecated. This needs to support "g:"-prefixed globals at a
1360 commands.add(["unl[et]"],
1361 "Delete a variable",
1363 for (let [, name] in args) {
1364 name = name.replace(/^g:/, ""); // throw away the scope prefix
1365 if (!Set.has(dactyl._globalVariables, name)) {
1367 dactyl.echoerr(_("command.let.noSuch", name));
1371 delete dactyl._globalVariables[name];
1377 deprecated: "the options system"
1380 completion: function initCompletion(dactyl, modules, window) {
1381 const { completion } = modules;
1383 completion.option = function option(context, scope, prefix) {
1384 context.title = ["Option"];
1385 context.keys = { text: "names", description: "description" };
1386 context.anchored = false;
1387 context.completions = modules.options;
1388 if (prefix == "inv")
1389 context.keys.text = function (opt)
1390 opt.type == "boolean" || isArray(opt.value) ? opt.names.map(function (n) "inv" + n)
1393 context.filters.push(function ({ item }) item.scope & scope);
1396 completion.optionValue = function (context, name, op, curValue, completer) {
1397 let opt = modules.options.get(name);
1398 completer = completer || opt.completer;
1399 if (!completer || !opt)
1403 var curValues = curValue != null ? opt.parse(curValue) : opt.value;
1404 var newValues = opt.parse(context.filter);
1407 context.message = _("error.error", e);
1408 context.completions = [];
1418 newValues = Option.splitList(context.filter);
1423 Option._splitAt = newValues.length;
1428 let vals = Option.splitList(context.filter);
1429 let target = vals.pop() || "";
1431 let [count, key, quote] = Commands.parseArg(target, /:/, true);
1432 let split = Option._splitAt;
1434 extra.key = Option.dequote(key);
1435 extra.value = count < target.length ? Option.dequote(target.substr(count + 1)) : null;
1436 extra.values = opt.parse(vals.join(","));
1438 Option._splitAt = split + (extra.value == null ? 0 : count + 1);
1441 // TODO: Highlight when invalid
1442 context.advance(Option._splitAt);
1443 context.filter = Option.dequote(context.filter);
1445 context.title = ["Option Value"];
1446 context.quote = Commands.complQuote[Option._quote] || Commands.complQuote[""];
1447 // Not Vim compatible, but is a significant enough improvement
1448 // that it's worth breaking compatibility.
1449 if (isArray(newValues)) {
1450 context.filters.push(function (i) newValues.indexOf(i.text) == -1);
1452 context.filters.push(function (i) curValues.indexOf(i.text) == -1);
1454 context.filters.push(function (i) curValues.indexOf(i.text) > -1);
1456 memoize(extra, "values", function () {
1458 return curValues.concat(newValues);
1460 return curValues.filter(function (v) newValues.indexOf(val) == -1);
1465 let res = completer.call(opt, context, extra);
1467 context.completions = res;
1470 javascript: function initJavascript(dactyl, modules, window) {
1471 const { options, JavaScript } = modules;
1472 JavaScript.setCompleter(options.get, [function () ([o.name, o.description] for (o in options))]);
1474 sanitizer: function initSanitizer(dactyl, modules, window) {
1475 const { sanitizer } = modules;
1477 sanitizer.addItem("options", {
1478 description: "Options containing hostname data",
1479 action: function sanitize_action(timespan, host) {
1481 for (let opt in values(modules.options._options))
1482 if (timespan.contains(opt.lastSet * 1000) && opt.domains)
1484 opt.value = opt.filterDomain(host, opt.value);
1487 dactyl.reportError(e);
1490 privateEnter: function privateEnter() {
1491 for (let opt in values(modules.options._options))
1492 if (opt.privateData && (!callable(opt.privateData) || opt.privateData(opt.value)))
1493 opt.oldValue = opt.value;
1495 privateLeave: function privateLeave() {
1496 for (let opt in values(modules.options._options))
1497 if (opt.oldValue != null) {
1498 opt.value = opt.oldValue;
1499 opt.oldValue = null;
1508 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1510 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: