]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/styles.jsm
Import 1.0rc1 supporting Firefox up to 11.*
[dactyl.git] / common / modules / styles.jsm
1 // Copyright (c) 2008-2011 by 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 Components.utils.import("resource://dactyl/bootstrap.jsm");
8 defineModule("styles", {
9     exports: ["Style", "Styles", "styles"],
10     require: ["services", "util"]
11 }, this);
12
13 function cssUri(css) "chrome-data:text/css," + encodeURI(css);
14 var namespace = "@namespace html " + XHTML.uri.quote() + ";\n" +
15                 "@namespace xul " + XUL.uri.quote() + ";\n" +
16                 "@namespace dactyl " + NS.uri.quote() + ";\n";
17
18 var Sheet = Struct("name", "id", "sites", "css", "hive", "agent");
19 Sheet.liveProperty = function (name) {
20     let i = this.prototype.members[name];
21     this.prototype.__defineGetter__(name, function () this[i]);
22     this.prototype.__defineSetter__(name, function (val) {
23         if (isArray(val))
24             val = Array.slice(val);
25         if (isArray(val))
26             Object.freeze(val);
27         this[i] = val;
28         this.enabled = this.enabled;
29     });
30 }
31 Sheet.liveProperty("agent");
32 Sheet.liveProperty("css");
33 Sheet.liveProperty("sites");
34 update(Sheet.prototype, {
35     formatSites: function (uris)
36           template.map(this.sites,
37                        function (filter) <span highlight={uris.some(Styles.matchFilter(filter)) ? "Filter" : ""}>{filter}</span>,
38                        <>,</>),
39
40     remove: function () { this.hive.remove(this); },
41
42     get uri() "dactyl://style/" + this.id + "/" + this.hive.name + "/" + (this.name || ""),
43
44     get enabled() this._enabled,
45     set enabled(on) {
46         if (on != this._enabled || this.fullCSS != this._fullCSS) {
47             if (on)
48                 this.enabled = false;
49             else if (!this._fullCSS)
50                 return;
51
52             let meth = on ? "registerSheet" : "unregisterSheet";
53             styles[meth](this.uri, on ? this.agent : this._agent);
54
55             this._agent = this.agent;
56             this._enabled = Boolean(on);
57             this._fullCSS = this.fullCSS;
58         }
59     },
60
61     match: function (uri) {
62         if (isString(uri))
63             uri = util.newURI(uri);
64         return this.sites.some(function (site) Styles.matchFilter(site, uri));
65     },
66
67     get fullCSS() {
68         let filter = this.sites;
69         let css = this.css;
70
71         let preamble = "/* " + this.uri + (this.agent ? " (agent)" : "") + " */\n\n" + namespace + "\n";
72         if (filter[0] == "*")
73             return preamble + css;
74
75         let selectors = filter.map(function (part)
76                                     !/^(?:[a-z-]+[:*]|[a-z-.]+$)/i.test(part) ? "regexp(" + Styles.quote(".*(?:" + part + ").*") + ")" :
77                                        (/[*]$/.test(part)   ? "url-prefix" :
78                                         /[\/:]/.test(part)  ? "url"
79                                                             : "domain")
80                                        + '(' + Styles.quote(part.replace(/\*$/, "")) + ')')
81                               .join(",\n               ");
82
83         return preamble + "@-moz-document " + selectors + " {\n\n" + css + "\n\n}\n";
84     }
85 });
86
87 var Hive = Class("Hive", {
88     init: function (name, persist) {
89         this.name = name;
90         this.sheets = [];
91         this.names = {};
92         this.refs = [];
93         this.persist = persist;
94     },
95
96     get modifiable() this.name !== "system",
97
98     addRef: function (obj) {
99         this.refs.push(util.weakReference(obj));
100         this.dropRef(null);
101     },
102     dropRef: function (obj) {
103         this.refs = this.refs.filter(function (ref) ref.get() && ref.get() !== obj);
104         if (!this.refs.length) {
105             this.cleanup();
106             styles.hives = styles.hives.filter(function (h) h !== this, this);
107         }
108     },
109
110     cleanup: function cleanup() {
111         for (let sheet in values(this.sheets))
112             sheet.enabled = false;
113     },
114
115     __iterator__: function () Iterator(this.sheets),
116
117     get sites() array(this.sheets).map(function (s) s.sites).flatten().uniq().array,
118
119     /**
120      * Add a new style sheet.
121      *
122      * @param {string} name The name given to the style sheet by
123      *     which it may be later referenced.
124      * @param {string} filter The sites to which this sheet will
125      *     apply. Can be a domain name or a URL. Any URL ending in
126      *     "*" is matched as a prefix.
127      * @param {string} css The CSS to be applied.
128      * @param {boolean} agent If true, the sheet is installed as an
129      *     agent sheet.
130      * @param {boolean} lazy If true, the sheet is not initially enabled.
131      * @returns {Sheet}
132      */
133     add: function add(name, filter, css, agent, lazy) {
134
135         if (!isArray(filter))
136             filter = filter.split(",");
137         if (name && name in this.names) {
138             var sheet = this.names[name];
139             sheet.agent = agent;
140             sheet.css = String(css);
141             sheet.sites = filter;
142         }
143         else {
144             sheet = Sheet(name, styles._id++, filter.filter(util.identity), String(css), this, agent);
145             this.sheets.push(sheet);
146         }
147
148         styles.allSheets[sheet.id] = sheet;
149
150         if (!lazy)
151             sheet.enabled = true;
152
153         if (name)
154             this.names[name] = sheet;
155         return sheet;
156     },
157
158     /**
159      * Get a sheet with a given name or index.
160      *
161      * @param {string or number} sheet The sheet to retrieve. Strings indicate
162      *     sheet names, while numbers indicate indices.
163      */
164     get: function get(sheet) {
165         if (typeof sheet === "number")
166             return this.sheets[sheet];
167         return this.names[sheet];
168     },
169
170     /**
171      * Find sheets matching the parameters. See {@link #addSheet}
172      * for parameters.
173      *
174      * @param {string} name
175      * @param {string} filter
176      * @param {string} css
177      * @param {number} index
178      */
179     find: function find(name, filter, css, index) {
180         // Grossly inefficient.
181         let matches = [k for ([k, v] in Iterator(this.sheets))];
182         if (index)
183             matches = String(index).split(",").filter(function (i) i in this.sheets, this);
184         if (name)
185             matches = matches.filter(function (i) this.sheets[i].name == name, this);
186         if (css)
187             matches = matches.filter(function (i) this.sheets[i].css == css, this);
188         if (filter)
189             matches = matches.filter(function (i) this.sheets[i].sites.indexOf(filter) >= 0, this);
190         return matches.map(function (i) this.sheets[i], this);
191     },
192
193     /**
194      * Remove a style sheet. See {@link #addSheet} for parameters.
195      * In cases where *filter* is supplied, the given filters are removed from
196      * matching sheets. If any remain, the sheet is left in place.
197      *
198      * @param {string} name
199      * @param {string} filter
200      * @param {string} css
201      * @param {number} index
202      */
203     remove: function remove(name, filter, css, index) {
204         let self = this;
205         if (arguments.length == 1) {
206             var matches = [name];
207             name = null;
208         }
209
210         if (filter && filter.indexOf(",") > -1)
211             return filter.split(",").reduce(
212                 function (n, f) n + self.removeSheet(name, f, index), 0);
213
214         if (filter == undefined)
215             filter = "";
216
217         if (!matches)
218             matches = this.findSheets(name, filter, css, index);
219         if (matches.length == 0)
220             return null;
221
222         for (let [, sheet] in Iterator(matches.reverse())) {
223             if (filter) {
224                 let sites = sheet.sites.filter(function (f) f != filter);
225                 if (sites.length) {
226                     sheet.sites = sites;
227                     continue;
228                 }
229             }
230             sheet.enabled = false;
231             if (sheet.name)
232                 delete this.names[sheet.name];
233             delete styles.allSheets[sheet.id];
234         }
235         this.sheets = this.sheets.filter(function (s) matches.indexOf(s) == -1);
236         return matches.length;
237     },
238 });
239
240 /**
241  * Manages named and unnamed user style sheets, which apply to both
242  * chrome and content pages.
243  *
244  * @author Kris Maglione <maglione.k@gmail.com>
245  */
246 var Styles = Module("Styles", {
247     Local: function (dactyl, modules, window) ({
248         cleanup: function () {}
249     }),
250
251     init: function () {
252         this._id = 0;
253         this.cleanup();
254         this.allSheets = {};
255
256         update(services["dactyl:"].providers, {
257             "style": function styleProvider(uri, path) {
258                 let id = parseInt(path);
259                 if (Set.has(styles.allSheets, id))
260                     return ["text/css", styles.allSheets[id].fullCSS];
261                 return null;
262             }
263         });
264     },
265
266     cleanup: function cleanup() {
267         for each (let hive in this.hives)
268             util.trapErrors("cleanup", hive);
269         this.hives = [];
270         this.user = this.addHive("user", this, true);
271         this.system = this.addHive("system", this, false);
272     },
273
274     addHive: function addHive(name, ref, persist) {
275         let hive = array.nth(this.hives, function (h) h.name === name, 0);
276         if (!hive) {
277             hive = Hive(name, persist);
278             this.hives.push(hive);
279         }
280         hive.persist = persist;
281         if (ref)
282             hive.addRef(ref);
283         return hive;
284     },
285
286     __iterator__: function () Iterator(this.user.sheets.concat(this.system.sheets)),
287
288     _proxy: function (name, args)
289         let (obj = this[args[0] ? "system" : "user"])
290             obj[name].apply(obj, Array.slice(args, 1)),
291
292     addSheet: deprecated("Styles#{user,system}.add", function addSheet() this._proxy("add", arguments)),
293     findSheets: deprecated("Styles#{user,system}.find", function findSheets() this._proxy("find", arguments)),
294     get: deprecated("Styles#{user,system}.get", function get() this._proxy("get", arguments)),
295     removeSheet: deprecated("Styles#{user,system}.remove", function removeSheet() this._proxy("remove", arguments)),
296
297     userSheets: Class.Property({ get: deprecated("Styles#user.sheets", function userSheets() this.user.sheets) }),
298     systemSheets: Class.Property({ get: deprecated("Styles#system.sheets", function systemSheets() this.system.sheets) }),
299     userNames: Class.Property({ get: deprecated("Styles#user.names", function userNames() this.user.names) }),
300     systemNames: Class.Property({ get: deprecated("Styles#system.names", function systemNames() this.system.names) }),
301     sites: Class.Property({ get: deprecated("Styles#user.sites", function sites() this.user.sites) }),
302
303     list: function list(content, sites, name, hives) {
304         const { commandline, dactyl } = this.modules;
305
306         hives = hives || styles.hives.filter(function (h) h.modifiable && h.sheets.length);
307
308         function sheets(group)
309             group.sheets.slice()
310                  .filter(function (sheet) (!name || sheet.name === name) &&
311                                           (!sites || sites.every(function (s) sheet.sites.indexOf(s) >= 0)))
312                  .sort(function (a, b) a.name && b.name ? String.localeCompare(a.name, b.name)
313                                                         : !!b.name - !!a.name || a.id - b.id);
314
315         let uris = util.visibleURIs(content);
316
317         let list = <table>
318                 <tr highlight="Title">
319                     <td/>
320                     <td/>
321                     <td style="padding-right: 1em;">{_("title.Name")}</td>
322                     <td style="padding-right: 1em;">{_("title.Filter")}</td>
323                     <td style="padding-right: 1em;">{_("title.CSS")}</td>
324                 </tr>
325                 <col style="min-width: 4em; padding-right: 1em;"/>
326                 <col style="min-width: 1em; text-align: center; color: red; font-weight: bold;"/>
327                 <col style="padding: 0 1em 0 1ex; vertical-align: top;"/>
328                 <col style="padding: 0 1em 0 0; vertical-align: top;"/>
329                 {
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 : ""}</td>
335                                 <td>{sheet.enabled ? "" : UTF8("×")}</td>
336                                 <td>{sheet.name || hive.sheets.indexOf(sheet)}</td>
337                                 <td>{sheet.formatSites(uris)}</td>
338                                 <td>{sheet.css}</td>
339                             </tr>) +
340                         <tr style="height: .5ex;"/>)
341                 }
342                 </table>;
343
344         // TODO: Move this to an ItemList to show this automatically
345         if (list.*.length() === list.text().length() + 5)
346             dactyl.echomsg(_("style.none"));
347         else
348             commandline.commandOutput(list);
349     },
350
351     registerSheet: function registerSheet(url, agent, reload) {
352         let uri = services.io.newURI(url, null, null);
353         if (reload)
354             this.unregisterSheet(url, agent);
355
356         let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
357         if (reload || !services.stylesheet.sheetRegistered(uri, type))
358             services.stylesheet.loadAndRegisterSheet(uri, type);
359     },
360
361     unregisterSheet: function unregisterSheet(url, agent) {
362         let uri = services.io.newURI(url, null, null);
363         let type = services.stylesheet[agent ? "AGENT_SHEET" : "USER_SHEET"];
364         if (services.stylesheet.sheetRegistered(uri, type))
365             services.stylesheet.unregisterSheet(uri, type);
366     },
367 }, {
368     append: function (dest, src, sort) {
369         let props = {};
370         for each (let str in [dest, src])
371             for (let prop in Styles.propertyIter(str))
372                 props[prop.name] = prop.value;
373
374         let val = Object.keys(props)[sort ? "sort" : "slice"]()
375                         .map(function (prop) prop + ": " + props[prop] + ";")
376                         .join(" ");
377
378         if (/^\s*(\/\*.*?\*\/)/.exec(src))
379             val = RegExp.$1 + " " + val;
380         return val;
381     },
382
383     completeSite: function (context, content, group) {
384         group = group || styles.user;
385         context.anchored = false;
386         try {
387             context.fork("current", 0, this, function (context) {
388                 context.title = ["Current Site"];
389                 context.completions = [
390                     [content.location.host, /*L*/"Current Host"],
391                     [content.location.href, /*L*/"Current URL"]
392                 ];
393             });
394         }
395         catch (e) {}
396
397         let uris = util.visibleURIs(content);
398
399         context.generate = function () values(group.sites);
400
401         context.keys.text = util.identity;
402         context.keys.description = function (site) this.sheets.length + /*L*/" sheet" + (this.sheets.length == 1 ? "" : "s") + ": " +
403             array.compact(this.sheets.map(function (s) s.name)).join(", ");
404         context.keys.sheets = function (site) group.sheets.filter(function (s) s.sites.indexOf(site) >= 0);
405         context.keys.active = function (site) uris.some(Styles.matchFilter(site));
406
407         Styles.splitContext(context, "Sites");
408     },
409
410     /**
411      * A curried function which determines which host names match a
412      * given stylesheet filter. When presented with one argument,
413      * returns a matcher function which, given one nsIURI argument,
414      * returns true if that argument matches the given filter. When
415      * given two arguments, returns true if the second argument matches
416      * the given filter.
417      *
418      * @param {string} filter The URI filter to match against.
419      * @param {nsIURI} uri The location to test.
420      * @returns {nsIURI -> boolean}
421      */
422     matchFilter: function (filter) {
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(<![CDATA[
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(<![CDATA[
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(<![CDATA[
507                 (?P<function>
508                     \s* \( \s*
509                         (?: <string> | [^)]*  )
510                     \s* (?: \) | $)
511                 )
512             ]]>, "gx", this),
513
514         space: /(?: \s | \/\* .*? \*\/ )/,
515
516         get string() util.regexp(<![CDATA[
517                 (?P<string>
518                     " (?:[^\\"]|\\.)* (?:"|$) |
519                     ' (?:[^\\']|\\.)* (?:'|$)
520                 )
521             ]]>, "gx", this),
522
523         get token() util.regexp(<![CDATA[
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 (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 (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 (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 (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 () {
741         let patterns = Styles.patterns;
742
743         template.highlightCSS = function highlightCSS(css) {
744             XML.prettyPrinting = XML.ignoreWhitespace = false;
745
746             return this.highlightRegexp(css, patterns.property, function (match) {
747                 if (!match.length)
748                     return <></>;
749                 return <>{match.preSpace}{template.filter(match.name)}: {
750
751                     template.highlightRegexp(match.value, patterns.token, function (match) {
752                         if (match.function)
753                             return <>{template.filter(match.word)}{
754                                 template.highlightRegexp(match.function, patterns.string,
755                                     function (match) <span highlight="String">{match.string}</span>)
756                             }</>;
757                         if (match.important == "!important")
758                             return <span highlight="String">{match.important}</span>;
759                         if (match.string)
760                             return <span highlight="String">{match.string}</span>;
761                         return template.highlightRegexp(match.wholeMatch, /^(\d+)(em|ex|px|in|cm|mm|pt|pc)?/g,
762                                                         function (m, n, u) <><span highlight="Number">{n}</span><span highlight="Object">{u || ""}</span></>);
763                     })
764
765                 }{ match.postSpace }</>
766             })
767         }
768     },
769 });
770
771 endModule();
772
773 // catch(e){dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack);}
774
775 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: