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