]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/options.jsm
Import 1.0rc1 supporting Firefox up to 11.*
[dactyl.git] / common / modules / options.jsm
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k@gmail.com>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 /* use strict */
8
9 try {
10
11 Components.utils.import("resource://dactyl/bootstrap.jsm");
12 defineModule("options", {
13     exports: ["Option", "Options", "ValueError", "options"],
14     require: ["contexts", "messages", "storage"]
15 }, this);
16
17 this.lazyRequire("config", ["config"]);
18
19 /** @scope modules */
20
21 let ValueError = Class("ValueError", ErrorBase);
22
23 // do NOT create instances of this class yourself, use the helper method
24 // options.add() instead
25 /**
26  * A class representing configuration options. Instances are created by the
27  * {@link Options} class.
28  *
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}
44  * @optional
45  * @private
46  */
47 var Option = Class("Option", {
48     init: function init(modules, names, description, defaultValue, extraInfo) {
49         this.modules = modules;
50         this.name = names[0];
51         this.realNames = names;
52         this.description = description;
53
54         if (extraInfo)
55             this.update(extraInfo);
56
57         this._defaultValue = defaultValue;
58
59         if (this.globalValue == undefined && !this.initialValue)
60             this.globalValue = this.defaultValue;
61     },
62
63     magicalProperties: Set(["cleanupValue"]),
64
65     /**
66      * @property {string} This option's description, as shown in :listoptions.
67      */
68     description: Messages.Localized(""),
69
70     get helpTag() "'" + this.name + "'",
71
72     initValue: function initValue() {
73         util.trapErrors(function () this.value = this.value, this);
74     },
75
76     get isDefault() this.stringValue === this.stringDefaultValue,
77
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);
83     },
84
85     /** @property {value} The option's global value. @see #scope */
86     get globalValue() {
87         let val = options.store.get(this.name, {}).value;
88         if (val != null)
89             return val;
90         return this.globalValue = this.defaultValue;
91     },
92     set globalValue(val) {
93         options.store.set(this.name, { value: val, time: Date.now() });
94     },
95
96     /**
97      * Returns *value* as an array of parsed values if the option type is
98      * "charlist" or "stringlist" or else unchanged.
99      *
100      * @param {value} value The option value.
101      * @returns {value|[string]}
102      */
103     parse: function parse(value) Option.dequote(value),
104
105     /**
106      * Returns *values* packed in the appropriate format for the option type.
107      *
108      * @param {value|[string]} values The option value.
109      * @returns {value}
110      */
111     stringify: function stringify(vals) Commands.quote(vals),
112
113     /**
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.
116      *
117      * @param {number} scope The scope to return these values from (see
118      *     {@link Option#scope}).
119      * @returns {value|[string]}
120      */
121     get: function get(scope) {
122         if (scope) {
123             if ((scope & this.scope) == 0) // option doesn't exist in this scope
124                 return null;
125         }
126         else
127             scope = this.scope;
128
129         let values;
130
131         /*
132         if (config.has("tabs") && (scope & Option.SCOPE_LOCAL))
133             values = tabs.options[this.name];
134          */
135         if ((scope & Option.SCOPE_GLOBAL) && (values == undefined))
136             values = this.globalValue;
137
138         if (this.getter)
139             return util.trapErrors(this.getter, this, values);
140
141         return values;
142     },
143
144     /**
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.
147      *
148      * @param {number} scope The scope to apply these values to (see
149      *     {@link Option#scope}).
150      */
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
154             return;
155
156         if (this.setter)
157             newValues = this.setter(newValues);
158         if (newValues === undefined)
159             return;
160
161         /*
162         if (config.has("tabs") && (scope & Option.SCOPE_LOCAL))
163             tabs.options[this.name] = newValues;
164         */
165         if ((scope & Option.SCOPE_GLOBAL) && !skipGlobal)
166             this.globalValue = newValues;
167
168         this.hasChanged = true;
169         this.setFrom = null;
170
171         // dactyl.triggerObserver("options." + this.name, newValues);
172     },
173
174     getValues: deprecated("Option#get", "get"),
175     setValues: deprecated("Option#set", "set"),
176     joinValues: deprecated("Option#stringify", "stringify"),
177     parseValues: deprecated("Option#parse", "parse"),
178
179     /**
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).
183      */
184     get value() this.get(),
185     set value(val) this.set(val),
186
187     get stringValue() this.stringify(this.value),
188     set stringValue(value) this.value = this.parse(value),
189
190     get stringDefaultValue() this.stringify(this.defaultValue),
191     set stringDefaultValue(val) this.defaultValue = this.parse(val),
192
193     getKey: function getKey(key) undefined,
194
195     /**
196      * Returns whether the option value contains one or more of the specified
197      * arguments.
198      *
199      * @returns {boolean}
200      */
201     has: function has() Array.some(arguments, function (val) this.value.indexOf(val) >= 0, this),
202
203     /**
204      * Returns whether this option is identified by *name*.
205      *
206      * @param {string} name
207      * @returns {boolean}
208      */
209     hasName: function hasName(name) this.names.indexOf(name) >= 0,
210
211     /**
212      * Returns whether the specified *values* are valid for this option.
213      * @see Option#validator
214      */
215     isValidValue: function isValidValue(values) this.validator(values),
216
217     invalidArgument: function invalidArgument(arg, op) _("error.invalidArgument",
218         this.name + (op || "").replace(/=?$/, "=") + arg),
219
220     /**
221      * Resets the option to its default value.
222      */
223     reset: function reset() {
224         this.value = this.defaultValue;
225     },
226
227     /**
228      * Sets the option's value using the specified set *operator*.
229      *
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
233      *     {@link #scope}).
234      * @param {boolean} invert Whether this is an invert boolean operation.
235      */
236     op: function op(operator, values, scope, invert, str) {
237
238         try {
239             var newValues = this._op(operator, values, scope, invert);
240             if (newValues == null)
241                 return _("option.operatorNotSupported", operator, this.type);
242
243             if (!this.isValidValue(newValues))
244                 return this.invalidArgument(str || this.stringify(values), operator);
245
246             this.set(newValues, scope);
247         }
248         catch (e) {
249             if (!(e instanceof ValueError))
250                 util.reportError(e);
251             return this.invalidArgument(str || this.stringify(values), operator) + ": " + e.message;
252         }
253         return null;
254     },
255
256     // Properties {{{2
257
258     /** @property {string} The option's canonical name. */
259     name: null,
260
261     /** @property {[string]} All names by which this option is identified. */
262     names: Class.Memoize(function () this.realNames),
263
264     /**
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"
273      */
274     type: null,
275
276     /**
277      * @property {number} The scope of the option. This can be local, global,
278      *     or both.
279      * @see Option#SCOPE_LOCAL
280      * @see Option#SCOPE_GLOBAL
281      * @see Option#SCOPE_BOTH
282      */
283     scope: 1, // Option.SCOPE_GLOBAL // XXX set to BOTH by default someday? - kstep
284
285     /**
286      * @property {function(CompletionContext, Args)} This option's completer.
287      * @see CompletionContext
288      */
289     completer: function completer(context, extra) {
290         if (/map$/.test(this.type) && extra.value == null)
291             return;
292
293         if (this.values)
294             context.completions = this.values;
295     },
296
297     /**
298      * @property {[[string, string]]} This option's possible values.
299      * @see CompletionContext
300      */
301     values: Messages.Localized(null),
302
303     /**
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
308      */
309     domains: null,
310
311     /**
312      * @property {function(host, values)} A function which should strip
313      *     references to a given domain from the given values.
314      */
315     filterDomain: function filterDomain(host, values)
316         Array.filter(values, function (val) !this.domains([val]).some(function (val) util.isSubdomain(val, host)), this),
317
318     /**
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
321      *     file or plugin.
322      */
323     defaultValue: Class.Memoize(function () {
324         let defaultValue = this._defaultValue;
325         delete this._defaultValue;
326
327         if (Set.has(this.modules.config.optionDefaults, this.name))
328             defaultValue = this.modules.config.optionDefaults[this.name];
329
330         if (defaultValue == null && this.getter)
331             defaultValue = this.getter();
332
333         if (defaultValue == undefined)
334             return null;
335
336         if (this.type === "string")
337             defaultValue = Commands.quote(defaultValue);
338
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(",");
343
344         if (isArray(defaultValue))
345             defaultValue = defaultValue.map(Option.quote).join(",");
346
347         return this.parse(defaultValue);
348     }),
349
350     /**
351      * @property {function} The function called when the option value is read.
352      */
353     getter: null,
354
355     /**
356      * @property {boolean} When true, this options values will be saved
357      *     when generating a configuration file.
358      * @default true
359      */
360     persist: true,
361
362     /**
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
368      */
369     privateData: false,
370
371     /**
372      * @property {function} The function called when the option value is set.
373      */
374     setter: null,
375
376     testValues: function testValues(values, validator) validator(values),
377
378     /**
379      * @property {function} The function called to validate the option's value
380      *     when set.
381      */
382     validator: function validator() {
383         if (this.values || this.completer !== Option.prototype.completer)
384             return Option.validateCompleter.apply(this, arguments);
385         return true;
386     },
387
388     /**
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.
392      */
393     hasChanged: false,
394
395     /**
396      * Returns the timestamp when the option's value was last changed.
397      */
398     get lastSet() options.store.get(this.name).time,
399     set lastSet(val) { options.store.set(this.name, { value: this.globalValue, time: Date.now() }); },
400
401     /**
402      * @property {nsIFile} The script in which this option was last set. null
403      *     implies an interactive command.
404      */
405     setFrom: null
406
407 }, {
408     /**
409      * @property {number} Global option scope.
410      * @final
411      */
412     SCOPE_GLOBAL: 1,
413
414     /**
415      * @property {number} Local option scope. Options in this scope only
416      *     apply to the current tab/buffer.
417      * @final
418      */
419     SCOPE_LOCAL: 2,
420
421     /**
422      * @property {number} Both local and global option scope.
423      * @final
424      */
425     SCOPE_BOTH: 3,
426
427     has: {
428         toggleAll: function toggleAll() toggleAll.supercall(this, "all") ^ !!toggleAll.superapply(this, arguments),
429     },
430
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;
435
436         if (flags == null)
437             flags = this && this.regexpFlags || "";
438
439         let [, bang, val] = /^(!?)(.*)/.exec(value);
440         let re = util.regexp(Option.dequote(val), flags);
441         re.bang = bang;
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);
445         return re;
446     },
447
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))),
450
451     parseSite: function parseSite(pattern, result, rest) {
452         if (isArray(rest)) // Called by Array.map
453             result = undefined;
454
455         let [, bang, filter] = /^(!?)(.*)/.exec(pattern);
456         filter = Option.dequote(filter);
457
458         let quote = this.keepQuotes ? util.identity : Option.quote;
459
460         return update(Styles.matchFilter(filter), {
461             bang: bang,
462             filter: 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)),
466         });
467     },
468
469     getKey: {
470         stringlist: function stringlist(k) this.value.indexOf(k) >= 0,
471         get charlist() this.stringlist,
472
473         regexplist: function regexplist(k, default_) {
474             for (let re in values(this.value))
475                 if ((re.test || re).call(re, k))
476                     return re.result;
477             return arguments.length > 1 ? default_ : null;
478         },
479         get regexpmap() this.regexplist,
480         get sitelist() this.regexplist,
481         get sitemap() this.regexplist
482     },
483
484     domains: {
485         sitelist: function (vals) array.compact(vals.map(function (site) util.getHost(site.filter))),
486         get sitemap() this.sitelist
487     },
488
489     stringify: {
490         charlist:    function (vals) Commands.quote(vals.join("")),
491
492         stringlist:  function (vals) vals.map(Option.quote).join(","),
493
494         stringmap:   function (vals) [Option.quote(k, /:/) + ":" + Option.quote(v) for ([k, v] in Iterator(vals))].join(","),
495
496         regexplist:  function (vals) vals.join(","),
497         get regexpmap() this.regexplist,
498         get sitelist() this.regexplist,
499         get sitemap() this.regexplist
500     },
501
502     parse: {
503         number:     function (value) let (val = Option.dequote(value))
504                             Option.validIf(Number(val) % 1 == 0, _("option.intRequired")) && parseInt(val),
505
506         boolean:    function boolean(value) Option.dequote(value) == "true" || value == true ? true : false,
507
508         charlist:   function charlist(value) Array.slice(Option.dequote(value)),
509
510         stringlist: function stringlist(value) (value === "") ? [] : Option.splitList(value),
511
512         regexplist: function regexplist(value) (value === "") ? [] :
513             Option.splitList(value, true)
514                   .map(function (re) Option.parseRegexp(re, undefined, this.regexpFlags), this),
515
516         sitelist: function sitelist(value) {
517             if (value === "")
518                 return [];
519             if (!isArray(value))
520                 value = Option.splitList(value, true);
521             return value.map(Option.parseSite, this);
522         },
523
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))];
528             })),
529
530         regexpmap: function regexpmap(value) Option.parse.list.call(this, value, Option.parseRegexp),
531
532         sitemap: function sitemap(value) Option.parse.list.call(this, value, Option.parseSite),
533
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);
537
538                 let val = v.substr(count + 1);
539                 if (!this.keepQuotes)
540                     val = Option.dequote(val);
541
542                 if (v.length > count)
543                     return prev = parse.call(this, filter, val);
544                 else {
545                     util.assert(prev, _("error.syntaxError"), false);
546                     prev.result += "," + v;
547                 }
548             }, this))
549     },
550
551     testValues: {
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)
556     },
557
558     dequote: function dequote(value) {
559         let arg;
560         [, arg, Option._quote] = Commands.parseArg(String(value), "");
561         Option._splitAt = 0;
562         return arg;
563     },
564
565     splitList: function splitList(value, keepQuotes) {
566         let res = [];
567         Option._splitAt = 0;
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
573             res.push(arg);
574             if (value.length > count)
575                 Option._splitAt += count + 1;
576             value = value.slice(count);
577         }
578         return res;
579     },
580
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) ? '"' : "'")
584             : ""](str, re),
585
586     ops: {
587         boolean: function boolean(operator, values, scope, invert) {
588             if (operator != "=")
589                 return null;
590             if (invert)
591                 return !this.value;
592             return values;
593         },
594
595         number: function number(operator, values, scope, invert) {
596             if (invert)
597                 values = values[(values.indexOf(String(this.value)) + 1) % values.length];
598
599             let value = parseInt(values);
600             util.assert(Number(values) % 1 == 0,
601                         _("command.set.numberRequired", this.name, values));
602
603             switch (operator) {
604             case "+":
605                 return this.value + value;
606             case "-":
607                 return this.value - value;
608             case "^":
609                 return this.value * value;
610             case "=":
611                 return value;
612             }
613             return null;
614         },
615
616         string: function string(operator, values, scope, invert) {
617             if (invert)
618                 return values[(values.indexOf(this.value) + 1) % values.length];
619
620             switch (operator) {
621             case "+":
622                 return this.value + values;
623             case "-":
624                 return this.value.replace(values, "");
625             case "^":
626                 return values + this.value;
627             case "=":
628                 return values;
629             }
630             return null;
631         },
632
633         stringmap: function stringmap(operator, values, scope, invert) {
634             let res = update({}, this.value);
635
636             switch (operator) {
637             // The result is the same.
638             case "+":
639             case "^":
640                 return update(res, values);
641             case "-":
642                 for (let [k, v] in Iterator(values))
643                     if (v === res[k])
644                         delete res[k];
645                 return res;
646             case "=":
647                 if (invert) {
648                     for (let [k, v] in Iterator(values))
649                         if (v === res[k])
650                             delete res[k];
651                         else
652                             res[k] = v;
653                     return res;
654                 }
655                 return values;
656             }
657             return null;
658         },
659
660         stringlist: function stringlist(operator, values, scope, invert) {
661             values = Array.concat(values);
662
663             function uniq(ary) {
664                 let seen = {};
665                 return ary.filter(function (elem) !Set.add(seen, elem));
666             }
667
668             switch (operator) {
669             case "+":
670                 return uniq(Array.concat(this.value, values), true);
671             case "^":
672                 // NOTE: Vim doesn't prepend if there's a match in the current value
673                 return uniq(Array.concat(values, this.value), true);
674             case "-":
675                 return this.value.filter(function (item) !Set.has(this, item), Set(values));
676             case "=":
677                 if (invert) {
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);
681                 }
682                 return values;
683             }
684             return null;
685         },
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
691     },
692
693     validIf: function validIf(test, error) {
694         if (test)
695             return true;
696         throw ValueError(error);
697     },
698
699     /**
700      * Validates the specified *values* against values generated by the
701      * option's completer function.
702      *
703      * @param {value|[string]} values The value or array of values to validate.
704      * @returns {boolean}
705      */
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]);
711         };
712
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));
717         }
718
719         if (this.values)
720             var acceptable = this.values.array || this.values;
721         else
722             acceptable = completions.call(this);
723
724         if (isArray(acceptable))
725             acceptable = Set(acceptable.map(function ([k]) k));
726
727         if (this.type === "regexpmap" || this.type === "sitemap")
728             return Array.concat(vals).every(function (re) Set.has(acceptable, re.result));
729
730         return Array.concat(vals).every(Set.has(acceptable));
731     },
732
733     types: {}
734 });
735
736 ["Boolean",
737  "Charlist",
738  "Number",
739  "RegexpList",
740  "RegexpMap",
741  "SiteList",
742  "SiteMap",
743  "String",
744  "StringList",
745  "StringMap"].forEach(function (name) {
746      let type = name.toLowerCase();
747      let class_ = Class(name + "Option", Option, {
748          type: type,
749
750          _op: Option.ops[type]
751      });
752
753     if (type in Option.getKey)
754         class_.prototype.getKey = Option.getKey[type];
755
756     if (type in Option.parse)
757         class_.prototype.parse = Option.parse[type];
758
759     if (type in Option.stringify)
760         class_.prototype.stringify = Option.stringify[type];
761
762     if (type in Option.domains)
763         class_.prototype.domains = Option.domains[type];
764
765     if (type in Option.testValues)
766         class_.prototype.testValues = Option.testValues[type];
767
768     Option.types[type] = class_;
769     this[class_.className] = class_;
770     EXPORTED_SYMBOLS.push(class_.className);
771 }, this);
772
773 update(BooleanOption.prototype, {
774     names: Class.Memoize(function ()
775                 array.flatten([[name, "no" + name] for (name in values(this.realNames))]))
776 });
777
778 var OptionHive = Class("OptionHive", Contexts.Hive, {
779     init: function init(group) {
780         init.supercall(this, group);
781         this.values = {};
782         this.has = Set.has(this.values);
783     },
784
785     add: function add(names, description, type, defaultValue, extraInfo) {
786         return this.modules.options.add(names, description, type, defaultValue, extraInfo);
787     }
788 });
789
790 /**
791  * @instance options
792  */
793 var Options = Module("options", {
794     Local: function Local(dactyl, modules, window) let ({ contexts } = modules) ({
795         init: function init() {
796             const self = this;
797
798             update(this, {
799                 hives: contexts.Hives("options", Class("OptionHive", OptionHive, { modules: modules })),
800                 user: contexts.hives.options.user
801             });
802
803             this.needInit = [];
804             this._options = [];
805             this._optionMap = {};
806
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);
813             }, window);
814
815             modules.cache.register("options.dtd", function ()
816                 util.makeDTD(
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]
821                           for (o in self)),
822
823                          ([["option", o.name, "type"].join("."), o.type] for (o in self)),
824
825                          config.dtd)));
826         },
827
828         signals: {
829             "io.source": function ioSource(context, file, modTime) {
830                 cache.flushEntry("options.dtd", modTime);
831             }
832         },
833
834         dactyl: dactyl,
835
836         /**
837          * Lists all options in *scope* or only those with changed values if
838          * *onlyNonDefault* is specified.
839          *
840          * @param {function(Option)} filter Limit the list
841          * @param {number} scope Only list options in this scope (see
842          *     {@link Option#scope}).
843          */
844         list: function list(filter, scope) {
845             if (!scope)
846                 scope = Option.SCOPE_BOTH;
847
848             function opts(opt) {
849                 for (let opt in Iterator(this)) {
850                     let option = {
851                         __proto__: opt,
852                         isDefault: opt.isDefault,
853                         default:   opt.stringDefaultValue,
854                         pre:       "\u00a0\u00a0", // Unicode nonbreaking space.
855                         value:     <></>
856                     };
857
858                     if (filter && !filter(opt))
859                         continue;
860                     if (!(opt.scope & scope))
861                         continue;
862
863                     if (opt.type == "boolean") {
864                         if (!opt.value)
865                             option.pre = "no";
866                         option.default = (opt.defaultValue ? "" : "no") + opt.name;
867                     }
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></>)}</>;
872                     else
873                         option.value = <>={template.highlight(opt.stringValue)}</>;
874                     yield option;
875                 }
876             };
877
878             modules.commandline.commandOutput(template.options("Options", opts.call(this), this["verbose"] > 0));
879         },
880
881         cleanup: function cleanup() {
882             for (let opt in this)
883                 if (opt.cleanupValue != null)
884                     opt.stringValue = opt.cleanupValue;
885         },
886
887         /**
888          * Adds a new option.
889          *
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}).
896          * @optional
897          */
898         add: function add(names, description, type, defaultValue, extraInfo) {
899             const self = this;
900
901             if (!util.isDactyl(Components.stack.caller))
902                 deprecated.warn(add, "options.add", "group.options.add");
903
904             util.assert(type in Option.types, _("option.noSuchType", type),
905                         false);
906
907             if (!extraInfo)
908                 extraInfo = {};
909
910             extraInfo.definedAt = contexts.getCaller(Components.stack.caller);
911
912             let name = names[0];
913             if (name in this._optionMap) {
914                 this.dactyl.log(_("option.replaceExisting", name.quote()), 1);
915                 this.remove(name);
916             }
917
918             let closure = function () self._optionMap[name];
919
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);
923
924             if (extraInfo.setter && (!extraInfo.scope || extraInfo.scope & Option.SCOPE_GLOBAL))
925                 if (this.dactyl.initialized)
926                     closure().initValue();
927                 else
928                     memoize(this.needInit, this.needInit.length, closure);
929
930             this._floptions = (this._floptions || []).concat(name);
931             memoize(this._options, this._options.length, closure);
932
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; });
936         }
937     }),
938
939     /** @property {Iterator(Option)} @private */
940     __iterator__: function __iterator__()
941         values(this._options.sort(function (a, b) String.localeCompare(a.name, b.name))),
942
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)),
955
956     cleanupPrefs: Class.Memoize(function () config.prefs.Branch("cleanup.option.")),
957
958     cleanup: function cleanup(reason) {
959         if (~["disable", "uninstall"].indexOf(reason))
960             this.cleanupPrefs.resetBranch();
961     },
962
963     /**
964      * Returns the option with *name* in the specified *scope*.
965      *
966      * @param {string} name The option's name.
967      * @param {number} scope The option's scope (see {@link Option#scope}).
968      * @optional
969      * @returns {Option} The matching option.
970      */
971     get: function get(name, scope) {
972         if (!scope)
973             scope = Option.SCOPE_BOTH;
974
975         if (this._optionMap[name] && (this._optionMap[name].scope & scope))
976             return this._optionMap[name];
977         return null;
978     },
979
980     /**
981      * Parses a :set command's argument string.
982      *
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}
986      * @optional
987      * @returns {Object} The parsed command object.
988      */
989     parseOpt: function parseOpt(args, modifiers) {
990         let res = {};
991         let matches, prefix, postfix;
992
993         [matches, prefix, res.name, postfix, res.valueGiven, res.operator, res.value] =
994         args.match(/^\s*(no|inv)?([^=]+?)([?&!])?\s*(([-+^]?)=(.*))?\s*$/) || [];
995
996         res.args = args;
997         res.onlyNonDefault = false; // used for :set to print non-default options
998         if (!args) {
999             res.name = "all";
1000             res.onlyNonDefault = true;
1001         }
1002
1003         if (matches) {
1004             if (res.option = this.get(res.name, res.scope)) {
1005                 if (prefix === "no" && res.option.type !== "boolean")
1006                     res.option = null;
1007             }
1008             else if (res.option = this.get(prefix + res.name, res.scope)) {
1009                 res.name = prefix + res.name;
1010                 prefix = "";
1011             }
1012         }
1013
1014         res.prefix = prefix;
1015         res.postfix = postfix;
1016
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");
1022
1023         res.scope = modifiers && modifiers.scope;
1024
1025         if (!res.option)
1026             return res;
1027
1028         if (res.value === undefined)
1029             res.value = "";
1030
1031         res.optionValue = res.option.get(res.scope);
1032
1033         try {
1034             if (!res.invert || res.option.type != "number") // Hack.
1035                 res.values = res.option.parse(res.value);
1036         }
1037         catch (e) {
1038             res.error = e;
1039         }
1040
1041         return res;
1042     },
1043
1044     /**
1045      * Remove the option with matching *name*.
1046      *
1047      * @param {string} name The name of the option to remove. This can be
1048      *     any of the option's names.
1049      */
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];
1055     },
1056
1057     /** @property {Object} The options store. */
1058     get store() storage.options
1059 }, {
1060 }, {
1061     commands: function initCommands(dactyl, modules, window) {
1062         const { commands, contexts, options } = modules;
1063
1064         let args = {
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 };
1070             },
1071             format: {
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"))
1076                               })</span>
1077                             : <></>}
1078                         {template.linkifyHelp(map.description)}
1079                 </>)
1080             }
1081         };
1082
1083         dactyl.addUsageCommand({
1084             name: ["listo[ptions]", "lo"],
1085             description: "List all options along with their short descriptions",
1086             index: "option",
1087             iterate: function (args) options,
1088             format: {
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)}
1093                 </>),
1094                 help: function (opt) "'" + opt.name + "'"
1095             }
1096         });
1097
1098         function setAction(args, modifiers) {
1099             let bang = args.bang;
1100             if (!args.length)
1101                 args[0] = "";
1102
1103             let list = [];
1104             function flushList() {
1105                 let names = Set(list.map(function (opt) opt.option ? opt.option.name : ""));
1106                 if (list.length)
1107                     if (list.some(function (opt) opt.all))
1108                         options.list(function (opt) !(list[0].onlyNonDefault && opt.isDefault), list[0].scope);
1109                     else
1110                         options.list(function (opt) Set.has(names, opt.name), list[0].scope);
1111                 list = [];
1112             }
1113
1114             for (let [, arg] in args) {
1115                 if (bang) {
1116                     let onlyNonDefault = false;
1117                     let reset = false;
1118                     let invertBoolean = false;
1119
1120                     if (args[0] == "") {
1121                         var name = "all";
1122                         onlyNonDefault = true;
1123                     }
1124                     else {
1125                         var [matches, name, postfix, valueGiven, operator, value] =
1126                             arg.match(/^\s*?((?:[^=\\']|\\.|'[^']*')+?)([?&!])?\s*(([-+^]?)=(.*))?\s*$/);
1127                         reset = (postfix == "&");
1128                         invertBoolean = (postfix == "!");
1129                     }
1130
1131                     name = Option.dequote(name);
1132                     if (name == "all" && reset)
1133                         modules.commandline.input(_("pref.prompt.resetAll", config.host) + " ",
1134                             function (resp) {
1135                                 if (resp == "yes")
1136                                     for (let pref in values(prefs.getNames()))
1137                                         prefs.reset(pref);
1138                             },
1139                             { promptHighlight: "WarningMsg" });
1140                     else if (name == "all")
1141                         modules.commandline.commandOutput(prefs.list(onlyNonDefault, ""));
1142                     else if (reset)
1143                         prefs.reset(name);
1144                     else if (invertBoolean)
1145                         prefs.toggle(name);
1146                     else if (valueGiven) {
1147                         if (value == undefined)
1148                             value = "";
1149                         else if (value == "true")
1150                             value = true;
1151                         else if (value == "false")
1152                             value = false;
1153                         else if (Number(value) % 1 == 0)
1154                             value = parseInt(value);
1155                         else
1156                             value = Option.dequote(value);
1157
1158                         if (operator)
1159                             value = Option.ops[typeof value].call({ value: prefs.get(name) }, operator, value);
1160                         prefs.set(name, value);
1161                     }
1162                     else
1163                         modules.commandline.commandOutput(prefs.list(onlyNonDefault, name));
1164                     return;
1165                 }
1166
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));
1170
1171                 let option = opt.option;
1172                 util.assert(option != null || opt.all, _("command.set.unknownOption", opt.name));
1173
1174                 // reset a variable to its default value
1175                 if (opt.reset) {
1176                     flushList();
1177                     if (opt.all) {
1178                         for (let option in modules.options)
1179                             option.reset();
1180                     }
1181                     else {
1182                         option.reset();
1183                     }
1184                 }
1185                 // read access
1186                 else if (opt.get)
1187                     list.push(opt);
1188                 // write access
1189                 else {
1190                     flushList();
1191                     if (opt.option.type === "boolean") {
1192                         util.assert(!opt.valueGiven, _("error.invalidArgument", arg));
1193                         opt.values = !opt.unsetBoolean;
1194                     }
1195                     else if (/^(string|number)$/.test(opt.option.type) && opt.invert)
1196                         opt.values = Option.splitList(opt.value);
1197                     try {
1198                         var res = opt.option.op(opt.operator || "=", opt.values, opt.scope, opt.invert,
1199                                                 opt.value);
1200                     }
1201                     catch (e) {
1202                         res = e;
1203                     }
1204                     if (res)
1205                         dactyl.echoerr(res);
1206                     option.setFrom = contexts.getCaller(null);
1207                 }
1208             }
1209             flushList();
1210         }
1211
1212         function setCompleter(context, args, modifiers) {
1213             const { completion } = modules;
1214
1215             let filter = context.filter;
1216
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);
1221
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);
1227                     return null;
1228                 }
1229
1230                 return completion.preference(context);
1231             }
1232
1233             let opt = modules.options.parseOpt(filter, modifiers);
1234             let prefix = opt.prefix;
1235
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);
1241             }
1242
1243             function error(length, message) {
1244                 context.message = message;
1245                 context.highlight(0, length, "SPELLCHECK");
1246             }
1247
1248             let option = opt.option;
1249             if (!option)
1250                 return error(opt.name.length, _("option.noSuch", opt.name));
1251
1252             context.advance(context.filter.indexOf("="));
1253             if (option.type == "boolean")
1254                 return error(context.filter.length, _("error.trailingCharacters"));
1255
1256             context.advance(1);
1257             if (opt.error)
1258                 return error(context.filter.length, opt.error);
1259
1260             if (opt.get || opt.reset || !option || prefix)
1261                 return null;
1262
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, ""];
1272                 });
1273             }
1274
1275             let optcontext = context.fork("values");
1276             modules.completion.optionValue(optcontext, opt.name, opt.operator);
1277
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;
1284
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, ""]);
1289                                        });
1290                 context.title = ["Current values"];
1291             }
1292         }
1293
1294         // TODO: deprecated. This needs to support "g:"-prefixed globals at a
1295         // minimum for now.  The coderepos plugins make extensive use of global
1296         // variables.
1297         commands.add(["let"],
1298             "Set or list a variable",
1299             function (args) {
1300                 let globalVariables = dactyl._globalVariables;
1301                 args = (args[0] || "").trim();
1302                 function fmt(value) (typeof value == "number"   ? "#" :
1303                                      typeof value == "function" ? "*" :
1304                                                                   " ") + value;
1305                 if (!args || args == "g:") {
1306                     let str =
1307                         <table>
1308                         {
1309                             template.map(globalVariables, function ([i, value]) {
1310                                 return <tr>
1311                                             <td style="width: 200px;">{i}</td>
1312                                             <td>{fmt(value)}</td>
1313                                        </tr>;
1314                             })
1315                         }
1316                         </table>;
1317                     if (str.text().length() == str.*.length())
1318                         dactyl.echomsg(_("variable.none"));
1319                     else
1320                         dactyl.echo(str, modules.commandline.FORCE_MULTILINE);
1321                     return;
1322                 }
1323
1324                 let matches = args.match(/^([a-z]:)?([\w]+)(?:\s*([-+.])?=\s*(.*)?)?$/);
1325                 if (matches) {
1326                     let [, scope, name, op, expr] = matches;
1327                     let fullName = (scope || "") + name;
1328
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));
1333
1334                     if (!expr)
1335                         dactyl.echo(fullName + "\t\t" + fmt(globalVariables[name]));
1336                     else {
1337                         try {
1338                             var newValue = dactyl.userEval(expr);
1339                         }
1340                         catch (e) {}
1341                         util.assert(newValue !== undefined,
1342                             _("command.let.invalidExpression", expr));
1343
1344                         let value = newValue;
1345                         if (op) {
1346                             value = globalVariables[name];
1347                             if (op == "+")
1348                                 value += newValue;
1349                             else if (op == "-")
1350                                 value -= newValue;
1351                             else if (op == ".")
1352                                 value += String(newValue);
1353                         }
1354                         globalVariables[name] = value;
1355                     }
1356                 }
1357                 else
1358                     dactyl.echoerr(_("command.let.unexpectedChar"));
1359             },
1360             {
1361                 deprecated: "the options system",
1362                 literal: 0
1363             }
1364         );
1365
1366         [
1367             {
1368                 names: ["setl[ocal]"],
1369                 description: "Set local option",
1370                 modifiers: { scope: Option.SCOPE_LOCAL }
1371             },
1372             {
1373                 names: ["setg[lobal]"],
1374                 description: "Set global option",
1375                 modifiers: { scope: Option.SCOPE_GLOBAL }
1376             },
1377             {
1378                 names: ["se[t]"],
1379                 description: "Set an option",
1380                 modifiers: {},
1381                 extra: {
1382                     serialize: function () [
1383                         {
1384                             command: this.name,
1385                             literalArg: [opt.type == "boolean" ? (opt.value ? "" : "no") + opt.name
1386                                                                : opt.name + "=" + opt.stringValue]
1387                         }
1388                         for (opt in modules.options)
1389                         if (!opt.getter && !opt.isDefault && (opt.scope & Option.SCOPE_GLOBAL))
1390                     ]
1391                 }
1392             }
1393         ].forEach(function (params) {
1394             commands.add(params.names, params.description,
1395                 function (args, modifiers) {
1396                     setAction(args, update(modifiers, params.modifiers));
1397                 },
1398                 update({
1399                     bang: true,
1400                     completer: setCompleter,
1401                     domains: function domains(args) array.flatten(args.map(function (spec) {
1402                         try {
1403                             let opt = modules.options.parseOpt(spec);
1404                             if (opt.option && opt.option.domains)
1405                                 return opt.option.domains(opt.values);
1406                         }
1407                         catch (e) {
1408                             util.reportError(e);
1409                         }
1410                         return [];
1411                     })),
1412                     keepQuotes: true,
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));
1418                     })
1419                 }, params.extra || {}));
1420         });
1421
1422         // TODO: deprecated. This needs to support "g:"-prefixed globals at a
1423         // minimum for now.
1424         commands.add(["unl[et]"],
1425             "Delete a variable",
1426             function (args) {
1427                 for (let [, name] in args) {
1428                     name = name.replace(/^g:/, ""); // throw away the scope prefix
1429                     if (!Set.has(dactyl._globalVariables, name)) {
1430                         if (!args.bang)
1431                             dactyl.echoerr(_("command.let.noSuch", name));
1432                         return;
1433                     }
1434
1435                     delete dactyl._globalVariables[name];
1436                 }
1437             },
1438             {
1439                 argCount: "+",
1440                 bang: true,
1441                 deprecated: "the options system"
1442             });
1443     },
1444     completion: function initCompletion(dactyl, modules, window) {
1445         const { completion } = modules;
1446
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)
1455                                                                 : opt.names;
1456             if (scope)
1457                 context.filters.push(function ({ item }) item.scope & scope);
1458         };
1459
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)
1464                 return;
1465
1466             try {
1467                 var curValues = curValue != null ? opt.parse(curValue) : opt.value;
1468                 var newValues = opt.parse(context.filter);
1469             }
1470             catch (e) {
1471                 context.message = _("error.error", e);
1472                 context.completions = [];
1473                 return;
1474             }
1475
1476             let extra = {};
1477             switch (opt.type) {
1478             case "boolean":
1479                 return;
1480             case "sitelist":
1481             case "regexplist":
1482                 newValues = Option.splitList(context.filter);
1483                 // Fallthrough
1484             case "stringlist":
1485                 break;
1486             case "charlist":
1487                 Option._splitAt = newValues.length;
1488                 break;
1489             case "stringmap":
1490             case "sitemap":
1491             case "regexpmap":
1492                 let vals = Option.splitList(context.filter);
1493                 let target = vals.pop() || "";
1494
1495                 let [count, key, quote] = Commands.parseArg(target, /:/, true);
1496                 let split = Option._splitAt;
1497
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(","));
1501
1502                 Option._splitAt = split + (extra.value == null ? 0 : count + 1);
1503                 break;
1504             }
1505             // TODO: Highlight when invalid
1506             context.advance(Option._splitAt);
1507             context.filter = Option.dequote(context.filter);
1508
1509             function val(obj) {
1510                 if (isArray(opt.defaultValue)) {
1511                     let val = array.nth(obj, function (re) re.key == extra.key, 0);
1512                     return val && val.result;
1513                 }
1514                 if (Set.has(opt.defaultValue, extra.key))
1515                     return obj[extra.key];
1516             }
1517
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);
1524                 });
1525                 context = context.fork("stuff", 0);
1526             }
1527
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);
1534                 if (op == "+")
1535                     context.filters.push(function (i) curValues.indexOf(i.text) == -1);
1536                 if (op == "-")
1537                     context.filters.push(function (i) curValues.indexOf(i.text) > -1);
1538
1539                 memoize(extra, "values", function () {
1540                     if (op == "+")
1541                         return curValues.concat(newValues);
1542                     if (op == "-")
1543                         return curValues.filter(function (v) newValues.indexOf(val) == -1);
1544                     return newValues;
1545                 });
1546             }
1547
1548             let res = completer.call(opt, context, extra);
1549             if (res)
1550                 context.completions = res;
1551         };
1552     },
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))]);
1556     },
1557     sanitizer: function initSanitizer(dactyl, modules, window) {
1558         const { sanitizer } = modules;
1559
1560         sanitizer.addItem("options", {
1561             description: "Options containing hostname data",
1562             action: function sanitize_action(timespan, host) {
1563                 if (host)
1564                     for (let opt in values(modules.options._options))
1565                         if (timespan.contains(opt.lastSet * 1000) && opt.domains)
1566                             try {
1567                                 opt.value = opt.filterDomain(host, opt.value);
1568                             }
1569                             catch (e) {
1570                                 dactyl.reportError(e);
1571                             }
1572             },
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;
1577             },
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;
1583                     }
1584             }
1585         });
1586     }
1587 });
1588
1589 endModule();
1590
1591 } catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1592
1593 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: