]> git.donarmstrong.com Git - dactyl.git/blob - common/modules/completion.jsm
Import r6948 from upstream hg supporting Firefox up to 24.*
[dactyl.git] / common / modules / completion.jsm
1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2012 Kris Maglione <maglione.k@gmail.com>
4 //
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
7 "use strict";
8
9 defineModule("completion", {
10     exports: ["CompletionContext", "Completion", "completion"]
11 }, this);
12
13 lazyRequire("dom", ["DOM"]);
14 lazyRequire("messages", ["_", "messages"]);
15 lazyRequire("template", ["template"]);
16
17 /**
18  * Creates a new completion context.
19  *
20  * @class A class to provide contexts for command completion.
21  * Manages the filtering and formatting of completions, and keeps
22  * track of the positions and quoting of replacement text. Allows for
23  * the creation of sub-contexts with different headers and quoting
24  * rules.
25  *
26  * @param {nsIEditor} editor The editor for which completion is
27  *     intended. May be a {CompletionContext} when forking a context,
28  *     or a {string} when creating a new one.
29  * @param {string} name The name of this context. Used when the
30  *     context is forked.
31  * @param {number} offset The offset from the parent context.
32  * @author Kris Maglione <maglione.k@gmail.com>
33  * @constructor
34  */
35 var CompletionContext = Class("CompletionContext", {
36     init: function cc_init(editor, name, offset) {
37         if (!name)
38             name = "";
39
40         let self = this;
41         if (editor instanceof this.constructor) {
42             let parent = editor;
43             name = parent.name + "/" + name;
44
45             if (this.options) {
46                 this.autoComplete = this.options.get("autocomplete").getKey(name);
47                 this.sortResults  = this.options.get("wildsort").getKey(name);
48                 this.wildcase     = this.options.get("wildcase").getKey(name);
49             }
50
51             this.contexts = parent.contexts;
52             if (name in this.contexts)
53                 self = this.contexts[name];
54             else
55                 self.contexts[name] = this;
56
57             /**
58              * @property {CompletionContext} This context's parent. {null} when
59              *     this is a top-level context.
60              */
61             self.parent = parent;
62
63             ["filters", "keys", "process", "title", "quote"].forEach(function fe(key)
64                 self[key] = parent[key] && util.cloneObject(parent[key]));
65             ["anchored", "compare", "editor", "_filter", "filterFunc", "forceAnchored", "top"].forEach(function (key)
66                 self[key] = parent[key]);
67
68             self.__defineGetter__("value", function get_value() this.top.value);
69
70             self.offset = parent.offset;
71             self.advance(offset || 0);
72
73             /**
74              * @property {boolean} Specifies that this context is not finished
75              *     generating results.
76              * @default false
77              */
78             self.incomplete = false;
79             self.message = null;
80             /**
81              * @property {boolean} Specifies that this context is waiting for the
82              *     user to press <Tab>. Useful when fetching completions could be
83              *     dangerous or slow, and the user has enabled autocomplete.
84              */
85             self.waitingForTab = false;
86
87             self.hasItems = null;
88
89             delete self._generate;
90             delete self.ignoreCase;
91             if (self != this)
92                 return self;
93             ["_caret", "contextList", "maxItems", "onUpdate", "selectionTypes", "tabPressed", "updateAsync", "value"].forEach(function fe(key) {
94                 self.__defineGetter__(key, function () this.top[key]);
95                 self.__defineSetter__(key, function (val) this.top[key] = val);
96             });
97         }
98         else {
99             if (typeof editor == "string")
100                 this._value = editor;
101             else
102                 this.editor = editor;
103             /**
104              * @property {boolean} Specifies whether this context results must
105              *     match the filter at the beginning of the string.
106              * @default true
107              */
108             this.anchored = true;
109             this.forceAnchored = null;
110
111             this.compare = function compare(a, b) String.localeCompare(a.text, b.text);
112             /**
113              * @property {function} This function is called when we close
114              *     a completion window with Esc or Ctrl-c. Usually this callback
115              *     is only needed for long, asynchronous completions
116              */
117             this.cancel = null;
118             /**
119              * @property {[CompletionContext]} A list of active
120              *     completion contexts, in the order in which they were
121              *     instantiated.
122              */
123             this.contextList = [];
124             /**
125              * @property {Object} A map of all contexts, keyed on their names.
126              *    Names are assigned when a context is forked, with its specified
127              *    name appended, after a '/', to its parent's name. May
128              *    contain inactive contexts. For active contexts, see
129              *    {@link #contextList}.
130              */
131             this.contexts = { "": this };
132             /**
133              * @property {function} The function used to filter the results.
134              * @default Selects all results which match every predicate in the
135              *     {@link #filters} array.
136              */
137             this.filterFunc = function filterFunc(items) {
138                 return this.filters
139                            .reduce((res, filter)
140                                         => res.filter((item) => filter.call(this, item)),
141                                    items);
142             };
143             /**
144              * @property {Array} An array of predicates on which to filter the
145              *     results.
146              */
147             this.filters = [CompletionContext.Filter.text];
148             /**
149              * @property {Object} A mapping of keys, for {@link #getKey}. Given
150              *      { key: value }, getKey(item, key) will return values as such:
151              *      if value is a string, it will return item.item[value]. If it's a
152              *      function, it will return value(item.item).
153              */
154             this.keys = { text: 0, description: 1, icon: "icon" };
155             /**
156              * @property {number} This context's offset from the beginning of
157              *     {@link #editor}'s value.
158              */
159             this.offset = offset || 0;
160             /**
161              * @property {function} A function which is called when any subcontext
162              *     changes its completion list. Only called when
163              *     {@link #updateAsync} is true.
164              */
165             this.onUpdate = function onUpdate() true;
166
167             this.runCount = 0;
168
169             /**
170              * @property {CompletionContext} The top-level completion context.
171              */
172             this.top = this;
173             this.__defineGetter__("incomplete", function get_incomplete() this._incomplete
174                 || this.contextList.some(function (c) c.parent && c.incomplete));
175             this.__defineGetter__("waitingForTab", function get_waitingForTab() this._waitingForTab
176                 || this.contextList.some(function (c) c.parent && c.waitingForTab));
177             this.__defineSetter__("incomplete", function get_incomplete(val) { this._incomplete = val; });
178             this.__defineSetter__("waitingForTab", function get_waitingForTab(val) { this._waitingForTab = val; });
179             this.reset();
180         }
181         /**
182          * @property {Object} A general-purpose store for functions which need to
183          *     cache data between calls.
184          */
185         this.cache = {};
186         this._cache = {};
187         /**
188          * @private
189          * @property {Object} A cache for return values of {@link #generate}.
190          */
191         this.itemCache = {};
192         /**
193          * @property {string} A key detailing when the cached value of
194          *     {@link #generate} may be used. Every call to
195          *     {@link #generate} stores its result in {@link #itemCache}.
196          *     When itemCache[key] exists, its value is returned, and
197          *     {@link #generate} is not called again.
198          */
199         this.key = "";
200         /**
201          * @property {string} A message to be shown before any results.
202          */
203         this.message = null;
204         this.name = name || "";
205         /** @private */
206         this._completions = []; // FIXME
207         /**
208          * Returns a key, as detailed in {@link #keys}.
209          * @function
210          */
211         this.getKey = function getKey(item, key) (typeof self.keys[key] == "function") ? self.keys[key].call(this, item.item) :
212                 key in self.keys ? item.item[self.keys[key]]
213                                  : item.item[key];
214         return this;
215     },
216
217     __title: Class.Memoize(function __title() this._title.map(function (s)
218                 typeof s == "string" ? messages.get("completion.title." + s, s)
219                                      : s)),
220
221     set title(val) {
222         delete this.__title;
223         return this._title = val;
224     },
225     get title() this.__title,
226
227     get activeContexts() this.contextList.filter(function f(c) c.items.length),
228
229     // Temporary
230     /**
231      * @property {Object}
232      *
233      * An object describing the results from all sub-contexts. Results are
234      * adjusted so that all have the same starting offset.
235      *
236      * @deprecated
237      */
238     get allItems() {
239         let self = this;
240
241         try {
242             let allItems = this.contextList.map(function m(context) context.hasItems && context.items.length);
243             if (this.cache.allItems && array.equals(this.cache.allItems, allItems))
244                 return this.cache.allItemsResult;
245             this.cache.allItems = allItems;
246
247             let minStart = Math.min.apply(Math, this.activeContexts.map(function m(c) c.offset));
248             if (minStart == Infinity)
249                 minStart = 0;
250
251             this.cache.allItemsResult = memoize({
252                 start: minStart,
253
254                 get longestSubstring() self.longestAllSubstring,
255
256                 get items() array.flatten(self.activeContexts.map(function m(context) {
257                     let prefix = self.value.substring(minStart, context.offset);
258
259                     return context.items.map(function m(item) ({
260                         text: prefix + item.text,
261                         result: prefix + item.result,
262                         __proto__: item
263                     }));
264                 }))
265             });
266
267             return this.cache.allItemsResult;
268         }
269         catch (e) {
270             util.reportError(e);
271             return { start: 0, items: [], longestAllSubstring: "" };
272         }
273     },
274     // Temporary
275     get allSubstrings() {
276         let contexts = this.activeContexts;
277         let minStart = Math.min.apply(Math, contexts.map(function m(c) c.offset));
278         let lists = contexts.map(function m(context) {
279             let prefix = context.value.substring(minStart, context.offset);
280             return context.substrings.map(function m(s) prefix + s);
281         });
282
283         /* TODO: Deal with sub-substrings for multiple contexts again.
284          * Possibly.
285          */
286         let substrings = lists.reduce(
287                 function r(res, list) res.filter(function f(str) list.some(function s_(s) s.substr(0, str.length) == str)),
288                 lists.pop());
289         if (!substrings) // FIXME: How is this undefined?
290             return [];
291         return array.uniq(Array.slice(substrings));
292     },
293     // Temporary
294     get longestAllSubstring() {
295         return this.allSubstrings.reduce(function r(a, b) a.length > b.length ? a : b, "");
296     },
297
298     get caret() this._caret - this.offset,
299     set caret(val) this._caret = val + this.offset,
300
301     get compare() this._compare || function compare() 0,
302     set compare(val) this._compare = val,
303
304     get completions() this._completions || [],
305     set completions(items) {
306         if (items && isArray(items.array))
307             items = items.array;
308         // Accept a generator
309         if (!isArray(items))
310             items = [x for (x in Iterator(items || []))];
311         if (this._completions !== items) {
312             delete this.cache.filtered;
313             delete this.cache.filter;
314             this.cache.rows = [];
315             this._completions = items;
316             this.itemCache[this.key] = items;
317         }
318
319         if (this._completions)
320             this.hasItems = this._completions.length > 0;
321
322         if (this.updateAsync && !this.noUpdate)
323             util.trapErrors("onUpdate", this);
324     },
325
326     get createRow() this._createRow || template.completionRow, // XXX
327     set createRow(createRow) this._createRow = createRow,
328
329     get filterFunc() this._filterFunc || util.identity,
330     set filterFunc(val) this._filterFunc = val,
331
332     get filter() this._filter != null ? this._filter : this.value.substr(this.offset, this.caret),
333     set filter(val) {
334         delete this.ignoreCase;
335         return this._filter = val;
336     },
337
338     get format() ({
339         anchored: this.anchored,
340         title: this.title,
341         keys: this.keys,
342         process: this.process
343     }),
344     set format(format) {
345         this.anchored = format.anchored,
346         this.title = format.title || this.title;
347         this.keys = format.keys || this.keys;
348         this.process = format.process || this.process;
349     },
350
351     /**
352      * @property {string | xml | null}
353      * The message displayed at the head of the completions for the
354      * current context.
355      */
356     get message() this._message || (this.waitingForTab && this.hasItems !== false ? _("completion.waitingFor", "<Tab>") : null),
357     set message(val) this._message = val,
358
359     /**
360      * The prototype object for items returned by {@link items}.
361      */
362     get itemPrototype() {
363         let self = this;
364         let res = { highlight: "" };
365
366         function result(quote) {
367             yield ["context", function p_context() self];
368             yield ["result", quote ? function p_result() quote[0] + util.trapErrors(1, quote, this.text) + quote[2]
369                                    : function p_result() this.text];
370             yield ["texts", function p_texts() Array.concat(this.text)];
371         };
372
373         for (let i in iter(this.keys, result(this.quote))) {
374             let [k, v] = i;
375             if (typeof v == "string" && /^[.[]/.test(v))
376                 // This is only allowed to be a simple accessor, and shouldn't
377                 // reference any variables. Don't bother with eval context.
378                 v = Function("i", "return i" + v);
379             if (typeof v == "function")
380                 res.__defineGetter__(k, function p_gf() Class.replaceProperty(this, k, v.call(this, this.item, self)));
381             else
382                 res.__defineGetter__(k, function p_gp() Class.replaceProperty(this, k, this.item[v]));
383             res.__defineSetter__(k, function p_s(val) Class.replaceProperty(this, k, val));
384         }
385         return res;
386     },
387
388     /**
389      * Returns true when the completions generated by {@link #generate}
390      * must be regenerated. May be set to true to invalidate the current
391      * completions.
392      */
393     get regenerate() this._generate && (!this.completions || !this.itemCache[this.key] || this._cache.offset != this.offset),
394     set regenerate(val) { if (val) delete this.itemCache[this.key]; },
395
396     /**
397      * A property which may be set to a function to generate the value
398      * of {@link completions} only when necessary. The generated
399      * completions are linked to the value in {@link #key} and may be
400      * invalidated by setting the {@link #regenerate} property.
401      */
402     get generate() this._generate || null,
403     set generate(arg) {
404         this.hasItems = true;
405         this._generate = arg;
406     },
407     /**
408      * Generates the item list in {@link #completions} via the
409      * {@link #generate} method if the previously generated value is no
410      * longer valid.
411      */
412     generateCompletions: function generateCompletions() {
413         if (this.offset != this._cache.offset || this.lastActivated != this.top.runCount) {
414             this.itemCache = {};
415             this._cache.offset = this.offset;
416             this.lastActivated = this.top.runCount;
417         }
418         if (!this.itemCache[this.key] && !this.waitingForTab) {
419             try {
420                 let res = this._generate();
421                 if (res != null)
422                     this.itemCache[this.key] = res;
423             }
424             catch (e) {
425                 util.reportError(e);
426                 this.message = _("error.error", e);
427             }
428         }
429         // XXX
430         this.noUpdate = true;
431         this.completions = this.itemCache[this.key];
432         this.noUpdate = false;
433     },
434
435     ignoreCase: Class.Memoize(function M() {
436         let mode = this.wildcase;
437         if (mode == "match")
438             return false;
439         else if (mode == "ignore")
440             return true;
441         else
442             return !/[A-Z]/.test(this.filter);
443     }),
444
445     /**
446      * Returns a list of all completion items which match the current
447      * filter. The items returned are objects containing one property
448      * for each corresponding property in {@link keys}. The returned
449      * list is generated on-demand from the item list in {@link completions}
450      * or generated by {@link generate}, and is cached as long as no
451      * properties which would invalidate the result are changed.
452      */
453     get items() {
454         // Don't return any items if completions or generator haven't
455         // been set during this completion cycle.
456         if (!this.hasItems)
457             return [];
458
459         // Regenerate completions if we must
460         if (this.generate)
461             this.generateCompletions();
462         let items = this.completions;
463
464         // Check for cache miss
465         if (this._cache.completions !== this.completions) {
466             this._cache.completions = this.completions;
467             this._cache.constructed = null;
468             this.cache.filtered = null;
469         }
470
471         if (this.cache.filtered && this.cache.filter == this.filter)
472             return this.cache.filtered;
473
474         this.cache.rows = [];
475         this.cache.filter = this.filter;
476         if (items == null)
477             return null;
478
479         let self = this;
480         delete this._substrings;
481
482         if (!this.forceAnchored && this.options)
483             this.anchored = this.options.get("wildanchor").getKey(this.name, this.anchored);
484
485         // Item matchers
486         if (this.ignoreCase)
487             this.matchString = this.anchored ?
488                 function matchString(filter, str) String.toLowerCase(str).indexOf(filter.toLowerCase()) == 0 :
489                 function matchString(filter, str) String.toLowerCase(str).indexOf(filter.toLowerCase()) >= 0;
490         else
491             this.matchString = this.anchored ?
492                 function matchString(filter, str) String.indexOf(str, filter) == 0 :
493                 function matchString(filter, str) String.indexOf(str, filter) >= 0;
494
495         // Item formatters
496         this.processor = Array.slice(this.process);
497         if (!this.anchored)
498             this.processor[0] = function processor_0(item, text) self.process[0].call(self, item,
499                     template.highlightFilter(item.text, self.filter, null, item.isURI));
500
501         try {
502             // Item prototypes
503             if (!this._cache.constructed) {
504                 let proto = this.itemPrototype;
505                 this._cache.constructed = items.map(function m(item) ({ __proto__: proto, item: item }));
506             }
507
508             // Filters
509             let filtered = this.filterFunc(this._cache.constructed);
510             if (this.maxItems)
511                 filtered = filtered.slice(0, this.maxItems);
512
513             // Sorting
514             if (this.sortResults && this.compare) {
515                 filtered.sort(this.compare);
516                 if (!this.anchored) {
517                     let filter = this.filter;
518                     filtered.sort(function s(a, b) (b.text.indexOf(filter) == 0) - (a.text.indexOf(filter) == 0));
519                 }
520             }
521
522             return this.cache.filtered = filtered;
523         }
524         catch (e) {
525             this.message = _("error.error", e);
526             util.reportError(e);
527             return [];
528         }
529     },
530
531     /**
532      * Returns a list of all substrings common to all items which
533      * include the current filter.
534      */
535     get substrings() {
536         let items = this.items;
537         if (items.length == 0 || !this.hasItems)
538             return [];
539         if (this._substrings)
540             return this._substrings;
541
542         let fixCase = this.ignoreCase ? String.toLowerCase : util.identity;
543         let text   = fixCase(items[0].text);
544         let filter = fixCase(this.filter);
545
546         // Exceedingly long substrings cause Gecko to go into convulsions
547         if (text.length > 100)
548             text = text.substr(0, 100);
549
550         if (this.anchored) {
551             var compare = function compare(text, s) text.substr(0, s.length) == s;
552             var substrings = [text];
553         }
554         else {
555             var compare = function compare(text, s) text.indexOf(s) >= 0;
556             var substrings = [];
557             let start = 0;
558             let idx;
559             let length = filter.length;
560             while ((idx = text.indexOf(filter, start)) > -1 && idx < text.length) {
561                 substrings.push(text.substring(idx));
562                 start = idx + 1;
563             }
564         }
565
566         substrings = items.reduce(function r(res, item)
567             res.map(function m(substring) {
568                 // A simple binary search to find the longest substring
569                 // of the given string which also matches the current
570                 // item's text.
571                 let len = substring.length;
572                 let i = 0, n = len + 1;
573                 let result = n && fixCase(item.result);
574                 while (n) {
575                     let m = Math.floor(n / 2);
576                     let keep = compare(result, substring.substring(0, i + m));
577                     if (!keep)
578                         len = i + m - 1;
579                     if (!keep || m == 0)
580                         n = m;
581                     else {
582                         i += m;
583                         n = n - m;
584                     }
585                 }
586                 return len == substring.length ? substring : substring.substr(0, Math.max(len, 0));
587             }),
588             substrings);
589
590         let quote = this.quote;
591         if (quote)
592             substrings = substrings.map(function m(str) quote[0] + quote[1](str));
593         return this._substrings = substrings;
594     },
595
596     /**
597      * Advances the context *count* characters. {@link #filter} is advanced to
598      * match. If {@link #quote} is non-null, its prefix and suffix are set to
599      * the null-string.
600      *
601      * This function is still imperfect for quoted strings. When
602      * {@link #quote} is non-null, it adjusts the count based on the quoted
603      * size of the *count*-character substring of the filter, which is accurate
604      * so long as unquoting and quoting a string will always map to the
605      * original quoted string, which is often not the case.
606      *
607      * @param {number} count The number of characters to advance the context.
608      */
609     advance: function advance(count) {
610         delete this.ignoreCase;
611         let advance = count;
612         if (this.quote && count) {
613             advance = this.quote[1](this.filter.substr(0, count)).length;
614             count = this.quote[0].length + advance;
615             this.quote[0] = "";
616             this.quote[2] = "";
617         }
618         this.offset += count;
619         if (this._filter)
620             this._filter = this._filter.substr(arguments[0] || 0);
621     },
622
623     /**
624      * Calls the {@link #cancel} method of all currently active
625      * sub-contexts.
626      */
627     cancelAll: function cancelAll() {
628         for (let [, context] in Iterator(this.contextList)) {
629             if (context.cancel)
630                 context.cancel();
631         }
632     },
633
634     /**
635      * Gets a key from {@link #cache}, setting it to *defVal* if it doesn't
636      * already exists.
637      *
638      * @param {string} key
639      * @param defVal
640      */
641     getCache: function getCache(key, defVal) {
642         if (!(key in this.cache))
643             this.cache[key] = defVal();
644         return this.cache[key];
645     },
646
647     getItems: function getItems(start, end) {
648         let items = this.items;
649         let step = start > end ? -1 : 1;
650         start = Math.max(0, start || 0);
651         end = Math.min(items.length, end ? end : items.length);
652         return iter.map(util.range(start, end, step), function m(i) items[i]);
653     },
654
655     getRow: function getRow(idx, doc) {
656         let cache = this.cache.rows;
657         if (cache) {
658             if (idx in this.items && !(idx in this.cache.rows))
659                 try {
660                     cache[idx] = DOM.fromJSON(this.createRow(this.items[idx]),
661                                               doc || this.doc);
662                 }
663                 catch (e) {
664                     util.reportError(e);
665                     util.dump(util.prettifyJSON(this.createRow(this.items[idx]), null, true));
666                     cache[idx] = DOM.fromJSON(
667                         ["div", { highlight: "CompItem", style: "white-space: nowrap" },
668                             ["li", { highlight: "CompResult" }, this.text + "\u00a0"],
669                             ["li", { highlight: "CompDesc ErrorMsg" }, e + "\u00a0"]],
670                         doc || this.doc);
671                 }
672             return cache[idx];
673         }
674     },
675
676     getRows: function getRows(start, end, doc) {
677         let items = this.items;
678         let cache = this.cache.rows;
679         let step = start > end ? -1 : 1;
680
681         start = Math.max(0, start || 0);
682         end = Math.min(items.length, end != null ? end : items.length);
683
684         this.doc = doc;
685         for (let i in util.range(start, end, step))
686             yield [i, this.getRow(i)];
687     },
688
689     /**
690      * Forks this completion context to create a new sub-context named
691      * as {this.name}/{name}. The new context is automatically advanced
692      * *offset* characters. If *completer* is provided, it is called
693      * with *self* as its 'this' object, the new context as its first
694      * argument, and any subsequent arguments after *completer* as its
695      * following arguments.
696      *
697      * If *completer* is provided, this function returns its return
698      * value, otherwise it returns the new completion context.
699      *
700      * @param {string} name The name of the new context.
701      * @param {number} offset The offset of the new context relative to
702      *      the current context's offset.
703      * @param {object} self *completer*'s 'this' object. @optional
704      * @param {function|string} completer A completer function to call
705      *      for the new context. If a string is provided, it is
706      *      interpreted as a method to access on *self*.
707      */
708     fork: function fork(name, offset, self, completer, ...args) {
709         return this.forkapply(name, offset, self, completer, args);
710     },
711
712     forkapply: function forkapply(name, offset, self, completer, args) {
713         if (isString(completer))
714             completer = self[completer];
715         let context = this.constructor(this, name, offset);
716         if (this.contextList.indexOf(context) < 0)
717             this.contextList.push(context);
718
719         if (!context.autoComplete && !context.tabPressed && context.editor)
720             context.waitingForTab = true;
721         else if (completer) {
722             let res = completer.apply(self || this, [context].concat(args));
723             if (res && !isArray(res) && !isArray(res.__proto__))
724                 res = [k for (k in res)];
725             if (res)
726                 context.completions = res;
727             return res;
728         }
729         if (completer)
730             return null;
731         return context;
732     },
733
734     split: function split(name, obj, fn, ...args) {
735         let context = this.fork(name);
736         let alias = (prop) => {
737             context.__defineGetter__(prop, () => this[prop]);
738             context.__defineSetter__(prop, (val) => this[prop] = val);
739         }
740         alias("_cache");
741         alias("_completions");
742         alias("_generate");
743         alias("_regenerate");
744         alias("itemCache");
745         alias("lastActivated");
746         context.hasItems = true;
747         this.hasItems = false;
748         if (fn)
749             return fn.apply(obj || this, [context].concat(args));
750         return context;
751     },
752
753     /**
754      * Highlights text in the nsIEditor associated with this completion
755      * context. *length* characters are highlighted from the position
756      * *start*, relative to the current context's offset, with the
757      * selection type *type* as defined in nsISelectionController.
758      *
759      * When called with no arguments, all highlights are removed. When
760      * called with a 0 length, all highlights of type *type* are
761      * removed.
762      *
763      * @param {number} start The position at which to start
764      *      highlighting.
765      * @param {number} length The length of the substring to highlight.
766      * @param {string} type The selection type to highlight with.
767      */
768     highlight: function highlight(start, length, type) {
769         if (arguments.length == 0) {
770             for (let type in this.selectionTypes)
771                 this.highlight(0, 0, type);
772             this.selectionTypes = {};
773         }
774         try {
775             // Requires Gecko >= 1.9.1
776             this.selectionTypes[type] = true;
777             const selType = Ci.nsISelectionController["SELECTION_" + type];
778             let sel = this.editor.selectionController.getSelection(selType);
779             if (length == 0)
780                 sel.removeAllRanges();
781             else {
782                 let range = this.editor.selection.getRangeAt(0).cloneRange();
783                 range.setStart(range.startContainer, this.offset + start);
784                 range.setEnd(range.startContainer, this.offset + start + length);
785                 sel.addRange(range);
786             }
787         }
788         catch (e) {}
789     },
790
791     /**
792      * Tests the given string for a match against the current filter,
793      * taking into account anchoring and case sensitivity rules.
794      *
795      * @param {string} str The string to match.
796      * @returns {boolean} True if the string matches, false otherwise.
797      */
798     match: function match(str) this.matchString(this.filter, str),
799
800     /**
801      * Pushes a new output processor onto the processor chain of
802      * {@link #process}. The provided function is called with the item
803      * and text to process along with a reference to the processor
804      * previously installed in the given *index* of {@link #process}.
805      *
806      * @param {number} index The index into {@link #process}.
807      * @param {function(object, string, function)} func The new
808      *      processor.
809      */
810     pushProcessor: function pushProcess(index, func) {
811         let next = this.process[index];
812         this.process[index] = function process_(item, text) func(item, text, next);
813     },
814
815     /**
816      * Resets this completion context and all sub-contexts for use in a
817      * new completion cycle. May only be called on the top-level
818      * context.
819      */
820     reset: function reset() {
821         if (this.parent)
822             throw Error();
823
824         this.offset = 0;
825         this.process = [template.icon, function process_1(item, k) k];
826         this.filters = [CompletionContext.Filter.text];
827         this.tabPressed = false;
828         this.title = ["Completions"];
829         this.updateAsync = false;
830
831         this.cancelAll();
832
833         if (this.editor) {
834             this.value = this.editor.selection.focusNode.textContent;
835             this._caret = this.editor.selection.focusOffset;
836         }
837         else {
838             this.value = this._value;
839             this._caret = this.value.length;
840         }
841         //for (let key in (k for ([k, v] in Iterator(this.contexts)) if (v.offset > this.caret)))
842         //    delete this.contexts[key];
843         for each (let context in this.contexts) {
844             context.hasItems = false;
845             context.incomplete = false;
846         }
847         this.waitingForTab = false;
848         this.runCount++;
849         for each (let context in this.contextList)
850             context.lastActivated = this.runCount;
851         this.contextList = [];
852     },
853
854     /**
855      * Wait for all subcontexts to complete.
856      *
857      * @param {number} timeout The maximum time, in milliseconds, to wait.
858      *    If 0 or null, wait indefinitely.
859      * @param {boolean} interruptible When true, the call may be interrupted
860      *    via <C-c>, in which case, "Interrupted" may be thrown.
861      */
862     wait: function wait(timeout, interruptable) {
863         this.allItems;
864         return util.waitFor(function wf() !this.incomplete, this, timeout, interruptable);
865     }
866 }, {
867     Sort: {
868         number: function S_number(a, b) parseInt(a.text) - parseInt(b.text)
869                     || String.localeCompare(a.text, b.text),
870         unsorted: null
871     },
872
873     Filter: {
874         text: function F_text(item) {
875             let text = item.texts;
876             for (let [i, str] in Iterator(text)) {
877                 if (this.match(String(str))) {
878                     item.text = String(text[i]);
879                     return true;
880                 }
881             }
882             return false;
883         },
884         textDescription: function F_textDescription(item) {
885             return CompletionContext.Filter.text.call(this, item) || this.match(item.description);
886         }
887     }
888 });
889
890 /**
891  * @instance completion
892  */
893 var Completion = Module("completion", {
894     init: function init() {
895     },
896
897     get setFunctionCompleter() JavaScript.setCompleter, // Backward compatibility
898
899     Local: function Local(dactyl, modules, window) ({
900         urlCompleters: {},
901
902         get modules() modules,
903         get options() modules.options,
904
905         // FIXME
906         _runCompleter: function _runCompleter(name, filter, maxItems, ...args) {
907             let context = modules.CompletionContext(filter);
908             context.maxItems = maxItems;
909             let res = context.fork.apply(context, ["run", 0, this, name].concat(args));
910             if (res) {
911                 if (Components.stack.caller.name === "runCompleter") // FIXME
912                     return { items: res.map(function m(i) ({ item: i })) };
913                 context.contexts["/run"].completions = res;
914             }
915             context.wait(null, true);
916             return context.allItems;
917         },
918
919         runCompleter: function runCompleter(name, filter, maxItems) {
920             return this._runCompleter.apply(this, arguments)
921                        .items.map(function m(i) i.item);
922         },
923
924         listCompleter: function listCompleter(name, filter, maxItems, ...args) {
925             let context = modules.CompletionContext(filter || "");
926             context.maxItems = maxItems;
927             context.fork.apply(context, ["list", 0, this, name].concat(args));
928             context = context.contexts["/list"];
929             context.wait(null, true);
930
931             let contexts = context.activeContexts;
932             if (!contexts.length)
933                 contexts = context.contextList.filter(function f(c) c.hasItems).slice(0, 1);
934             if (!contexts.length)
935                 contexts = context.contextList.slice(-1);
936
937             modules.commandline.commandOutput(
938                 ["div", { highlight: "Completions" },
939                     template.map(contexts, function m(context)
940                         [template.completionRow(context.title, "CompTitle"),
941                          template.map(context.items, function m(item) context.createRow(item), null, 100)])]);
942         }
943     }),
944
945     ////////////////////////////////////////////////////////////////////////////////
946     ////////////////////// COMPLETION TYPES ////////////////////////////////////////
947     /////////////////////////////////////////////////////////////////////////////{{{
948
949     // filter a list of urls
950     //
951     // may consist of search engines, filenames, bookmarks and history,
952     // depending on the 'complete' option
953     // if the 'complete' argument is passed like "h", it temporarily overrides the complete option
954     url: function url(context, complete) {
955         if (/^jar:[^!]*$/.test(context.filter)) {
956             context.advance(4);
957
958             context.quote = context.quote || ["", util.identity, ""];
959             let quote = context.quote[1];
960             context.quote[1] = function quote_1(str) quote(str.replace(/!/g, escape));
961         }
962
963         if (this.options["urlseparator"])
964             var skip = util.regexp("^.*" + this.options["urlseparator"] + "\\s*")
965                            .exec(context.filter);
966
967         if (skip)
968             context.advance(skip[0].length);
969
970         if (/^about:/.test(context.filter))
971             context.fork("about", 6, this, function fork_(context) {
972                 context.title = ["about:"];
973                 context.generate = function generate_() {
974                     return [[k.substr(services.ABOUT.length), ""]
975                             for (k in Cc)
976                             if (k.indexOf(services.ABOUT) == 0)];
977                 };
978             });
979
980         if (complete == null)
981             complete = this.options["complete"];
982
983         // Will, and should, throw an error if !(c in opts)
984         Array.forEach(complete, function fe(c) {
985             let completer = this.urlCompleters[c] || { args: [], completer: this.autocomplete(c.replace(/^native:/, "")) };
986             context.forkapply(c, 0, this, completer.completer, completer.args);
987         }, this);
988     },
989
990     addUrlCompleter: function addUrlCompleter(name, description, completer, ...args) {
991         let completer = Completion.UrlCompleter(name, description, completer);
992         completer.args = args;
993         this.urlCompleters[name] = completer;
994     },
995
996     autocomplete: curry(function autocomplete(provider, context) {
997         let running = context.getCache("autocomplete-search-running", Object);
998
999         let name = "autocomplete:" + provider;
1000         if (!services.has(name))
1001             services.add(name, services.AUTOCOMPLETE + provider, "nsIAutoCompleteSearch");
1002         let service = services[name];
1003
1004         util.assert(service, _("autocomplete.noSuchProvider", provider), false);
1005
1006         if (running[provider]) {
1007             this.completions = this.completions;
1008             this.cancel();
1009         }
1010
1011         context.anchored = false;
1012         context.compare = CompletionContext.Sort.unsorted;
1013         context.filterFunc = null;
1014
1015         let words = context.filter.toLowerCase().split(/\s+/g);
1016         context.hasItems = true;
1017         context.completions = context.completions.filter(function f({ url, title })
1018             words.every(function e(w) (url + " " + title).toLowerCase().indexOf(w) >= 0));
1019
1020         context.format = this.modules.bookmarks.format;
1021         context.keys.extra = function k_extra(item) {
1022             try {
1023                 return bookmarkcache.get(item.url).extra;
1024             }
1025             catch (e) {}
1026             return null;
1027         };
1028         context.title = [_("autocomplete.title", provider)];
1029
1030         context.cancel = function cancel_() {
1031             this.incomplete = false;
1032             if (running[provider])
1033                 service.stopSearch();
1034             running[provider] = false;
1035         };
1036
1037         if (!context.waitingForTab) {
1038             context.incomplete = true;
1039
1040             service.startSearch(context.filter, "", context.result, {
1041                 onSearchResult: util.wrapCallback(function onSearchResult(search, result) {
1042                     if (result.searchResult <= result.RESULT_SUCCESS)
1043                         running[provider] = null;
1044
1045                     context.incomplete = result.searchResult >= result.RESULT_NOMATCH_ONGOING;
1046                     context.completions = [
1047                         { url: result.getValueAt(i), title: result.getCommentAt(i), icon: result.getImageAt(i) }
1048                         for (i in util.range(0, result.matchCount))
1049                     ];
1050                 }),
1051                 get onUpdateSearchResult() this.onSearchResult
1052             });
1053             running[provider] = true;
1054         }
1055     }),
1056
1057     urls: function urls(context, tags) {
1058         let compare = String.localeCompare;
1059         let contains = String.indexOf;
1060         if (context.ignoreCase) {
1061             compare = util.compareIgnoreCase;
1062             contains = function contains_(a, b) a && a.toLowerCase().indexOf(b.toLowerCase()) > -1;
1063         }
1064
1065         if (tags)
1066             context.filters.push(function filter_(item) tags.
1067                 every(function e(tag) (item.tags || []).
1068                     some(function s(t) !compare(tag, t))));
1069
1070         context.anchored = false;
1071         if (!context.title)
1072             context.title = ["URL", "Title"];
1073
1074         context.fork("additional", 0, this, function fork_(context) {
1075             context.title[0] += " " + _("completion.additional");
1076             context.filter = context.parent.filter; // FIXME
1077             context.completions = context.parent.completions;
1078
1079             // For items whose URL doesn't exactly match the filter,
1080             // accept them if all tokens match either the URL or the title.
1081             // Filter out all directly matching strings.
1082             let match = context.filters[0];
1083             context.filters[0] = function filters_0(item) !match.call(this, item);
1084
1085             // and all that don't match the tokens.
1086             let tokens = context.filter.split(/\s+/);
1087             context.filters.push(function filter_(item) tokens.every(
1088                     function e(tok) contains(item.url, tok) ||
1089                                    contains(item.title, tok)));
1090
1091             let re = RegExp(tokens.filter(util.identity).map(util.regexp.escape).join("|"), "g");
1092             function highlight(item, text, i) process[i].call(this, item, template.highlightRegexp(text, re));
1093             let process = context.process;
1094             context.process = [
1095                 function process_0(item, text) highlight.call(this, item, item.text, 0),
1096                 function process_1(item, text) highlight.call(this, item, text, 1)
1097             ];
1098         });
1099     }
1100     //}}}
1101 }, {
1102     UrlCompleter: Struct("name", "description", "completer")
1103 }, {
1104     init: function init(dactyl, modules, window) {
1105         init.superapply(this, arguments);
1106
1107         modules.CompletionContext = Class("CompletionContext", CompletionContext, {
1108             init: function init() {
1109                 this.modules = modules;
1110                 return init.superapply(this, arguments);
1111             },
1112
1113             get options() this.modules.options
1114         });
1115     },
1116     commands: function initCommands(dactyl, modules, window) {
1117         const { commands, completion } = modules;
1118         commands.add(["contexts"],
1119             "List the completion contexts used during completion of an Ex command",
1120             function (args) {
1121                 modules.commandline.commandOutput(
1122                     ["div", { highlight: "Completions" },
1123                         template.completionRow(["Context", "Title"], "CompTitle"),
1124                         template.map(completion.contextList || [],
1125                                      function m(item) template.completionRow(item, "CompItem"))]);
1126             },
1127             {
1128                 argCount: "*",
1129                 completer: function (context) {
1130                     let PREFIX = "/ex/contexts";
1131                     context.fork("ex", 0, completion, "ex");
1132                     completion.contextList = [[k.substr(PREFIX.length), v.title[0]] for ([k, v] in iter(context.contexts)) if (k.substr(0, PREFIX.length) == PREFIX)];
1133                 },
1134                 literal: 0
1135             });
1136     },
1137     options: function initOptions(dactyl, modules, window) {
1138         const { completion, options } = modules;
1139         let wildmode = {
1140             values: {
1141                 // Why do we need ""?
1142                 // Because its description is useful during completion. --Kris
1143                 "":              "Complete only the first match",
1144                 "full":          "Complete the next full match",
1145                 "longest":       "Complete the longest common string",
1146                 "list":          "If more than one match, list all matches",
1147                 "list:full":     "List all and complete first match",
1148                 "list:longest":  "List all and complete the longest common string"
1149             },
1150             checkHas: function (value, val) {
1151                 let [first, second] = value.split(":", 2);
1152                 return first == val || second == val;
1153             },
1154             has: function () {
1155                 let test = function test(val) this.value.some(function s(value) this.checkHas(value, val), this);
1156                 return Array.some(arguments, test, this);
1157             }
1158         };
1159
1160         options.add(["altwildmode", "awim"],
1161             "Define the behavior of the c_<A-Tab> key in command-line completion",
1162             "stringlist", "list:full",
1163             wildmode);
1164
1165         options.add(["autocomplete", "au"],
1166             "Automatically update the completion list on any key press",
1167             "regexplist", ".*");
1168
1169         options.add(["complete", "cpt"],
1170             "Items which are completed at the :open prompts",
1171             "stringlist", "slf",
1172             {
1173                 valueMap: {
1174                     S: "suggestion",
1175                     b: "bookmark",
1176                     f: "file",
1177                     h: "history",
1178                     l: "location",
1179                     s: "search"
1180                 },
1181
1182                 get values() values(completion.urlCompleters).toArray()
1183                                 .concat([let (name = k.substr(services.AUTOCOMPLETE.length))
1184                                             ["native:" + name, _("autocomplete.description", name)]
1185                                          for (k in Cc)
1186                                          if (k.indexOf(services.AUTOCOMPLETE) == 0)]),
1187
1188                 setter: function setter(values) {
1189                     if (values.length == 1 && !Set.has(values[0], this.values)
1190                             && Array.every(values[0], Set.has(this.valueMap)))
1191                         return Array.map(values[0], function m(v) this[v], this.valueMap);
1192                     return values;
1193                 },
1194
1195                 validator: function validator(values) validator.supercall(this, this.setter(values))
1196             });
1197
1198         options.add(["wildanchor", "wia"],
1199             "Define which completion groups only match at the beginning of their text",
1200             "regexplist", "!/ex/(back|buffer|ext|forward|help|undo)");
1201
1202         options.add(["wildcase", "wic"],
1203             "Completion case matching mode",
1204             "regexpmap", ".?:smart",
1205             {
1206                 values: {
1207                     "smart": "Case is significant when capital letters are typed",
1208                     "match": "Case is always significant",
1209                     "ignore": "Case is never significant"
1210                 }
1211             });
1212
1213         options.add(["wildmode", "wim"],
1214             "Define the behavior of the c_<Tab> key in command-line completion",
1215             "stringlist", "list:full",
1216             wildmode);
1217
1218         options.add(["wildsort", "wis"],
1219             "Define which completion groups are sorted",
1220             "regexplist", ".*");
1221     }
1222 });
1223
1224 endModule();
1225
1226 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1227
1228 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: