1 // Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
2 // Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
3 // Copyright (c) 2008-2011 by Kris Maglione <maglione.k@gmail.com>
5 // This work is licensed for reuse under an MIT license. Details are
6 // given in the LICENSE.txt file included with this file.
9 Components.utils.import("resource://dactyl/bootstrap.jsm");
10 defineModule("completion", {
11 exports: ["CompletionContext", "Completion", "completion"]
15 * Creates a new completion context.
17 * @class A class to provide contexts for command completion.
18 * Manages the filtering and formatting of completions, and keeps
19 * track of the positions and quoting of replacement text. Allows for
20 * the creation of sub-contexts with different headers and quoting
23 * @param {nsIEditor} editor The editor for which completion is
24 * intended. May be a {CompletionContext} when forking a context,
25 * or a {string} when creating a new one.
26 * @param {string} name The name of this context. Used when the
28 * @param {number} offset The offset from the parent context.
29 * @author Kris Maglione <maglione.k@gmail.com>
32 var CompletionContext = Class("CompletionContext", {
33 init: function (editor, name, offset) {
38 if (editor instanceof this.constructor) {
40 name = parent.name + "/" + name;
43 this.autoComplete = this.options.get("autocomplete").getKey(name);
44 this.sortResults = this.options.get("wildsort").getKey(name);
45 this.wildcase = this.options.get("wildcase").getKey(name);
48 this.contexts = parent.contexts;
49 if (name in this.contexts)
50 self = this.contexts[name];
52 self.contexts[name] = this;
55 * @property {CompletionContext} This context's parent. {null} when
56 * this is a top-level context.
60 ["filters", "keys", "process", "title", "quote"].forEach(function (key)
61 self[key] = parent[key] && util.cloneObject(parent[key]));
62 ["anchored", "compare", "editor", "_filter", "filterFunc", "forceAnchored", "top"].forEach(function (key)
63 self[key] = parent[key]);
65 self.__defineGetter__("value", function () this.top.value);
67 self.offset = parent.offset;
68 self.advance(offset || 0);
71 * @property {boolean} Specifies that this context is not finished
75 self.incomplete = false;
78 * @property {boolean} Specifies that this context is waiting for the
79 * user to press <Tab>. Useful when fetching completions could be
80 * dangerous or slow, and the user has enabled autocomplete.
82 self.waitingForTab = false;
86 delete self._generate;
87 delete self.ignoreCase;
90 ["_caret", "contextList", "maxItems", "onUpdate", "selectionTypes", "tabPressed", "updateAsync", "value"].forEach(function (key) {
91 self.__defineGetter__(key, function () this.top[key]);
92 self.__defineSetter__(key, function (val) this.top[key] = val);
96 if (typeof editor == "string")
101 * @property {boolean} Specifies whether this context results must
102 * match the filter at the beginning of the string.
105 this.anchored = true;
106 this.forceAnchored = null;
108 this.compare = function (a, b) String.localeCompare(a.text, b.text);
110 * @property {function} This function is called when we close
111 * a completion window with Esc or Ctrl-c. Usually this callback
112 * is only needed for long, asynchronous completions
116 * @property {[CompletionContext]} A list of active
117 * completion contexts, in the order in which they were
120 this.contextList = [];
122 * @property {Object} A map of all contexts, keyed on their names.
123 * Names are assigned when a context is forked, with its specified
124 * name appended, after a '/', to its parent's name. May
125 * contain inactive contexts. For active contexts, see
126 * {@link #contextList}.
128 this.contexts = { "": this };
130 * @property {function} The function used to filter the results.
131 * @default Selects all results which match every predicate in the
132 * {@link #filters} array.
134 this.filterFunc = function (items) {
137 reduce(function (res, filter) res.filter(function (item) filter.call(self, item)),
141 * @property {Array} An array of predicates on which to filter the
144 this.filters = [CompletionContext.Filter.text];
146 * @property {Object} A mapping of keys, for {@link #getKey}. Given
147 * { key: value }, getKey(item, key) will return values as such:
148 * if value is a string, it will return item.item[value]. If it's a
149 * function, it will return value(item.item).
151 this.keys = { text: 0, description: 1, icon: "icon" };
153 * @property {number} This context's offset from the beginning of
154 * {@link #editor}'s value.
156 this.offset = offset || 0;
158 * @property {function} A function which is called when any subcontext
159 * changes its completion list. Only called when
160 * {@link #updateAsync} is true.
162 this.onUpdate = function () true;
167 * @property {CompletionContext} The top-level completion context.
170 this.__defineGetter__("incomplete", function () this._incomplete || this.contextList.some(function (c) c.parent && c.incomplete));
171 this.__defineGetter__("waitingForTab", function () this._waitingForTab || this.contextList.some(function (c) c.parent && c.waitingForTab));
172 this.__defineSetter__("incomplete", function (val) { this._incomplete = val; });
173 this.__defineSetter__("waitingForTab", function (val) { this._waitingForTab = val; });
177 * @property {Object} A general-purpose store for functions which need to
178 * cache data between calls.
184 * @property {Object} A cache for return values of {@link #generate}.
188 * @property {string} A key detailing when the cached value of
189 * {@link #generate} may be used. Every call to
190 * {@link #generate} stores its result in {@link #itemCache}.
191 * When itemCache[key] exists, its value is returned, and
192 * {@link #generate} is not called again.
196 * @property {string} A message to be shown before any results.
199 this.name = name || "";
201 this._completions = []; // FIXME
203 * Returns a key, as detailed in {@link #keys}.
206 this.getKey = function (item, key) (typeof self.keys[key] == "function") ? self.keys[key].call(this, item.item) :
207 key in self.keys ? item.item[self.keys[key]]
212 __title: Class.Memoize(function () this._title.map(function (s)
213 typeof s == "string" ? messages.get("completion.title." + s, s)
218 return this._title = val;
220 get title() this.__title,
222 get activeContexts() this.contextList.filter(function (c) c.items.length),
228 * An object describing the results from all sub-contexts. Results are
229 * adjusted so that all have the same starting offset.
237 let allItems = this.contextList.map(function (context) context.hasItems && context.items.length);
238 if (this.cache.allItems && array.equals(this.cache.allItems, allItems))
239 return this.cache.allItemsResult;
240 this.cache.allItems = allItems;
242 let minStart = Math.min.apply(Math, this.activeContexts.map(function (c) c.offset));
243 if (minStart == Infinity)
246 this.cache.allItemsResult = memoize({
249 get longestSubstring() self.longestAllSubstring,
251 get items() array.flatten(self.activeContexts.map(function (context) {
252 let prefix = self.value.substring(minStart, context.offset);
254 return context.items.map(function (item) ({
255 text: prefix + item.text,
256 result: prefix + item.result,
262 return this.cache.allItemsResult;
266 return { start: 0, items: [], longestAllSubstring: "" };
270 get allSubstrings() {
271 let contexts = this.activeContexts;
272 let minStart = Math.min.apply(Math, contexts.map(function (c) c.offset));
273 let lists = contexts.map(function (context) {
274 let prefix = context.value.substring(minStart, context.offset);
275 return context.substrings.map(function (s) prefix + s);
278 /* TODO: Deal with sub-substrings for multiple contexts again.
281 let substrings = lists.reduce(
282 function (res, list) res.filter(function (str) list.some(function (s) s.substr(0, str.length) == str)),
284 if (!substrings) // FIXME: How is this undefined?
286 return array.uniq(Array.slice(substrings));
289 get longestAllSubstring() {
290 return this.allSubstrings.reduce(function (a, b) a.length > b.length ? a : b, "");
293 get caret() this._caret - this.offset,
294 set caret(val) this._caret = val + this.offset,
296 get compare() this._compare || function () 0,
297 set compare(val) this._compare = val,
299 get completions() this._completions || [],
300 set completions(items) {
301 if (items && isArray(items.array))
303 // Accept a generator
305 items = [x for (x in Iterator(items || []))];
306 if (this._completions !== items) {
307 delete this.cache.filtered;
308 delete this.cache.filter;
309 this.cache.rows = [];
310 this._completions = items;
311 this.itemCache[this.key] = items;
314 if (this._completions)
315 this.hasItems = this._completions.length > 0;
317 if (this.updateAsync && !this.noUpdate)
318 util.trapErrors("onUpdate", this);
321 get createRow() this._createRow || template.completionRow, // XXX
322 set createRow(createRow) this._createRow = createRow,
324 get filterFunc() this._filterFunc || util.identity,
325 set filterFunc(val) this._filterFunc = val,
327 get filter() this._filter != null ? this._filter : this.value.substr(this.offset, this.caret),
329 delete this.ignoreCase;
330 return this._filter = val;
334 anchored: this.anchored,
337 process: this.process
340 this.anchored = format.anchored,
341 this.title = format.title || this.title;
342 this.keys = format.keys || this.keys;
343 this.process = format.process || this.process;
347 * @property {string | xml | null}
348 * The message displayed at the head of the completions for the
351 get message() this._message || (this.waitingForTab && this.hasItems !== false ? _("completion.waitingFor", "<Tab>") : null),
352 set message(val) this._message = val,
355 * The prototype object for items returned by {@link items}.
357 get itemPrototype() {
359 let res = { highlight: "" };
361 function result(quote) {
362 yield ["context", function () self];
363 yield ["result", quote ? function () quote[0] + util.trapErrors(1, quote, this.text) + quote[2]
364 : function () this.text];
365 yield ["texts", function () Array.concat(this.text)];
368 for (let i in iter(this.keys, result(this.quote))) {
370 if (typeof v == "string" && /^[.[]/.test(v))
371 // This is only allowed to be a simple accessor, and shouldn't
372 // reference any variables. Don't bother with eval context.
373 v = Function("i", "return i" + v);
374 if (typeof v == "function")
375 res.__defineGetter__(k, function () Class.replaceProperty(this, k, v.call(this, this.item, self)));
377 res.__defineGetter__(k, function () Class.replaceProperty(this, k, this.item[v]));
378 res.__defineSetter__(k, function (val) Class.replaceProperty(this, k, val));
384 * Returns true when the completions generated by {@link #generate}
385 * must be regenerated. May be set to true to invalidate the current
388 get regenerate() this._generate && (!this.completions || !this.itemCache[this.key] || this._cache.offset != this.offset),
389 set regenerate(val) { if (val) delete this.itemCache[this.key]; },
392 * A property which may be set to a function to generate the value
393 * of {@link completions} only when necessary. The generated
394 * completions are linked to the value in {@link #key} and may be
395 * invalidated by setting the {@link #regenerate} property.
397 get generate() this._generate || null,
399 this.hasItems = true;
400 this._generate = arg;
403 * Generates the item list in {@link #completions} via the
404 * {@link #generate} method if the previously generated value is no
407 generateCompletions: function generateCompletions() {
408 if (this.offset != this._cache.offset || this.lastActivated != this.top.runCount) {
410 this._cache.offset = this.offset;
411 this.lastActivated = this.top.runCount;
413 if (!this.itemCache[this.key]) {
415 let res = this._generate();
417 this.itemCache[this.key] = res;
421 this.message = _("error.error", e);
425 this.noUpdate = true;
426 this.completions = this.itemCache[this.key];
427 this.noUpdate = false;
430 ignoreCase: Class.Memoize(function () {
431 let mode = this.wildcase;
434 else if (mode == "ignore")
437 return !/[A-Z]/.test(this.filter);
441 * Returns a list of all completion items which match the current
442 * filter. The items returned are objects containing one property
443 * for each corresponding property in {@link keys}. The returned
444 * list is generated on-demand from the item list in {@link completions}
445 * or generated by {@link generate}, and is cached as long as no
446 * properties which would invalidate the result are changed.
449 // Don't return any items if completions or generator haven't
450 // been set during this completion cycle.
454 // Regenerate completions if we must
456 this.generateCompletions();
457 let items = this.completions;
459 // Check for cache miss
460 if (this._cache.completions !== this.completions) {
461 this._cache.completions = this.completions;
462 this._cache.constructed = null;
463 this.cache.filtered = null;
466 if (this.cache.filtered && this.cache.filter == this.filter)
467 return this.cache.filtered;
469 this.cache.rows = [];
470 this.cache.filter = this.filter;
475 delete this._substrings;
477 if (!this.forceAnchored && this.options)
478 this.anchored = this.options.get("wildanchor").getKey(this.name, this.anchored);
482 this.matchString = this.anchored ?
483 function (filter, str) String.toLowerCase(str).indexOf(filter.toLowerCase()) == 0 :
484 function (filter, str) String.toLowerCase(str).indexOf(filter.toLowerCase()) >= 0;
486 this.matchString = this.anchored ?
487 function (filter, str) String.indexOf(str, filter) == 0 :
488 function (filter, str) String.indexOf(str, filter) >= 0;
491 this.processor = Array.slice(this.process);
493 this.processor[0] = function (item, text) self.process[0].call(self, item,
494 template.highlightFilter(item.text, self.filter, null, item.isURI));
498 if (!this._cache.constructed) {
499 let proto = this.itemPrototype;
500 this._cache.constructed = items.map(function (item) ({ __proto__: proto, item: item }));
504 let filtered = this.filterFunc(this._cache.constructed);
506 filtered = filtered.slice(0, this.maxItems);
509 if (this.sortResults && this.compare) {
510 filtered.sort(this.compare);
511 if (!this.anchored) {
512 let filter = this.filter;
513 filtered.sort(function (a, b) (b.text.indexOf(filter) == 0) - (a.text.indexOf(filter) == 0));
517 return this.cache.filtered = filtered;
520 this.message = _("error.error", e);
527 * Returns a list of all substrings common to all items which
528 * include the current filter.
531 let items = this.items;
532 if (items.length == 0 || !this.hasItems)
534 if (this._substrings)
535 return this._substrings;
537 let fixCase = this.ignoreCase ? String.toLowerCase : util.identity;
538 let text = fixCase(items[0].text);
539 let filter = fixCase(this.filter);
541 // Exceedingly long substrings cause Gecko to go into convulsions
542 if (text.length > 100)
543 text = text.substr(0, 100);
546 var compare = function compare(text, s) text.substr(0, s.length) == s;
547 var substrings = [text];
550 var compare = function compare(text, s) text.indexOf(s) >= 0;
554 let length = filter.length;
555 while ((idx = text.indexOf(filter, start)) > -1 && idx < text.length) {
556 substrings.push(text.substring(idx));
561 substrings = items.reduce(function (res, item)
562 res.map(function (substring) {
563 // A simple binary search to find the longest substring
564 // of the given string which also matches the current
566 let len = substring.length;
567 let i = 0, n = len + 1;
568 let result = n && fixCase(item.result);
570 let m = Math.floor(n / 2);
571 let keep = compare(result, substring.substring(0, i + m));
581 return len == substring.length ? substring : substring.substr(0, Math.max(len, 0));
585 let quote = this.quote;
587 substrings = substrings.map(function (str) quote[0] + quote[1](str));
588 return this._substrings = substrings;
592 * Advances the context *count* characters. {@link #filter} is advanced to
593 * match. If {@link #quote} is non-null, its prefix and suffix are set to
596 * This function is still imperfect for quoted strings. When
597 * {@link #quote} is non-null, it adjusts the count based on the quoted
598 * size of the *count*-character substring of the filter, which is accurate
599 * so long as unquoting and quoting a string will always map to the
600 * original quoted string, which is often not the case.
602 * @param {number} count The number of characters to advance the context.
604 advance: function advance(count) {
605 delete this.ignoreCase;
607 if (this.quote && count) {
608 advance = this.quote[1](this.filter.substr(0, count)).length;
609 count = this.quote[0].length + advance;
613 this.offset += count;
615 this._filter = this._filter.substr(arguments[0] || 0);
619 * Calls the {@link #cancel} method of all currently active
622 cancelAll: function () {
623 for (let [, context] in Iterator(this.contextList)) {
630 * Gets a key from {@link #cache}, setting it to *defVal* if it doesn't
633 * @param {string} key
636 getCache: function (key, defVal) {
637 if (!(key in this.cache))
638 this.cache[key] = defVal();
639 return this.cache[key];
642 getItems: function getItems(start, end) {
643 let items = this.items;
644 let step = start > end ? -1 : 1;
645 start = Math.max(0, start || 0);
646 end = Math.min(items.length, end ? end : items.length);
647 return iter.map(util.range(start, end, step), function (i) items[i]);
650 getRow: function getRow(idx, doc) {
651 let cache = this.cache.rows;
653 if (idx in this.items && !(idx in this.cache.rows))
655 cache[idx] = util.xmlToDom(this.createRow(this.items[idx]),
660 cache[idx] = util.xmlToDom(
661 <div highlight="CompItem" style="white-space: nowrap">
662 <li highlight="CompResult">{this.text} </li>
663 <li highlight="CompDesc ErrorMsg">{e} </li>
664 </div>, doc || this.doc);
670 getRows: function getRows(start, end, doc) {
672 let items = this.items;
673 let cache = this.cache.rows;
674 let step = start > end ? -1 : 1;
676 start = Math.max(0, start || 0);
677 end = Math.min(items.length, end != null ? end : items.length);
680 for (let i in util.range(start, end, step))
681 yield [i, this.getRow(i)];
685 * Forks this completion context to create a new sub-context named
686 * as {this.name}/{name}. The new context is automatically advanced
687 * *offset* characters. If *completer* is provided, it is called
688 * with *self* as its 'this' object, the new context as its first
689 * argument, and any subsequent arguments after *completer* as its
690 * following arguments.
692 * If *completer* is provided, this function returns its return
693 * value, otherwise it returns the new completion context.
695 * @param {string} name The name of the new context.
696 * @param {number} offset The offset of the new context relative to
697 * the current context's offset.
698 * @param {object} self *completer*'s 'this' object. @optional
699 * @param {function|string} completer A completer function to call
700 * for the new context. If a string is provided, it is
701 * interpreted as a method to access on *self*.
703 fork: function fork(name, offset, self, completer) {
704 return this.forkapply(name, offset, self, completer, Array.slice(arguments, fork.length));
707 forkapply: function forkapply(name, offset, self, completer, args) {
708 if (isString(completer))
709 completer = self[completer];
710 let context = this.constructor(this, name, offset);
711 if (this.contextList.indexOf(context) < 0)
712 this.contextList.push(context);
714 if (!context.autoComplete && !context.tabPressed && context.editor)
715 context.waitingForTab = true;
716 else if (completer) {
717 let res = completer.apply(self || this, [context].concat(args));
718 if (res && !isArray(res) && !isArray(res.__proto__))
719 res = [k for (k in res)];
721 context.completions = res;
729 split: function split(name, obj, fn) {
732 let context = this.fork(name);
733 function alias(prop) {
734 context.__defineGetter__(prop, function () self[prop]);
735 context.__defineSetter__(prop, function (val) self[prop] = val);
738 alias("_completions");
740 alias("_regenerate");
742 alias("lastActivated");
743 context.hasItems = true;
744 this.hasItems = false;
746 return fn.apply(obj || this, [context].concat(Array.slice(arguments, split.length)));
751 * Highlights text in the nsIEditor associated with this completion
752 * context. *length* characters are highlighted from the position
753 * *start*, relative to the current context's offset, with the
754 * selection type *type* as defined in nsISelectionController.
756 * When called with no arguments, all highlights are removed. When
757 * called with a 0 length, all highlights of type *type* are
760 * @param {number} start The position at which to start
762 * @param {number} length The length of the substring to highlight.
763 * @param {string} type The selection type to highlight with.
765 highlight: function highlight(start, length, type) {
766 if (arguments.length == 0) {
767 for (let type in this.selectionTypes)
768 this.highlight(0, 0, type);
769 this.selectionTypes = {};
772 // Requires Gecko >= 1.9.1
773 this.selectionTypes[type] = true;
774 const selType = Ci.nsISelectionController["SELECTION_" + type];
775 let sel = this.editor.selectionController.getSelection(selType);
777 sel.removeAllRanges();
779 let range = this.editor.selection.getRangeAt(0).cloneRange();
780 range.setStart(range.startContainer, this.offset + start);
781 range.setEnd(range.startContainer, this.offset + start + length);
789 * Tests the given string for a match against the current filter,
790 * taking into account anchoring and case sensitivity rules.
792 * @param {string} str The string to match.
793 * @returns {boolean} True if the string matches, false otherwise.
795 match: function match(str) this.matchString(this.filter, str),
798 * Pushes a new output processor onto the processor chain of
799 * {@link #process}. The provided function is called with the item
800 * and text to process along with a reference to the processor
801 * previously installed in the given *index* of {@link #process}.
803 * @param {number} index The index into {@link #process}.
804 * @param {function(object, string, function)} func The new
807 pushProcessor: function pushProcess(index, func) {
808 let next = this.process[index];
809 this.process[index] = function (item, text) func(item, text, next);
813 * Resets this completion context and all sub-contexts for use in a
814 * new completion cycle. May only be called on the top-level
817 reset: function reset() {
823 this.process = [template.icon, function (item, k) k];
824 this.filters = [CompletionContext.Filter.text];
825 this.tabPressed = false;
826 this.title = ["Completions"];
827 this.updateAsync = false;
832 this.value = this.editor.selection.focusNode.textContent;
833 this._caret = this.editor.selection.focusOffset;
836 this.value = this._value;
837 this._caret = this.value.length;
839 //for (let key in (k for ([k, v] in Iterator(self.contexts)) if (v.offset > this.caret)))
840 // delete this.contexts[key];
841 for each (let context in this.contexts) {
842 context.hasItems = false;
843 context.incomplete = false;
845 this.waitingForTab = false;
847 for each (let context in this.contextList)
848 context.lastActivated = this.runCount;
849 this.contextList = [];
853 * Wait for all subcontexts to complete.
855 * @param {number} timeout The maximum time, in milliseconds, to wait.
856 * If 0 or null, wait indefinitely.
857 * @param {boolean} interruptible When true, the call may be interrupted
858 * via <C-c>, in which case, "Interrupted" may be thrown.
860 wait: function wait(timeout, interruptable) {
862 return util.waitFor(function () !this.incomplete, this, timeout, interruptable);
866 number: function (a, b) parseInt(a.text) - parseInt(b.text) || String.localeCompare(a.text, b.text),
871 text: function (item) {
872 let text = item.texts;
873 for (let [i, str] in Iterator(text)) {
874 if (this.match(String(str))) {
875 item.text = String(text[i]);
881 textDescription: function (item) {
882 return CompletionContext.Filter.text.call(this, item) || this.match(item.description);
888 * @instance completion
890 var Completion = Module("completion", {
894 get setFunctionCompleter() JavaScript.setCompleter, // Backward compatibility
896 Local: function (dactyl, modules, window) ({
899 get modules() modules,
900 get options() modules.options,
903 _runCompleter: function _runCompleter(name, filter, maxItems) {
904 let context = modules.CompletionContext(filter);
905 context.maxItems = maxItems;
906 let res = context.fork.apply(context, ["run", 0, this, name].concat(Array.slice(arguments, 3)));
908 if (Components.stack.caller.name === "runCompleter") // FIXME
909 return { items: res.map(function (i) ({ item: i })) };
910 context.contexts["/run"].completions = res;
912 context.wait(null, true);
913 return context.allItems;
916 runCompleter: function runCompleter(name, filter, maxItems) {
917 return this._runCompleter.apply(this, Array.slice(arguments))
918 .items.map(function (i) i.item);
921 listCompleter: function listCompleter(name, filter, maxItems) {
922 let context = modules.CompletionContext(filter || "");
923 context.maxItems = maxItems;
924 context.fork.apply(context, ["list", 0, this, name].concat(Array.slice(arguments, 3)));
925 context = context.contexts["/list"];
926 context.wait(null, true);
928 let contexts = context.activeContexts;
929 if (!contexts.length)
930 contexts = context.contextList.filter(function (c) c.hasItems).slice(0, 1);
931 if (!contexts.length)
932 contexts = context.contextList.slice(-1);
934 modules.commandline.commandOutput(
935 <div highlight="Completions">
936 { template.map(contexts, function (context)
937 template.completionRow(context.title, "CompTitle") +
938 template.map(context.items, function (item) context.createRow(item), null, 100)) }
943 ////////////////////////////////////////////////////////////////////////////////
944 ////////////////////// COMPLETION TYPES ////////////////////////////////////////
945 /////////////////////////////////////////////////////////////////////////////{{{
947 // filter a list of urls
949 // may consist of search engines, filenames, bookmarks and history,
950 // depending on the 'complete' option
951 // if the 'complete' argument is passed like "h", it temporarily overrides the complete option
952 url: function url(context, complete) {
953 if (/^jar:[^!]*$/.test(context.filter)) {
956 context.quote = context.quote || ["", util.identity, ""];
957 let quote = context.quote[1];
958 context.quote[1] = function (str) quote(str.replace(/!/g, escape));
961 if (this.options["urlseparator"])
962 var skip = util.regexp("^.*" + this.options["urlseparator"] + "\\s*")
963 .exec(context.filter);
966 context.advance(skip[0].length);
968 if (/^about:/.test(context.filter))
969 context.fork("about", 6, this, function (context) {
970 context.title = ["about:"];
971 context.generate = function () {
972 return [[k.substr(services.ABOUT.length), ""]
974 if (k.indexOf(services.ABOUT) == 0)];
978 if (complete == null)
979 complete = this.options["complete"];
981 // Will, and should, throw an error if !(c in opts)
982 Array.forEach(complete, function (c) {
983 let completer = this.urlCompleters[c] || { args: [], completer: this.autocomplete(c.replace(/^native:/, "")) };
984 context.forkapply(c, 0, this, completer.completer, completer.args);
988 addUrlCompleter: function addUrlCompleter(opt) {
989 let completer = Completion.UrlCompleter.apply(null, Array.slice(arguments));
990 completer.args = Array.slice(arguments, completer.length);
991 this.urlCompleters[opt] = completer;
994 autocomplete: curry(function autocomplete(provider, context) {
995 let running = context.getCache("autocomplete-search-running", Object);
997 let name = "autocomplete:" + provider;
998 if (!services.has(name))
999 services.add(name, services.AUTOCOMPLETE + provider, "nsIAutoCompleteSearch");
1000 let service = services[name];
1002 util.assert(service, _("autocomplete.noSuchProvider", provider), false);
1004 if (running[provider]) {
1005 this.completions = this.completions;
1009 context.anchored = false;
1010 context.compare = CompletionContext.Sort.unsorted;
1011 context.filterFunc = null;
1013 let words = context.filter.toLowerCase().split(/\s+/g);
1014 context.hasItems = true;
1015 context.completions = context.completions.filter(function ({ url, title })
1016 words.every(function (w) (url + " " + title).toLowerCase().indexOf(w) >= 0))
1017 context.incomplete = true;
1019 context.format = this.modules.bookmarks.format;
1020 context.keys.extra = function (item) {
1022 return bookmarkcache.get(item.url).extra;
1027 context.title = [_("autocomplete.title", provider)];
1029 context.cancel = function () {
1030 this.incomplete = false;
1031 if (running[provider])
1032 service.stopSearch();
1033 running[provider] = false;
1036 service.startSearch(context.filter, "", context.result, {
1037 onSearchResult: util.wrapCallback(function onSearchResult(search, result) {
1038 if (result.searchResult <= result.RESULT_SUCCESS)
1039 running[provider] = null;
1041 context.incomplete = result.searchResult >= result.RESULT_NOMATCH_ONGOING;
1042 context.completions = [
1043 { url: result.getValueAt(i), title: result.getCommentAt(i), icon: result.getImageAt(i) }
1044 for (i in util.range(0, result.matchCount))
1047 get onUpdateSearchResult() this.onSearchResult
1049 running[provider] = true;
1052 urls: function (context, tags) {
1053 let compare = String.localeCompare;
1054 let contains = String.indexOf;
1055 if (context.ignoreCase) {
1056 compare = util.compareIgnoreCase;
1057 contains = function (a, b) a && a.toLowerCase().indexOf(b.toLowerCase()) > -1;
1061 context.filters.push(function (item) tags.
1062 every(function (tag) (item.tags || []).
1063 some(function (t) !compare(tag, t))));
1065 context.anchored = false;
1067 context.title = ["URL", "Title"];
1069 context.fork("additional", 0, this, function (context) {
1070 context.title[0] += " " + _("completion.additional");
1071 context.filter = context.parent.filter; // FIXME
1072 context.completions = context.parent.completions;
1074 // For items whose URL doesn't exactly match the filter,
1075 // accept them if all tokens match either the URL or the title.
1076 // Filter out all directly matching strings.
1077 let match = context.filters[0];
1078 context.filters[0] = function (item) !match.call(this, item);
1080 // and all that don't match the tokens.
1081 let tokens = context.filter.split(/\s+/);
1082 context.filters.push(function (item) tokens.every(
1083 function (tok) contains(item.url, tok) ||
1084 contains(item.title, tok)));
1086 let re = RegExp(tokens.filter(util.identity).map(util.regexp.escape).join("|"), "g");
1087 function highlight(item, text, i) process[i].call(this, item, template.highlightRegexp(text, re));
1088 let process = context.process;
1090 function (item, text) highlight.call(this, item, item.text, 0),
1091 function (item, text) highlight.call(this, item, text, 1)
1097 UrlCompleter: Struct("name", "description", "completer")
1099 init: function init(dactyl, modules, window) {
1100 init.superapply(this, arguments);
1102 modules.CompletionContext = Class("CompletionContext", CompletionContext, {
1103 init: function init() {
1104 this.modules = modules;
1105 return init.superapply(this, arguments);
1108 get options() this.modules.options
1111 commands: function (dactyl, modules, window) {
1112 const { commands, completion } = modules;
1113 commands.add(["contexts"],
1114 "List the completion contexts used during completion of an Ex command",
1116 modules.commandline.commandOutput(
1117 <div highlight="Completions">
1118 { template.completionRow(["Context", "Title"], "CompTitle") }
1119 { template.map(completion.contextList || [], function (item) template.completionRow(item, "CompItem")) }
1124 completer: function (context) {
1125 let PREFIX = "/ex/contexts";
1126 context.fork("ex", 0, completion, "ex");
1127 completion.contextList = [[k.substr(PREFIX.length), v.title[0]] for ([k, v] in iter(context.contexts)) if (k.substr(0, PREFIX.length) == PREFIX)];
1132 options: function (dactyl, modules, window) {
1133 const { completion, options } = modules;
1136 // Why do we need ""?
1137 // Because its description is useful during completion. --Kris
1138 "": "Complete only the first match",
1139 "full": "Complete the next full match",
1140 "longest": "Complete the longest common string",
1141 "list": "If more than one match, list all matches",
1142 "list:full": "List all and complete first match",
1143 "list:longest": "List all and complete the longest common string"
1145 checkHas: function (value, val) {
1146 let [first, second] = value.split(":", 2);
1147 return first == val || second == val;
1150 test = function (val) this.value.some(function (value) this.checkHas(value, val), this);
1151 return Array.some(arguments, test, this);
1155 options.add(["altwildmode", "awim"],
1156 "Define the behavior of the c_<A-Tab> key in command-line completion",
1157 "stringlist", "list:full",
1160 options.add(["autocomplete", "au"],
1161 "Automatically update the completion list on any key press",
1162 "regexplist", ".*");
1164 options.add(["complete", "cpt"],
1165 "Items which are completed at the :open prompts",
1166 "stringlist", "slf",
1177 get values() values(completion.urlCompleters).toArray()
1178 .concat([let (name = k.substr(services.AUTOCOMPLETE.length))
1179 ["native:" + name, _("autocomplete.description", name)]
1181 if (k.indexOf(services.AUTOCOMPLETE) == 0)]),
1183 setter: function setter(values) {
1184 if (values.length == 1 && !Set.has(values[0], this.values)
1185 && Array.every(values[0], Set.has(this.valueMap)))
1186 return Array.map(values[0], function (v) this[v], this.valueMap);
1190 validator: function validator(values) validator.supercall(this, this.setter(values))
1193 options.add(["wildanchor", "wia"],
1194 "Define which completion groups only match at the beginning of their text",
1195 "regexplist", "!/ex/(back|buffer|ext|forward|help|undo)");
1197 options.add(["wildcase", "wic"],
1198 "Completion case matching mode",
1199 "regexpmap", ".?:smart",
1202 "smart": "Case is significant when capital letters are typed",
1203 "match": "Case is always significant",
1204 "ignore": "Case is never significant"
1208 options.add(["wildmode", "wim"],
1209 "Define the behavior of the c_<Tab> key in command-line completion",
1210 "stringlist", "list:full",
1213 options.add(["wildsort", "wis"],
1214 "Define which completion groups are sorted",
1215 "regexplist", ".*");
1221 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1223 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: