]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/styles.jsm
Import r6923 from upstream hg supporting Firefox up to 22.0a1
[dactyl.git] / common / modules / styles.jsm
1 // Copyright (c) 2008-2012 Kris Maglione <maglione.k at Gmail>
2 //
3 // This work is licensed for reuse under an MIT license. Details are
4 // given in the LICENSE.txt file included with this file.
5 "use strict";
6
7 defineModule("styles", {
8     exports: ["Style", "Styles", "styles"],
9     require: ["services", "util"]
10 });
11
12 lazyRequire("contexts", ["Contexts"]);
13 lazyRequire("template", ["template"]);
14
15 function cssUri(css) "chrome-data:text/css," + encodeURI(css);
16 var namespace = "@namespace html " + XHTML.quote() + ";\n" +
17                 "@namespace xul " + XUL.quote() + ";\n" +
18                 "@namespace dactyl " + NS.quote() + ";\n";
19
20 var Sheet = Struct("name", "id", "sites", "css", "hive", "agent");
21 Sheet.liveProperty = function (name) {
22     let i = this.prototype.members[name];
23     this.prototype.__defineGetter__(name, function () this[i]);
24     this.prototype.__defineSetter__(name, function (val) {
25         if (isArray(val))
26             val = Array.slice(val);
27         if (isArray(val))
28             Object.freeze(val);
29         this[i] = val;
30         this.enabled = this.enabled;
31     });
32 }
33 Sheet.liveProperty("agent");
34 Sheet.liveProperty("css");
35 Sheet.liveProperty("sites");
36 update(Sheet.prototype, {
37     formatSites: function (uris)
38           template.map(this.sites,
39                        function (filter) ["span", { highlight: uris.some(Styles.matchFilter(filter)) ? "Filter" : "" }, filter],
40                        ","),
41
42     remove: function () { this.hive.remove(this); },
43
44     get uri() "dactyl://style/" + this.id + "/" + this.hive.name + "/" + (this.name || ""),
45
46     get enabled() this._enabled,
47     set enabled(on) {
48         if (on != this._enabled || this.fullCSS != this._fullCSS) {
49             if (on)
50                 this.enabled = false;
51             else if (!this._fullCSS)
52                 return;
53
54             let meth = on ? "registerSheet" : "unregisterSheet";
55             styles[meth](this.uri, on ? this.agent : this._agent);
56
57             this._agent = this.agent;
58             this._enabled = Boolean(on);
59             this._fullCSS = this.fullCSS;
60         }
61     },
62
63     match: function (uri) {
64         if (isString(uri))
65             uri = util.newURI(uri);
66         return this.sites.some(function (site) Styles.matchFilter(site, uri));
67     },
68
69     get fullCSS() {
70         let filter = this.sites;
71         let css = this.css;
72
73         let preamble = "/* " + this.uri + (this.agent ? " (agent)" : "") + " */\n\n" + namespace + "\n";
74         if (filter[0] == "*")
75             return preamble + css;
76
77         let selectors = filter.map(function (part)
78                                     !/^(?:[a-z-]+[:*]|[a-z-.]+$)/i.test(part) ? "regexp(" + Styles.quote(".*(?:" + part + ").*") + ")" :
79                                        (/[*]$/.test(part)   ? "url-prefix" :
80                                         /[\/:]/.test(part)  ? "url"
81                                                             : "domain")
82                                        + '(' + Styles.quote(part.replace(/\*$/, "")) + ')')
83                               .join(",\n               ");
84
85         return preamble + "@-moz-document " + selectors + " {\n\n" + css + "\n\n}\n";
86     }
87 });
88
89 var Hive = Class("Hive", {
90     init: function (name, persist) {
91         this.name = name;
92         this.sheets = [];
93         this.names = {};
94         this.refs = [];
95         this.persist = persist;
96     },
97
98     get modifiable() this.name !== "system",
99
100     addRef: function (obj) {
101         this.refs.push(util.weakReference(obj));
102         this.dropRef(null);
103     },
104     dropRef: function (obj) {
105         this.refs = this.refs.filter(function (ref) ref.get() && ref.get() !== obj);
106         if (!this.refs.length) {
107             this.cleanup();
108             styles.hives = styles.hives.filter(function (h) h !== this, this);
109         }
110     },
111
112     cleanup: function cleanup() {
113         for (let sheet in values(this.sheets))
114             sheet.enabled = false;
115     },
116
117     __iterator__: function () Iterator(this.sheets),
118
119     get sites() array(this.sheets).map(function (s) s.sites).flatten().uniq().array,
120
121     /**
122      * Add a new style sheet.
123      *
124      * @param {string} name The name given to the style sheet by
125      *     which it may be later referenced.
126      * @param {string} filter The sites to which this sheet will
127      *     apply. Can be a domain name or a URL. Any URL ending in
128      *     "*" is matched as a prefix.
129      * @param {string} css The CSS to be applied.
130      * @param {boolean} agent If true, the sheet is installed as an
131      *     agent sheet.
132      * @param {boolean} lazy If true, the sheet is not initially enabled.
133      * @returns {Sheet}
134      */
135     add: function add(name, filter, css, agent, lazy) {
136
137         if (!isArray(filter))
138             filter = filter.split(",");
139         if (name && name in this.names) {
140             var sheet = this.names[name];
141             sheet.agent = agent;
142             sheet.css = String(css);
143             sheet.sites = filter;
144         }
145         else {
146             sheet = Sheet(name, styles._id++, filter.filter(util.identity), String(css), this, agent);
147             this.sheets.push(sheet);
148         }
149
150         styles.allSheets[sheet.id] = sheet;
151
152         if (!lazy)
153             sheet.enabled = true;
154
155         if (name)
156             this.names[name] = sheet;
157         return sheet;
158     },
159
160     /**
161      * Get a sheet with a given name or index.
162      *
163      * @param {string or number} sheet The sheet to retrieve. Strings indicate
164      *     sheet names, while numbers indicate indices.
165      */
166     get: function get(sheet) {
167         if (typeof sheet === "number")
168             return this.sheets[sheet];
169         return this.names[sheet];
170     },
171
172     /**
173      * Find sheets matching the parameters. See {@link #addSheet}
174      * for parameters.
175      *
176      * @param {string} name
177      * @param {string} filter
178      * @param {string} css
179      * @param {number} index
180      */
181     find: function find(name, filter, css, index) {
182         // Grossly inefficient.
183         let matches = [k for ([k, v] in Iterator(this.sheets))];
184         if (index)
185             matches = String(index).split(",").filter(function (i) i in this.sheets, this);
186         if (name)
187             matches = matches.filter(function (i) this.sheets[i].name == name, this);
188         if (css)
189             matches = matches.filter(function (i) this.sheets[i].css == css, this);
190         if (filter)
191             matches = matches.filter(function (i) this.sheets[i].sites.indexOf(filter) >= 0, this);
192         return matches.map(function (i) this.sheets[i], this);
193     },
194
195     /**
196      * Remove a style sheet. See {@link #addSheet} for parameters.
197      * In cases where *filter* is supplied, the given filters are removed from
198      * matching sheets. If any remain, the sheet is left in place.
199      *
200      * @param {string} name
201      * @param {string} filter
202      * @param {string} css
203      * @param {number} index
204      */
205     remove: function remove(name, filter, css, index) {
206         let self = this;
207         if (arguments.length == 1) {
208             var matches = [name];
209             name = null;
210         }
211
212         if (filter && filter.indexOf(",") > -1)
213             return filter.split(",").reduce(
214                 function (n, f) n + self.removeSheet(name, f, index), 0);
215
216         if (filter == undefined)
217             filter = "";
218
219         if (!matches)
220             matches = this.findSheets(name, filter, css, index);
221         if (matches.length == 0)
222             return null;
223
224         for (let [, sheet] in Iterator(matches.reverse())) {
225             if (filter) {
226                 let sites = sheet.sites.filter(function (f) f != filter);
227                 if (sites.length) {
228                     sheet.sites = sites;
229                     continue;
230                 }
231             }
232             sheet.enabled = false;
233             if (sheet.name)
234                 delete this.names[sheet.name];
235             delete styles.allSheets[sheet.id];
236         }
237         this.sheets = this.sheets.filter(function (s) matches.indexOf(s) == -1);
238         return matches.length;
239     },
240 });
241
242 /**
243  * Manages named and unnamed user style sheets, which apply to both
244  * chrome and content pages.
245  *
246  * @author Kris Maglione <maglione.k@gmail.com>
247  */
248 var Styles = Module("Styles", {
249     Local: function (dactyl, modules, window) ({
250         cleanup: function () {}
251     }),
252
253     init: function () {
254         this._id = 0;
255         this.cleanup();
256         this.allSheets = {};
257
258         update(services["dactyl:"].providers, {
259             "style": function styleProvider(uri, path) {
260                 let id = parseInt(path);
261                 if (Set.has(styles.allSheets, id))
262                     return ["text/css", styles.allSheets[id].fullCSS];
263                 return null;
264             }
265         });
266     },
267
268     cleanup: function cleanup() {
269         for each (let hive in this.hives)
270             util.trapErrors("cleanup", hive);
271         this.hives = [];
272         this.user = this.addHive("user", this, true);
273         this.system = this.addHive("system", this, false);
274     },
275
276     addHive: function addHive(name, ref, persist) {
277         let hive = array.nth(this.hives, function (h) h.name === name, 0);
278         if (!hive) {
279             hive = Hive(name, persist);
280             this.hives.push(hive);
281         }
282         hive.persist = persist;
283         if (ref)
284             hive.addRef(ref);
285         return hive;
286     },
287
288     __iterator__: function () Iterator(this.user.sheets.concat(this.system.sheets)),
289
290     _proxy: function (name, args)
291         let (obj = this[args[0] ? "system" : "user"])
292             obj[name].apply(obj, Array.slice(args, 1)),
293
294     addSheet: deprecated("Styles#{user,system}.add", function addSheet() this._proxy("add", arguments)),
295     findSheets: deprecated("Styles#{user,system}.find", function findSheets() this._proxy("find", arguments)),
296     get: deprecated("Styles#{user,system}.get", function get() this._proxy("get", arguments)),
297     removeSheet: deprecated("Styles#{user,system}.remove", function removeSheet() this._proxy("remove", arguments)),
298
299     userSheets: Class.Property({ get: deprecated("Styles#user.sheets", function userSheets() this.user.sheets) }),
300     systemSheets: Class.Property({ get: deprecated("Styles#system.sheets", function systemSheets() this.system.sheets) }),
301     userNames: Class.Property({ get: deprecated("Styles#user.names", function userNames() this.user.names) }),
302     systemNames: Class.Property({ get: deprecated("Styles#system.names", function systemNames() this.system.names) }),
303     sites: Class.Property({ get: deprecated("Styles#user.sites", function sites() this.user.sites) }),
304
305     list: function list(content, sites, name, hives) {
306         const { commandline, dactyl } = this.modules;
307
308         hives = hives || styles.hives.filter(function (h) h.modifiable && h.sheets.length);
309
310         function sheets(group)
311             group.sheets.slice()
312                  .filter(function (sheet) (!name || sheet.name === name) &&
313                                           (!sites || sites.every(function (s) sheet.sites.indexOf(s) >= 0)))
314                  .sort(function (a, b) a.name && b.name ? String.localeCompare(a.name, b.name)
315                                                         : !!b.name - !!a.name || a.id - b.id);
316
317         let uris = util.visibleURIs(content);
318
319         let list = ["table", {},
320                 ["tr", { highlight: "Title" },
321                     ["td"],
322                     ["td"],
323                     ["td", { style: "padding-right: 1em;" }, _("title.Name")],
324                     ["td", { style: "padding-right: 1em;" }, _("title.Filter")],
325                     ["td", { style: "padding-right: 1em;" }, _("title.CSS")]],
326                 ["col", { style: "min-width: 4em; padding-right: 1em;" }],
327                 ["col", { style: "min-width: 1em; text-align: center; color: red; font-weight: bold;" }],
328                 ["col", { style: "padding: 0 1em 0 1ex; vertical-align: top;" }],
329                 ["col", { style: "padding: 0 1em 0 0; vertical-align: top;" }],
330                 template.map(hives, function (hive) let (i = 0) [
331                     ["tr", { style: "height: .5ex;" }],
332                     template.map(sheets(hive), function (sheet)
333                         ["tr", {},
334                             ["td", { highlight: "Title" }, !i++ ? hive.name : ""],
335                             ["td", {}, sheet.enabled ? "" : UTF8("×")],
336                             ["td", {}, sheet.name || hive.sheets.indexOf(sheet)],
337                             ["td", {}, sheet.formatSites(uris)],
338                             ["td", {}, sheet.css]]),
339                     ["tr", { style: "height: .5ex;" }]])];
340
341         // E4X-FIXME
342         // // TODO: Move this to an ItemList to show this automatically
343         // if (list.*.length() === list.text().length() + 5)
344         //     dactyl.echomsg(_("style.none"));
345         // else
346         commandline.commandOutput(list);
347     },
348
349     registerSheet: function registerSheet(url, agent, reload) {
350         let uri = services.io.newURI(url, null, null);
351         if (reload)
352             this.unregisterSheet(url, agent);
353
354         let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
355         if (reload || !services.stylesheet.sheetRegistered(uri, type))
356             services.stylesheet.loadAndRegisterSheet(uri, type);
357     },
358
359     unregisterSheet: function unregisterSheet(url, agent) {
360         let uri = services.io.newURI(url, null, null);
361         let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
362         if (services.stylesheet.sheetRegistered(uri, type))
363             services.stylesheet.unregisterSheet(uri, type);
364     },
365 }, {
366     append: function (dest, src, sort) {
367         let props = {};
368         for each (let str in [dest, src])
369             for (let prop in Styles.propertyIter(str))
370                 props[prop.name] = prop.value;
371
372         let val = Object.keys(props)[sort ? "sort" : "slice"]()
373                         .map(function (prop) prop + ": " + props[prop] + ";")
374                         .join(" ");
375
376         if (/^\s*(\/\*.*?\*\/)/.exec(src))
377             val = RegExp.$1 + " " + val;
378         return val;
379     },
380
381     completeSite: function (context, content, group) {
382         group = group || styles.user;
383         context.anchored = false;
384         try {
385             context.fork("current", 0, this, function (context) {
386                 context.title = ["Current Site"];
387                 context.completions = [
388                     [content.location.host, /*L*/"Current Host"],
389                     [content.location.href, /*L*/"Current URL"]
390                 ];
391             });
392         }
393         catch (e) {}
394
395         let uris = util.visibleURIs(content);
396
397         context.generate = function () values(group.sites);
398
399         context.keys.text = util.identity;
400         context.keys.description = function (site) this.sheets.length + /*L*/" sheet" + (this.sheets.length == 1 ? "" : "s") + ": " +
401             array.compact(this.sheets.map(function (s) s.name)).join(", ");
402         context.keys.sheets = function (site) group.sheets.filter(function (s) s.sites.indexOf(site) >= 0);
403         context.keys.active = function (site) uris.some(Styles.matchFilter(site));
404
405         Styles.splitContext(context, "Sites");
406     },
407
408     /**
409      * A curried function which determines which host names match a
410      * given stylesheet filter. When presented with one argument,
411      * returns a matcher function which, given one nsIURI argument,
412      * returns true if that argument matches the given filter. When
413      * given two arguments, returns true if the second argument matches
414      * the given filter.
415      *
416      * @param {string} filter The URI filter to match against.
417      * @param {nsIURI} uri The location to test.
418      * @returns {nsIURI -> boolean}
419      */
420     matchFilter: function (filter) {
421         filter = filter.trim();
422
423         if (filter === "*")
424             var test = function test(uri) true;
425         else if (!/^(?:[a-z-]+:|[a-z-.]+$)/.test(filter)) {
426             let re = util.regexp(filter);
427             test = function test(uri) re.test(uri.spec);
428         }
429         else if (/[*]$/.test(filter)) {
430             let re = RegExp("^" + util.regexp.escape(filter.substr(0, filter.length - 1)));
431             test = function test(uri) re.test(uri.spec);
432         }
433         else if (/[\/:]/.test(filter))
434             test = function test(uri) uri.spec === filter;
435         else
436             test = function test(uri) { try { return util.isSubdomain(uri.host, filter); } catch (e) { return false; } };
437         test.toString = function toString() filter;
438         test.key = filter;
439         if (arguments.length < 2)
440             return test;
441         return test(arguments[1]);
442     },
443
444     splitContext: function splitContext(context, title) {
445         for (let item in Iterator({ Active: true, Inactive: false })) {
446             let [name, active] = item;
447             context.split(name, null, function (context) {
448                 context.title[0] = /*L*/name + " " + (title || "Sheets");
449                 context.filters.push(function (item) !!item.active == active);
450             });
451         }
452     },
453
454     propertyIter: function (str, always) {
455         let i = 0;
456         for (let match in this.propertyPattern.iterate(str)) {
457             if (match.value || always && match.name || match.wholeMatch === match.preSpace && always && !i++)
458                 yield match;
459             if (!/;/.test(match.postSpace))
460                 break;
461         }
462     },
463
464     propertyPattern: util.regexp(literal(/*
465             (?:
466                 (?P<preSpace> <space>*)
467                 (?P<name> [-a-z]*)
468                 (?:
469                     <space>* : \s* (?P<value>
470                         (?:
471                             [-\w]+
472                             (?:
473                                 \s* \( \s*
474                                     (?: <string> | [^)]*  )
475                                 \s* (?: \) | $)
476                             )?
477                             \s*
478                             | \s* <string> \s*
479                             | <space>*
480                             | [^;}]*
481                         )*
482                     )
483                 )?
484             )
485             (?P<postSpace> <space>* (?: ; | $) )
486         */), "gix",
487         {
488             space: /(?: \s | \/\* .*? \*\/ )/,
489             string: /(?:" (?:[^\\"]|\\.)* (?:"|$) | '(?:[^\\']|\\.)* (?:'|$) )/
490         }),
491
492     patterns: memoize({
493         get property() util.regexp(literal(/*
494                 (?:
495                     (?P<preSpace> <space>*)
496                     (?P<name> [-a-z]*)
497                     (?:
498                         <space>* : \s* (?P<value>
499                             <token>*
500                         )
501                     )?
502                 )
503                 (?P<postSpace> <space>* (?: ; | $) )
504             */), "gix", this),
505
506         get function() util.regexp(literal(/*
507                 (?P<function>
508                     \s* \( \s*
509                         (?: <string> | [^)]*  )
510                     \s* (?: \) | $)
511                 )
512             */), "gx", this),
513
514         space: /(?: \s | \/\* .*? \*\/ )/,
515
516         get string() util.regexp(literal(/*
517                 (?P<string>
518                     " (?:[^\\"]|\\.)* (?:"|$) |
519                     ' (?:[^\\']|\\.)* (?:'|$)
520                 )
521             */), "gx", this),
522
523         get token() util.regexp(literal(/*
524             (?P<token>
525                 (?P<word> [-\w]+)
526                 <function>?
527                 \s*
528                 | (?P<important> !important\b)
529                 | \s* <string> \s*
530                 | <space>+
531                 | [^;}\s]+
532             )
533         */), "gix", this)
534     }),
535
536     /**
537      * Quotes a string for use in CSS stylesheets.
538      *
539      * @param {string} str
540      * @returns {string}
541      */
542     quote: function quote(str) {
543         return '"' + str.replace(/([\\"])/g, "\\$1").replace(/\n/g, "\\00000a") + '"';
544     },
545 }, {
546     commands: function initCommands(dactyl, modules, window) {
547         const { commands, contexts, styles } = modules;
548
549         function sheets(context, args, filter) {
550             let uris = util.visibleURIs(window.content);
551             context.compare = modules.CompletionContext.Sort.number;
552             context.generate = function () args["-group"].sheets;
553             context.keys.active = function (sheet) uris.some(sheet.closure.match);
554             context.keys.description = function (sheet) [sheet.formatSites(uris), ": ", sheet.css.replace("\n", "\\n")];
555             if (filter)
556                 context.filters.push(function ({ item }) filter(item));
557             Styles.splitContext(context);
558         }
559
560         function nameFlag(filter) ({
561             names: ["-name", "-n"],
562             description: "The name of this stylesheet",
563             type: modules.CommandOption.STRING,
564             completer: function (context, args) {
565                 context.keys.text = function (sheet) sheet.name;
566                 context.filters.unshift(function ({ item }) item.name);
567                 sheets(context, args, filter);
568             }
569         });
570
571         commands.add(["sty[le]"],
572             "Add or list user styles",
573             function (args) {
574                 let [filter, css] = args;
575
576                 if (!css)
577                     styles.list(window.content, filter ? filter.split(",") : null, args["-name"], args.explicitOpts["-group"] ? [args["-group"]] : null);
578                 else {
579                     util.assert(args["-group"].modifiable && args["-group"].hive.modifiable,
580                                 _("group.cantChangeBuiltin", _("style.styles")));
581
582                     if (args["-append"]) {
583                         let sheet = args["-group"].get(args["-name"]);
584                         if (sheet) {
585                             filter = array(sheet.sites).concat(filter).uniq().join(",");
586                             css = sheet.css + " " + css;
587                         }
588                     }
589                     let style = args["-group"].add(args["-name"], filter, css, args["-agent"]);
590
591                     if (args["-nopersist"] || !args["-append"] || style.persist === undefined)
592                         style.persist = !args["-nopersist"];
593                 }
594             },
595             {
596                 completer: function (context, args) {
597                     let compl = [];
598                     let sheet = args["-group"].get(args["-name"]);
599                     if (args.completeArg == 0) {
600                         if (sheet)
601                             context.completions = [[sheet.sites.join(","), "Current Value"]];
602                         context.fork("sites", 0, Styles, "completeSite", window.content, args["-group"]);
603                     }
604                     else if (args.completeArg == 1) {
605                         if (sheet)
606                             context.completions = [
607                                 [sheet.css, _("option.currentValue")]
608                             ];
609                         context.fork("css", 0, modules.completion, "css");
610                     }
611                 },
612                 hereDoc: true,
613                 literal: 1,
614                 options: [
615                     { names: ["-agent", "-A"],  description: "Apply style as an Agent sheet" },
616                     { names: ["-append", "-a"], description: "Append site filter and css to an existing, matching sheet" },
617                     contexts.GroupFlag("styles"),
618                     nameFlag(),
619                     { names: ["-nopersist", "-N"], description: "Do not save this style to an auto-generated RC file" }
620                 ],
621                 serialize: function ()
622                     array(styles.hives)
623                         .filter(function (hive) hive.persist)
624                         .map(function (hive)
625                              hive.sheets.filter(function (style) style.persist)
626                                  .sort(function (a, b) String.localeCompare(a.name || "", b.name || ""))
627                                  .map(function (style) ({
628                                     command: "style",
629                                     arguments: [style.sites.join(",")],
630                                     literalArg: style.css,
631                                     options: {
632                                         "-group": hive.name == "user" ? undefined : hive.name,
633                                         "-name": style.name || undefined
634                                     }
635                                 })))
636                         .flatten().array
637             });
638
639         [
640             {
641                 name: ["stylee[nable]", "stye[nable]"],
642                 desc: "Enable a user style sheet",
643                 action: function (sheet) sheet.enabled = true,
644                 filter: function (sheet) !sheet.enabled
645             },
646             {
647                 name: ["styled[isable]", "styd[isable]"],
648                 desc: "Disable a user style sheet",
649                 action: function (sheet) sheet.enabled = false,
650                 filter: function (sheet) sheet.enabled
651             },
652             {
653                 name: ["stylet[oggle]", "styt[oggle]"],
654                 desc: "Toggle a user style sheet",
655                 action: function (sheet) sheet.enabled = !sheet.enabled
656             },
657             {
658                 name: ["dels[tyle]"],
659                 desc: "Remove a user style sheet",
660                 action: function (sheet) sheet.remove(),
661             }
662         ].forEach(function (cmd) {
663             commands.add(cmd.name, cmd.desc,
664                 function (args) {
665                     dactyl.assert(args.bang ^ !!(args[0] || args[1] || args["-name"] || args["-index"]),
666                                   _("error.argumentOrBang"));
667
668                     args["-group"].find(args["-name"], args[0], args.literalArg, args["-index"])
669                                   .forEach(cmd.action);
670                 }, {
671                     bang: true,
672                     completer: function (context, args) {
673                         let uris = util.visibleURIs(window.content);
674
675                         Styles.completeSite(context, window.content, args["-group"]);
676                         if (cmd.filter)
677                             context.filters.push(function ({ sheets }) sheets.some(cmd.filter));
678                     },
679                     literal: 1,
680                     options: [
681                         contexts.GroupFlag("styles"),
682                         {
683                             names: ["-index", "-i"],
684                             type: modules.CommandOption.INT,
685                             completer: function (context, args) {
686                                 context.keys.text = function (sheet) args["-group"].sheets.indexOf(sheet);
687                                 sheets(context, args, cmd.filter);
688                             }
689                         },
690                         nameFlag(cmd.filter)
691                     ]
692                 });
693         });
694     },
695     contexts: function initContexts(dactyl, modules, window) {
696         modules.contexts.Hives("styles",
697             Class("LocalHive", Contexts.Hive, {
698                 init: function init(group) {
699                     init.superapply(this, arguments);
700                     this.hive = styles.addHive(group.name, this, this.persist);
701                 },
702
703                 get names() this.hive.names,
704                 get sheets() this.hive.sheets,
705                 get sites() this.hive.sites,
706
707                 __noSuchMethod__: function __noSuchMethod__(meth, args) {
708                     return this.hive[meth].apply(this.hive, args);
709                 },
710
711                 destroy: function () {
712                     this.hive.dropRef(this);
713                 }
714             }));
715     },
716     completion: function initCompletion(dactyl, modules, window) {
717         const names = Array.slice(DOM(["div"], window.document).style);
718         modules.completion.css = function (context) {
719             context.title = ["CSS Property"];
720             context.keys = { text: function (p) p + ":", description: function () "" };
721
722             for (let match in Styles.propertyIter(context.filter, true))
723                 var lastMatch = match;
724
725             if (lastMatch != null && !lastMatch.value && !lastMatch.postSpace) {
726                 context.advance(lastMatch.index + lastMatch.preSpace.length);
727                 context.completions = names;
728             }
729         };
730     },
731     javascript: function initJavascript(dactyl, modules, window) {
732         modules.JavaScript.setCompleter(["get", "add", "remove", "find"].map(function (m) Hive.prototype[m]),
733             [ // Prototype: (name, filter, css, index)
734                 function (context, obj, args) this.names,
735                 function (context, obj, args) Styles.completeSite(context, window.content),
736                 null,
737                 function (context, obj, args) this.sheets
738             ]);
739     },
740     template: function initTemplate() {
741         let patterns = Styles.patterns;
742
743         template.highlightCSS = function highlightCSS(css) {
744             return this.highlightRegexp(css, patterns.property, function (match) {
745                 if (!match.length)
746                     return [];
747                 return ["", match.preSpace, template.filter(match.name), ": ",
748
749                     template.highlightRegexp(match.value, patterns.token, function (match) {
750                         if (match.function)
751                             return ["", template.filter(match.word),
752                                 template.highlightRegexp(match.function, patterns.string,
753                                     function (match) ["span", { highlight: "String" }, match.string])
754                             ];
755                         if (match.important == "!important")
756                             return ["span", { highlight: "String" }, match.important];
757                         if (match.string)
758                             return ["span", { highlight: "String" }, match.string];
759                         return template._highlightRegexp(match.wholeMatch, /^(\d+)(em|ex|px|in|cm|mm|pt|pc)?/g,
760                                                          function (m, n, u) [
761                                                              ["span", { highlight: "Number" }, n],
762                                                              ["span", { highlight: "Object" }, u || ""]
763                                                          ]);
764                     }),
765                     match.postSpace
766                 ]
767             })
768         }
769     }
770 });
771
772 endModule();
773
774 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
775
776 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: