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: ["contexts", "messages", "storage"]
17 this.lazyRequire("config", ["config"]);
21 let ValueError = Class("ValueError", ErrorBase);
23 // do NOT create instances of this class yourself, use the helper method
24 // options.add() instead
26 * A class representing configuration options. Instances are created by the
27 * {@link Options} class.
29 * @param {[string]} names The names by which this option is identified.
30 * @param {string} description A short one line description of the option.
31 * @param {string} type The option's value data type (see {@link Option#type}).
32 * @param {string} defaultValue The default value for this option.
33 * @param {Object} extraInfo An optional extra configuration hash. The
34 * following properties are supported.
35 * completer - see {@link Option#completer}
36 * domains - see {@link Option#domains}
37 * getter - see {@link Option#getter}
38 * initialValue - Initial value is loaded from getter
39 * persist - see {@link Option#persist}
40 * privateData - see {@link Option#privateData}
41 * scope - see {@link Option#scope}
42 * setter - see {@link Option#setter}
43 * validator - see {@link Option#validator}
47 var Option = Class("Option", {
48 init: function init(modules, names, description, defaultValue, extraInfo) {
49 this.modules = modules;
51 this.realNames = names;
52 this.description = description;
55 this.update(extraInfo);
57 this._defaultValue = defaultValue;
59 if (this.globalValue == undefined && !this.initialValue)
60 this.globalValue = this.defaultValue;
63 magicalProperties: Set(["cleanupValue"]),
66 * @property {string} This option's description, as shown in :listoptions.
68 description: Messages.Localized(""),
70 get helpTag() "'" + this.name + "'",
72 initValue: function initValue() {
73 util.trapErrors(function () this.value = this.value, this);
76 get isDefault() this.stringValue === this.stringDefaultValue,
78 /** @property {value} The value to reset this option to at cleanup time. */
79 get cleanupValue() options.cleanupPrefs.get(this.name),
80 set cleanupValue(value) {
81 if (options.cleanupPrefs.get(this.name) == null)
82 options.cleanupPrefs.set(this.name, value);
85 /** @property {value} The option's global value. @see #scope */
87 let val = options.store.get(this.name, {}).value;
90 return this.globalValue = this.defaultValue;
92 set globalValue(val) {
93 options.store.set(this.name, { value: val, time: Date.now() });
97 * Returns *value* as an array of parsed values if the option type is
98 * "charlist" or "stringlist" or else unchanged.
100 * @param {value} value The option value.
101 * @returns {value|[string]}
103 parse: function parse(value) Option.dequote(value),
106 * Returns *values* packed in the appropriate format for the option type.
108 * @param {value|[string]} values The option value.
111 stringify: function stringify(vals) Commands.quote(vals),
114 * Returns the option's value as an array of parsed values if the option
115 * type is "charlist" or "stringlist" or else the simple value.
117 * @param {number} scope The scope to return these values from (see
118 * {@link Option#scope}).
119 * @returns {value|[string]}
121 get: function get(scope) {
123 if ((scope & this.scope) == 0) // option doesn't exist in this scope
132 if (config.has("tabs") && (scope & Option.SCOPE_LOCAL))
133 values = tabs.options[this.name];
135 if ((scope & Option.SCOPE_GLOBAL) && (values == undefined))
136 values = this.globalValue;
139 return util.trapErrors(this.getter, this, values);
145 * Sets the option's value from an array of values if the option type is
146 * "charlist" or "stringlist" or else the simple value.
148 * @param {number} scope The scope to apply these values to (see
149 * {@link Option#scope}).
151 set: function set(newValues, scope, skipGlobal) {
152 scope = scope || this.scope;
153 if ((scope & this.scope) == 0) // option doesn't exist in this scope
157 newValues = this.setter(newValues);
158 if (newValues === undefined)
162 if (config.has("tabs") && (scope & Option.SCOPE_LOCAL))
163 tabs.options[this.name] = newValues;
165 if ((scope & Option.SCOPE_GLOBAL) && !skipGlobal)
166 this.globalValue = newValues;
168 this.hasChanged = true;
171 // dactyl.triggerObserver("options." + this.name, newValues);
174 getValues: deprecated("Option#get", "get"),
175 setValues: deprecated("Option#set", "set"),
176 joinValues: deprecated("Option#stringify", "stringify"),
177 parseValues: deprecated("Option#parse", "parse"),
180 * @property {value} The option's current value. The option's local value,
181 * or if no local value is set, this is equal to the
182 * (@link #globalValue).
184 get value() this.get(),
185 set value(val) this.set(val),
187 get stringValue() this.stringify(this.value),
188 set stringValue(value) this.value = this.parse(value),
190 get stringDefaultValue() this.stringify(this.defaultValue),
191 set stringDefaultValue(val) this.defaultValue = this.parse(val),
193 getKey: function getKey(key) undefined,
196 * Returns whether the option value contains one or more of the specified
201 has: function has() Array.some(arguments, function (val) this.value.indexOf(val) >= 0, this),
204 * Returns whether this option is identified by *name*.
206 * @param {string} name
209 hasName: function hasName(name) this.names.indexOf(name) >= 0,
212 * Returns whether the specified *values* are valid for this option.
213 * @see Option#validator
215 isValidValue: function isValidValue(values) this.validator(values),
217 invalidArgument: function invalidArgument(arg, op) _("error.invalidArgument",
218 this.name + (op || "").replace(/=?$/, "=") + arg),
221 * Resets the option to its default value.
223 reset: function reset() {
224 this.value = this.defaultValue;
228 * Sets the option's value using the specified set *operator*.
230 * @param {string} operator The set operator.
231 * @param {value|[string]} values The value (or values) to apply.
232 * @param {number} scope The scope to apply this value to (see
234 * @param {boolean} invert Whether this is an invert boolean operation.
236 op: function op(operator, values, scope, invert, str) {
239 var newValues = this._op(operator, values, scope, invert);
240 if (newValues == null)
241 return _("option.operatorNotSupported", operator, this.type);
243 if (!this.isValidValue(newValues))
244 return this.invalidArgument(str || this.stringify(values), operator);
246 this.set(newValues, scope);
249 if (!(e instanceof ValueError))
251 return this.invalidArgument(str || this.stringify(values), operator) + ": " + e.message;
258 /** @property {string} The option's canonical name. */
261 /** @property {[string]} All names by which this option is identified. */
262 names: Class.Memoize(function () this.realNames),
265 * @property {string} The option's data type. One of:
266 * "boolean" - Boolean, e.g., true
267 * "number" - Integer, e.g., 1
268 * "string" - String, e.g., "Pentadactyl"
269 * "charlist" - Character list, e.g., "rb"
270 * "regexplist" - Regexp list, e.g., "^foo,bar$"
271 * "stringmap" - String map, e.g., "key:v,foo:bar"
272 * "regexpmap" - Regexp map, e.g., "^key:v,foo$:bar"
277 * @property {number} The scope of the option. This can be local, global,
279 * @see Option#SCOPE_LOCAL
280 * @see Option#SCOPE_GLOBAL
281 * @see Option#SCOPE_BOTH
283 scope: 1, // Option.SCOPE_GLOBAL // XXX set to BOTH by default someday? - kstep
286 * @property {function(CompletionContext, Args)} This option's completer.
287 * @see CompletionContext
289 completer: function completer(context, extra) {
290 if (/map$/.test(this.type) && extra.value == null)
294 context.completions = this.values;
298 * @property {[[string, string]]} This option's possible values.
299 * @see CompletionContext
301 values: Messages.Localized(null),
304 * @property {function(host, values)} A function which should return a list
305 * of domains referenced in the given values. Used in determining whether
306 * to purge the command from history when clearing private data.
307 * @see Command#domains
312 * @property {function(host, values)} A function which should strip
313 * references to a given domain from the given values.
315 filterDomain: function filterDomain(host, values)
316 Array.filter(values, function (val) !this.domains([val]).some(function (val) util.isSubdomain(val, host)), this),
319 * @property {value} The option's default value. This value will be used
320 * unless the option is explicitly set either interactively or in an RC
323 defaultValue: Class.Memoize(function () {
324 let defaultValue = this._defaultValue;
325 delete this._defaultValue;
327 if (Set.has(this.modules.config.optionDefaults, this.name))
328 defaultValue = this.modules.config.optionDefaults[this.name];
330 if (defaultValue == null && this.getter)
331 defaultValue = this.getter();
333 if (defaultValue == undefined)
336 if (this.type === "string")
337 defaultValue = Commands.quote(defaultValue);
339 if (isArray(defaultValue))
340 defaultValue = defaultValue.map(Option.quote).join(",");
341 else if (isObject(defaultValue))
342 defaultValue = iter(defaultValue).map(function (val) val.map(Option.quote).join(":")).join(",");
344 if (isArray(defaultValue))
345 defaultValue = defaultValue.map(Option.quote).join(",");
347 return this.parse(defaultValue);
351 * @property {function} The function called when the option value is read.
356 * @property {boolean} When true, this options values will be saved
357 * when generating a configuration file.
363 * @property {boolean|function(values)} When true, values of this
364 * option may contain private data which should be purged from
365 * saved histories when clearing private data. If a function, it
366 * should return true if an invocation with the given values
367 * contains private data
372 * @property {function} The function called when the option value is set.
376 testValues: function testValues(values, validator) validator(values),
379 * @property {function} The function called to validate the option's value
382 validator: function validator() {
383 if (this.values || this.completer !== Option.prototype.completer)
384 return Option.validateCompleter.apply(this, arguments);
389 * @property {boolean} Set to true whenever the option is first set. This
390 * is useful to see whether it was changed from its default value
391 * interactively or by some RC file.
396 * Returns the timestamp when the option's value was last changed.
398 get lastSet() options.store.get(this.name).time,
399 set lastSet(val) { options.store.set(this.name, { value: this.globalValue, time: Date.now() }); },
402 * @property {nsIFile} The script in which this option was last set. null
403 * implies an interactive command.
409 * @property {number} Global option scope.
415 * @property {number} Local option scope. Options in this scope only
416 * apply to the current tab/buffer.
422 * @property {number} Both local and global option scope.
428 toggleAll: function toggleAll() toggleAll.supercall(this, "all") ^ !!toggleAll.superapply(this, arguments),
431 parseRegexp: function parseRegexp(value, result, flags) {
432 let keepQuotes = this && this.keepQuotes;
433 if (isArray(flags)) // Called by Array.map
434 result = flags = undefined;
437 flags = this && this.regexpFlags || "";
439 let [, bang, val] = /^(!?)(.*)/.exec(value);
440 let re = util.regexp(Option.dequote(val), flags);
442 re.result = result !== undefined ? result : !bang;
443 re.key = re.bang + Option.quote(util.regexp.getSource(re), /^!|:/);
444 re.toString = function () Option.unparseRegexp(this, keepQuotes);
448 unparseRegexp: function unparseRegexp(re, quoted) re.bang + Option.quote(util.regexp.getSource(re), /^!|:/) +
449 (typeof re.result === "boolean" ? "" : ":" + (quoted ? re.result : Option.quote(re.result))),
451 parseSite: function parseSite(pattern, result, rest) {
452 if (isArray(rest)) // Called by Array.map
455 let [, bang, filter] = /^(!?)(.*)/.exec(pattern);
456 filter = Option.dequote(filter);
458 let quote = this.keepQuotes ? util.identity : Option.quote;
460 return update(Styles.matchFilter(filter), {
463 result: result !== undefined ? result : !bang,
464 toString: function toString() this.bang + Option.quote(this.filter, /:/) +
465 (typeof this.result === "boolean" ? "" : ":" + quote(this.result)),
470 stringlist: function stringlist(k) this.value.indexOf(k) >= 0,
471 get charlist() this.stringlist,
473 regexplist: function regexplist(k, default_) {
474 for (let re in values(this.value))
475 if ((re.test || re).call(re, k))
477 return arguments.length > 1 ? default_ : null;
479 get regexpmap() this.regexplist,
480 get sitelist() this.regexplist,
481 get sitemap() this.regexplist
485 sitelist: function (vals) array.compact(vals.map(function (site) util.getHost(site.filter))),
486 get sitemap() this.sitelist
490 charlist: function (vals) Commands.quote(vals.join("")),
492 stringlist: function (vals) vals.map(Option.quote).join(","),
494 stringmap: function (vals) [Option.quote(k, /:/) + ":" + Option.quote(v) for ([k, v] in Iterator(vals))].join(","),
496 regexplist: function (vals) vals.join(","),
497 get regexpmap() this.regexplist,
498 get sitelist() this.regexplist,
499 get sitemap() this.regexplist
503 number: function (value) let (val = Option.dequote(value))
504 Option.validIf(Number(val) % 1 == 0, _("option.intRequired")) && parseInt(val),
506 boolean: function boolean(value) Option.dequote(value) == "true" || value == true ? true : false,
508 charlist: function charlist(value) Array.slice(Option.dequote(value)),
510 stringlist: function stringlist(value) (value === "") ? [] : Option.splitList(value),
512 regexplist: function regexplist(value) (value === "") ? [] :
513 Option.splitList(value, true)
514 .map(function (re) Option.parseRegexp(re, undefined, this.regexpFlags), this),
516 sitelist: function sitelist(value) {
520 value = Option.splitList(value, true);
521 return value.map(Option.parseSite, this);
524 stringmap: function stringmap(value) array.toObject(
525 Option.splitList(value, true).map(function (v) {
526 let [count, key, quote] = Commands.parseArg(v, /:/);
527 return [key, Option.dequote(v.substr(count + 1))];
530 regexpmap: function regexpmap(value) Option.parse.list.call(this, value, Option.parseRegexp),
532 sitemap: function sitemap(value) Option.parse.list.call(this, value, Option.parseSite),
534 list: function list(value, parse) let (prev = null)
535 array.compact(Option.splitList(value, true).map(function (v) {
536 let [count, filter, quote] = Commands.parseArg(v, /:/, true);
538 let val = v.substr(count + 1);
539 if (!this.keepQuotes)
540 val = Option.dequote(val);
542 if (v.length > count)
543 return prev = parse.call(this, filter, val);
545 util.assert(prev, _("error.syntaxError"), false);
546 prev.result += "," + v;
552 regexpmap: function regexpmap(vals, validator) vals.every(function (re) validator(re.result)),
553 get sitemap() this.regexpmap,
554 stringlist: function stringlist(vals, validator) vals.every(validator, this),
555 stringmap: function stringmap(vals, validator) values(vals).every(validator, this)
558 dequote: function dequote(value) {
560 [, arg, Option._quote] = Commands.parseArg(String(value), "");
565 splitList: function splitList(value, keepQuotes) {
568 while (value.length) {
569 if (count !== undefined)
570 value = value.slice(1);
571 var [count, arg, quote] = Commands.parseArg(value, /,/, keepQuotes);
572 Option._quote = quote; // FIXME
574 if (value.length > count)
575 Option._splitAt += count + 1;
576 value = value.slice(count);
581 quote: function quote(str, re) isArray(str) ? str.map(function (s) quote(s, re)).join(",") :
582 Commands.quoteArg[/[\s|"'\\,]|^$/.test(str) || re && re.test && re.test(str)
583 ? (/[\b\f\n\r\t]/.test(str) ? '"' : "'")
587 boolean: function boolean(operator, values, scope, invert) {
595 number: function number(operator, values, scope, invert) {
597 values = values[(values.indexOf(String(this.value)) + 1) % values.length];
599 let value = parseInt(values);
600 util.assert(Number(values) % 1 == 0,
601 _("command.set.numberRequired", this.name, values));
605 return this.value + value;
607 return this.value - value;
609 return this.value * value;
616 string: function string(operator, values, scope, invert) {
618 return values[(values.indexOf(this.value) + 1) % values.length];
622 return this.value + values;
624 return this.value.replace(values, "");
626 return values + this.value;
633 stringmap: function stringmap(operator, values, scope, invert) {
634 let res = update({}, this.value);
637 // The result is the same.
640 return update(res, values);
642 for (let [k, v] in Iterator(values))
648 for (let [k, v] in Iterator(values))
660 stringlist: function stringlist(operator, values, scope, invert) {
661 values = Array.concat(values);
665 return ary.filter(function (elem) !Set.add(seen, elem));
670 return uniq(Array.concat(this.value, values), true);
672 // NOTE: Vim doesn't prepend if there's a match in the current value
673 return uniq(Array.concat(values, this.value), true);
675 return this.value.filter(function (item) !Set.has(this, item), Set(values));
678 let keepValues = this.value.filter(function (item) !Set.has(this, item), Set(values));
679 let addValues = values.filter(function (item) !Set.has(this, item), Set(this.value));
680 return addValues.concat(keepValues);
686 get charlist() this.stringlist,
687 get regexplist() this.stringlist,
688 get regexpmap() this.stringlist,
689 get sitelist() this.stringlist,
690 get sitemap() this.stringlist
693 validIf: function validIf(test, error) {
696 throw ValueError(error);
700 * Validates the specified *values* against values generated by the
701 * option's completer function.
703 * @param {value|[string]} values The value or array of values to validate.
706 validateCompleter: function validateCompleter(vals) {
707 function completions(extra) {
708 let context = CompletionContext("");
709 return context.fork("", 0, this, this.completer, extra) ||
710 context.allItems.items.map(function (item) [item.text]);
713 if (isObject(vals) && !isArray(vals)) {
714 let k = values(completions.call(this, { values: {} })).toObject();
715 let v = values(completions.call(this, { value: "" })).toObject();
716 return Object.keys(vals).every(Set.has(k)) && values(vals).every(Set.has(v));
720 var acceptable = this.values.array || this.values;
722 acceptable = completions.call(this);
724 if (isArray(acceptable))
725 acceptable = Set(acceptable.map(function ([k]) k));
727 if (this.type === "regexpmap" || this.type === "sitemap")
728 return Array.concat(vals).every(function (re) Set.has(acceptable, re.result));
730 return Array.concat(vals).every(Set.has(acceptable));
745 "StringMap"].forEach(function (name) {
746 let type = name.toLowerCase();
747 let class_ = Class(name + "Option", Option, {
750 _op: Option.ops[type]
753 if (type in Option.getKey)
754 class_.prototype.getKey = Option.getKey[type];
756 if (type in Option.parse)
757 class_.prototype.parse = Option.parse[type];
759 if (type in Option.stringify)
760 class_.prototype.stringify = Option.stringify[type];
762 if (type in Option.domains)
763 class_.prototype.domains = Option.domains[type];
765 if (type in Option.testValues)
766 class_.prototype.testValues = Option.testValues[type];
768 Option.types[type] = class_;
769 this[class_.className] = class_;
770 EXPORTED_SYMBOLS.push(class_.className);
773 update(BooleanOption.prototype, {
774 names: Class.Memoize(function ()
775 array.flatten([[name, "no" + name] for (name in values(this.realNames))]))
778 var OptionHive = Class("OptionHive", Contexts.Hive, {
779 init: function init(group) {
780 init.supercall(this, group);
782 this.has = Set.has(this.values);
785 add: function add(names, description, type, defaultValue, extraInfo) {
786 return this.modules.options.add(names, description, type, defaultValue, extraInfo);
793 var Options = Module("options", {
794 Local: function Local(dactyl, modules, window) let ({ contexts } = modules) ({
795 init: function init() {
799 hives: contexts.Hives("options", Class("OptionHive", OptionHive, { modules: modules })),
800 user: contexts.hives.options.user
805 this._optionMap = {};
807 storage.newMap("options", { store: false });
808 storage.addObserver("options", function optionObserver(key, event, option) {
809 // Trigger any setters.
810 let opt = self.get(option);
811 if (event == "change" && opt)
812 opt.set(opt.globalValue, Option.SCOPE_GLOBAL, true);
815 modules.cache.register("options.dtd", function ()
817 iter(([["option", o.name, "default"].join("."),
818 o.type === "string" ? o.defaultValue.replace(/'/g, "''") :
819 o.defaultValue === true ? "on" :
820 o.defaultValue === false ? "off" : o.stringDefaultValue]
823 ([["option", o.name, "type"].join("."), o.type] for (o in self)),
829 "io.source": function ioSource(context, file, modTime) {
830 cache.flushEntry("options.dtd", modTime);
837 * Lists all options in *scope* or only those with changed values if
838 * *onlyNonDefault* is specified.
840 * @param {function(Option)} filter Limit the list
841 * @param {number} scope Only list options in this scope (see
842 * {@link Option#scope}).
844 list: function list(filter, scope) {
846 scope = Option.SCOPE_BOTH;
849 for (let opt in Iterator(this)) {
852 isDefault: opt.isDefault,
853 default: opt.stringDefaultValue,
854 pre: "\u00a0\u00a0", // Unicode nonbreaking space.
858 if (filter && !filter(opt))
860 if (!(opt.scope & scope))
863 if (opt.type == "boolean") {
866 option.default = (opt.defaultValue ? "" : "no") + opt.name;
868 else if (isArray(opt.value) && opt.type != "charlist")
869 option.value = <>={template.map(opt.value,
870 function (v) template.highlight(String(v)),
871 <>,<span style="width: 0; display: inline-block"> </span></>)}</>;
873 option.value = <>={template.highlight(opt.stringValue)}</>;
878 modules.commandline.commandOutput(template.options("Options", opts.call(this), this["verbose"] > 0));
881 cleanup: function cleanup() {
882 for (let opt in this)
883 if (opt.cleanupValue != null)
884 opt.stringValue = opt.cleanupValue;
890 * @param {[string]} names All names for the option.
891 * @param {string} description A description of the option.
892 * @param {string} type The option type (see {@link Option#type}).
893 * @param {value} defaultValue The option's default value.
894 * @param {Object} extra An optional extra configuration hash (see
895 * {@link Map#extraInfo}).
898 add: function add(names, description, type, defaultValue, extraInfo) {
901 if (!util.isDactyl(Components.stack.caller))
902 deprecated.warn(add, "options.add", "group.options.add");
904 util.assert(type in Option.types, _("option.noSuchType", type),
910 extraInfo.definedAt = contexts.getCaller(Components.stack.caller);
913 if (name in this._optionMap) {
914 this.dactyl.log(_("option.replaceExisting", name.quote()), 1);
918 let closure = function () self._optionMap[name];
920 memoize(this._optionMap, name, function () Option.types[type](modules, names, description, defaultValue, extraInfo));
921 for (let alias in values(names.slice(1)))
922 memoize(this._optionMap, alias, closure);
924 if (extraInfo.setter && (!extraInfo.scope || extraInfo.scope & Option.SCOPE_GLOBAL))
925 if (this.dactyl.initialized)
926 closure().initValue();
928 memoize(this.needInit, this.needInit.length, closure);
930 this._floptions = (this._floptions || []).concat(name);
931 memoize(this._options, this._options.length, closure);
933 // quickly access options with options["wildmode"]:
934 this.__defineGetter__(name, function () this._optionMap[name].value);
935 this.__defineSetter__(name, function (value) { this._optionMap[name].value = value; });
939 /** @property {Iterator(Option)} @private */
940 __iterator__: function __iterator__()
941 values(this._options.sort(function (a, b) String.localeCompare(a.name, b.name))),
943 allPrefs: deprecated("prefs.getNames", function allPrefs() prefs.getNames.apply(prefs, arguments)),
944 getPref: deprecated("prefs.get", function getPref() prefs.get.apply(prefs, arguments)),
945 invertPref: deprecated("prefs.invert", function invertPref() prefs.invert.apply(prefs, arguments)),
946 listPrefs: deprecated("prefs.list", function listPrefs() { this.modules.commandline.commandOutput(prefs.list.apply(prefs, arguments)); }),
947 observePref: deprecated("prefs.observe", function observePref() prefs.observe.apply(prefs, arguments)),
948 popContext: deprecated("prefs.popContext", function popContext() prefs.popContext.apply(prefs, arguments)),
949 pushContext: deprecated("prefs.pushContext", function pushContext() prefs.pushContext.apply(prefs, arguments)),
950 resetPref: deprecated("prefs.reset", function resetPref() prefs.reset.apply(prefs, arguments)),
951 safeResetPref: deprecated("prefs.safeReset", function safeResetPref() prefs.safeReset.apply(prefs, arguments)),
952 safeSetPref: deprecated("prefs.safeSet", function safeSetPref() prefs.safeSet.apply(prefs, arguments)),
953 setPref: deprecated("prefs.set", function setPref() prefs.set.apply(prefs, arguments)),
954 withContext: deprecated("prefs.withContext", function withContext() prefs.withContext.apply(prefs, arguments)),
956 cleanupPrefs: Class.Memoize(function () config.prefs.Branch("cleanup.option.")),
958 cleanup: function cleanup(reason) {
959 if (~["disable", "uninstall"].indexOf(reason))
960 this.cleanupPrefs.resetBranch();
964 * Returns the option with *name* in the specified *scope*.
966 * @param {string} name The option's name.
967 * @param {number} scope The option's scope (see {@link Option#scope}).
969 * @returns {Option} The matching option.
971 get: function get(name, scope) {
973 scope = Option.SCOPE_BOTH;
975 if (this._optionMap[name] && (this._optionMap[name].scope & scope))
976 return this._optionMap[name];
981 * Parses a :set command's argument string.
983 * @param {string} args The :set command's argument string.
984 * @param {Object} modifiers A hash of parsing modifiers. These are:
985 * scope - see {@link Option#scope}
987 * @returns {Object} The parsed command object.
989 parseOpt: function parseOpt(args, modifiers) {
991 let matches, prefix, postfix;
993 [matches, prefix, res.name, postfix, res.valueGiven, res.operator, res.value] =
994 args.match(/^\s*(no|inv)?([^=]+?)([?&!])?\s*(([-+^]?)=(.*))?\s*$/) || [];
997 res.onlyNonDefault = false; // used for :set to print non-default options
1000 res.onlyNonDefault = true;
1004 if (res.option = this.get(res.name, res.scope)) {
1005 if (prefix === "no" && res.option.type !== "boolean")
1008 else if (res.option = this.get(prefix + res.name, res.scope)) {
1009 res.name = prefix + res.name;
1014 res.prefix = prefix;
1015 res.postfix = postfix;
1017 res.all = (res.name == "all");
1018 res.get = (res.all || postfix == "?" || (res.option && res.option.type != "boolean" && !res.valueGiven));
1019 res.invert = (prefix == "inv" || postfix == "!");
1020 res.reset = (postfix == "&");
1021 res.unsetBoolean = (prefix == "no");
1023 res.scope = modifiers && modifiers.scope;
1028 if (res.value === undefined)
1031 res.optionValue = res.option.get(res.scope);
1034 if (!res.invert || res.option.type != "number") // Hack.
1035 res.values = res.option.parse(res.value);
1045 * Remove the option with matching *name*.
1047 * @param {string} name The name of the option to remove. This can be
1048 * any of the option's names.
1050 remove: function remove(name) {
1051 let opt = this.get(name);
1052 this._options = this._options.filter(function (o) o != opt);
1053 for (let name in values(opt.names))
1054 delete this._optionMap[name];
1057 /** @property {Object} The options store. */
1058 get store() storage.options
1061 commands: function initCommands(dactyl, modules, window) {
1062 const { commands, contexts, options } = modules;
1065 getMode: function (args) findMode(args["-mode"]),
1066 iterate: function (args) {
1067 for (let map in mappings.iterate(this.getMode(args)))
1068 for (let name in values(map.names))
1069 yield { name: name, __proto__: map };
1072 description: function (map) (XML.ignoreWhitespace = false, XML.prettyPrinting = false, <>
1073 {options.get("passkeys").has(map.name)
1074 ? <span highlight="URLExtra">({
1075 tempate.linkifyHelp(_("option.passkeys.passedBy"))
1078 {template.linkifyHelp(map.description)}
1083 dactyl.addUsageCommand({
1084 name: ["listo[ptions]", "lo"],
1085 description: "List all options along with their short descriptions",
1087 iterate: function (args) options,
1089 description: function (opt) (XML.ignoreWhitespace = false, XML.prettyPrinting = false, <>
1090 {opt.scope == Option.SCOPE_LOCAL
1091 ? <span highlight="URLExtra">({_("option.bufferLocal")})</span> : ""}
1092 {template.linkifyHelp(opt.description)}
1094 help: function (opt) "'" + opt.name + "'"
1098 function setAction(args, modifiers) {
1099 let bang = args.bang;
1104 function flushList() {
1105 let names = Set(list.map(function (opt) opt.option ? opt.option.name : ""));
1107 if (list.some(function (opt) opt.all))
1108 options.list(function (opt) !(list[0].onlyNonDefault && opt.isDefault), list[0].scope);
1110 options.list(function (opt) Set.has(names, opt.name), list[0].scope);
1114 for (let [, arg] in args) {
1116 let onlyNonDefault = false;
1118 let invertBoolean = false;
1120 if (args[0] == "") {
1122 onlyNonDefault = true;
1125 var [matches, name, postfix, valueGiven, operator, value] =
1126 arg.match(/^\s*?((?:[^=\\']|\\.|'[^']*')+?)([?&!])?\s*(([-+^]?)=(.*))?\s*$/);
1127 reset = (postfix == "&");
1128 invertBoolean = (postfix == "!");
1131 name = Option.dequote(name);
1132 if (name == "all" && reset)
1133 modules.commandline.input(_("pref.prompt.resetAll", config.host) + " ",
1136 for (let pref in values(prefs.getNames()))
1139 { promptHighlight: "WarningMsg" });
1140 else if (name == "all")
1141 modules.commandline.commandOutput(prefs.list(onlyNonDefault, ""));
1144 else if (invertBoolean)
1146 else if (valueGiven) {
1147 if (value == undefined)
1149 else if (value == "true")
1151 else if (value == "false")
1153 else if (Number(value) % 1 == 0)
1154 value = parseInt(value);
1156 value = Option.dequote(value);
1159 value = Option.ops[typeof value].call({ value: prefs.get(name) }, operator, value);
1160 prefs.set(name, value);
1163 modules.commandline.commandOutput(prefs.list(onlyNonDefault, name));
1167 let opt = modules.options.parseOpt(arg, modifiers);
1168 util.assert(opt, _("command.set.errorParsing", arg));
1169 util.assert(!opt.error, _("command.set.errorParsing", opt.error));
1171 let option = opt.option;
1172 util.assert(option != null || opt.all, _("command.set.unknownOption", opt.name));
1174 // reset a variable to its default value
1178 for (let option in modules.options)
1191 if (opt.option.type === "boolean") {
1192 util.assert(!opt.valueGiven, _("error.invalidArgument", arg));
1193 opt.values = !opt.unsetBoolean;
1195 else if (/^(string|number)$/.test(opt.option.type) && opt.invert)
1196 opt.values = Option.splitList(opt.value);
1198 var res = opt.option.op(opt.operator || "=", opt.values, opt.scope, opt.invert,
1205 dactyl.echoerr(res);
1206 option.setFrom = contexts.getCaller(null);
1212 function setCompleter(context, args, modifiers) {
1213 const { completion } = modules;
1215 let filter = context.filter;
1217 if (args.bang) { // list completions for about:config entries
1218 if (filter[filter.length - 1] == "=") {
1219 context.advance(filter.length);
1220 filter = filter.substr(0, filter.length - 1);
1222 context.pushProcessor(0, function (item, text, next) next(item, text.substr(0, 100)));
1223 context.completions = [
1224 [prefs.get(filter), _("option.currentValue")],
1225 [prefs.defaults.get(filter), _("option.defaultValue")]
1226 ].filter(function (k) k[0] != null);
1230 return completion.preference(context);
1233 let opt = modules.options.parseOpt(filter, modifiers);
1234 let prefix = opt.prefix;
1236 context.highlight();
1237 if (context.filter.indexOf("=") == -1) {
1238 if (false && prefix)
1239 context.filters.push(function ({ item }) item.type == "boolean" || prefix == "inv" && isArray(item.values));
1240 return completion.option(context, opt.scope, opt.name == "inv" ? opt.name : prefix);
1243 function error(length, message) {
1244 context.message = message;
1245 context.highlight(0, length, "SPELLCHECK");
1248 let option = opt.option;
1250 return error(opt.name.length, _("option.noSuch", opt.name));
1252 context.advance(context.filter.indexOf("="));
1253 if (option.type == "boolean")
1254 return error(context.filter.length, _("error.trailingCharacters"));
1258 return error(context.filter.length, opt.error);
1260 if (opt.get || opt.reset || !option || prefix)
1263 if (!opt.value && !opt.operator && !opt.invert) {
1264 context.fork("default", 0, this, function (context) {
1265 context.title = ["Extra Completions"];
1266 context.pushProcessor(0, function (item, text, next) next(item, text.substr(0, 100)));
1267 context.completions = [
1268 [option.stringValue, _("option.currentValue")],
1269 [option.stringDefaultValue, _("option.defaultValue")]
1270 ].filter(function (f) f[0] !== "");
1271 context.quote = ["", util.identity, ""];
1275 let optcontext = context.fork("values");
1276 modules.completion.optionValue(optcontext, opt.name, opt.operator);
1278 // Fill in the current values if we're removing
1279 if (opt.operator == "-" && isArray(opt.values)) {
1280 let have = Set([i.text for (i in values(context.allItems.items))]);
1281 context = context.fork("current-values", 0);
1282 context.anchored = optcontext.anchored;
1283 context.maxItems = optcontext.maxItems;
1285 context.filters.push(function (i) !Set.has(have, i.text));
1286 modules.completion.optionValue(context, opt.name, opt.operator, null,
1287 function (context) {
1288 context.generate = function () option.value.map(function (o) [o, ""]);
1290 context.title = ["Current values"];
1294 // TODO: deprecated. This needs to support "g:"-prefixed globals at a
1295 // minimum for now. The coderepos plugins make extensive use of global
1297 commands.add(["let"],
1298 "Set or list a variable",
1300 let globalVariables = dactyl._globalVariables;
1301 args = (args[0] || "").trim();
1302 function fmt(value) (typeof value == "number" ? "#" :
1303 typeof value == "function" ? "*" :
1305 if (!args || args == "g:") {
1309 template.map(globalVariables, function ([i, value]) {
1311 <td style="width: 200px;">{i}</td>
1312 <td>{fmt(value)}</td>
1317 if (str.text().length() == str.*.length())
1318 dactyl.echomsg(_("variable.none"));
1320 dactyl.echo(str, modules.commandline.FORCE_MULTILINE);
1324 let matches = args.match(/^([a-z]:)?([\w]+)(?:\s*([-+.])?=\s*(.*)?)?$/);
1326 let [, scope, name, op, expr] = matches;
1327 let fullName = (scope || "") + name;
1329 util.assert(scope == "g:" || scope == null,
1330 _("command.let.illegalVar", scope + name));
1331 util.assert(Set.has(globalVariables, name) || (expr && !op),
1332 _("command.let.undefinedVar", fullName));
1335 dactyl.echo(fullName + "\t\t" + fmt(globalVariables[name]));
1338 var newValue = dactyl.userEval(expr);
1341 util.assert(newValue !== undefined,
1342 _("command.let.invalidExpression", expr));
1344 let value = newValue;
1346 value = globalVariables[name];
1352 value += String(newValue);
1354 globalVariables[name] = value;
1358 dactyl.echoerr(_("command.let.unexpectedChar"));
1361 deprecated: "the options system",
1368 names: ["setl[ocal]"],
1369 description: "Set local option",
1370 modifiers: { scope: Option.SCOPE_LOCAL }
1373 names: ["setg[lobal]"],
1374 description: "Set global option",
1375 modifiers: { scope: Option.SCOPE_GLOBAL }
1379 description: "Set an option",
1382 serialize: function () [
1385 literalArg: [opt.type == "boolean" ? (opt.value ? "" : "no") + opt.name
1386 : opt.name + "=" + opt.stringValue]
1388 for (opt in modules.options)
1389 if (!opt.getter && !opt.isDefault && (opt.scope & Option.SCOPE_GLOBAL))
1393 ].forEach(function (params) {
1394 commands.add(params.names, params.description,
1395 function (args, modifiers) {
1396 setAction(args, update(modifiers, params.modifiers));
1400 completer: setCompleter,
1401 domains: function domains(args) array.flatten(args.map(function (spec) {
1403 let opt = modules.options.parseOpt(spec);
1404 if (opt.option && opt.option.domains)
1405 return opt.option.domains(opt.values);
1408 util.reportError(e);
1413 privateData: function privateData(args) args.some(function (spec) {
1414 let opt = modules.options.parseOpt(spec);
1415 return opt.option && opt.option.privateData &&
1416 (!callable(opt.option.privateData) ||
1417 opt.option.privateData(opt.values));
1419 }, params.extra || {}));
1422 // TODO: deprecated. This needs to support "g:"-prefixed globals at a
1424 commands.add(["unl[et]"],
1425 "Delete a variable",
1427 for (let [, name] in args) {
1428 name = name.replace(/^g:/, ""); // throw away the scope prefix
1429 if (!Set.has(dactyl._globalVariables, name)) {
1431 dactyl.echoerr(_("command.let.noSuch", name));
1435 delete dactyl._globalVariables[name];
1441 deprecated: "the options system"
1444 completion: function initCompletion(dactyl, modules, window) {
1445 const { completion } = modules;
1447 completion.option = function option(context, scope, prefix) {
1448 context.title = ["Option"];
1449 context.keys = { text: "names", description: "description" };
1450 context.anchored = false;
1451 context.completions = modules.options;
1452 if (prefix == "inv")
1453 context.keys.text = function (opt)
1454 opt.type == "boolean" || isArray(opt.value) ? opt.names.map(function (n) "inv" + n)
1457 context.filters.push(function ({ item }) item.scope & scope);
1460 completion.optionValue = function (context, name, op, curValue, completer) {
1461 let opt = modules.options.get(name);
1462 completer = completer || opt.completer;
1463 if (!completer || !opt)
1467 var curValues = curValue != null ? opt.parse(curValue) : opt.value;
1468 var newValues = opt.parse(context.filter);
1471 context.message = _("error.error", e);
1472 context.completions = [];
1482 newValues = Option.splitList(context.filter);
1487 Option._splitAt = newValues.length;
1492 let vals = Option.splitList(context.filter);
1493 let target = vals.pop() || "";
1495 let [count, key, quote] = Commands.parseArg(target, /:/, true);
1496 let split = Option._splitAt;
1498 extra.key = Option.dequote(key);
1499 extra.value = count < target.length ? Option.dequote(target.substr(count + 1)) : null;
1500 extra.values = opt.parse(vals.join(","));
1502 Option._splitAt = split + (extra.value == null ? 0 : count + 1);
1505 // TODO: Highlight when invalid
1506 context.advance(Option._splitAt);
1507 context.filter = Option.dequote(context.filter);
1510 if (isArray(opt.defaultValue)) {
1511 let val = array.nth(obj, function (re) re.key == extra.key, 0);
1512 return val && val.result;
1514 if (Set.has(opt.defaultValue, extra.key))
1515 return obj[extra.key];
1518 if (extra.key && extra.value != null) {
1519 context.fork("default", 0, this, function (context) {
1520 context.completions = [
1521 [val(opt.value), _("option.currentValue")],
1522 [val(opt.defaultValue), _("option.defaultValue")]
1523 ].filter(function (f) f[0] !== "" && f[0] != null);
1525 context = context.fork("stuff", 0);
1528 context.title = ["Option Value"];
1529 context.quote = Commands.complQuote[Option._quote] || Commands.complQuote[""];
1530 // Not Vim compatible, but is a significant enough improvement
1531 // that it's worth breaking compatibility.
1532 if (isArray(newValues)) {
1533 context.filters.push(function (i) newValues.indexOf(i.text) == -1);
1535 context.filters.push(function (i) curValues.indexOf(i.text) == -1);
1537 context.filters.push(function (i) curValues.indexOf(i.text) > -1);
1539 memoize(extra, "values", function () {
1541 return curValues.concat(newValues);
1543 return curValues.filter(function (v) newValues.indexOf(val) == -1);
1548 let res = completer.call(opt, context, extra);
1550 context.completions = res;
1553 javascript: function initJavascript(dactyl, modules, window) {
1554 const { options, JavaScript } = modules;
1555 JavaScript.setCompleter(Options.prototype.get, [function () ([o.name, o.description] for (o in options))]);
1557 sanitizer: function initSanitizer(dactyl, modules, window) {
1558 const { sanitizer } = modules;
1560 sanitizer.addItem("options", {
1561 description: "Options containing hostname data",
1562 action: function sanitize_action(timespan, host) {
1564 for (let opt in values(modules.options._options))
1565 if (timespan.contains(opt.lastSet * 1000) && opt.domains)
1567 opt.value = opt.filterDomain(host, opt.value);
1570 dactyl.reportError(e);
1573 privateEnter: function privateEnter() {
1574 for (let opt in values(modules.options._options))
1575 if (opt.privateData && (!callable(opt.privateData) || opt.privateData(opt.value)))
1576 opt.oldValue = opt.value;
1578 privateLeave: function privateLeave() {
1579 for (let opt in values(modules.options._options))
1580 if (opt.oldValue != null) {
1581 opt.value = opt.oldValue;
1582 opt.oldValue = null;
1591 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1593 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: