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>
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 defineModule("completion", {
10 exports: ["CompletionContext", "Completion", "completion"]
13 lazyRequire("dom", ["DOM"]);
14 lazyRequire("messages", ["_", "messages"]);
15 lazyRequire("template", ["template"]);
18 * Creates a new completion context.
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
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
31 * @param {number} offset The offset from the parent context.
32 * @author Kris Maglione <maglione.k@gmail.com>
35 var CompletionContext = Class("CompletionContext", {
36 init: function cc_init(editor, name, offset) {
41 if (editor instanceof this.constructor) {
43 name = parent.name + "/" + name;
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);
51 this.contexts = parent.contexts;
52 if (name in this.contexts)
53 self = this.contexts[name];
55 self.contexts[name] = this;
58 * @property {CompletionContext} This context's parent. {null} when
59 * this is a top-level context.
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]);
68 self.__defineGetter__("value", function get_value() this.top.value);
70 self.offset = parent.offset;
71 self.advance(offset || 0);
74 * @property {boolean} Specifies that this context is not finished
78 self.incomplete = false;
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.
85 self.waitingForTab = false;
89 delete self._generate;
90 delete self.ignoreCase;
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);
99 if (typeof editor == "string")
100 this._value = editor;
102 this.editor = editor;
104 * @property {boolean} Specifies whether this context results must
105 * match the filter at the beginning of the string.
108 this.anchored = true;
109 this.forceAnchored = null;
111 this.compare = function compare(a, b) String.localeCompare(a.text, b.text);
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
119 * @property {[CompletionContext]} A list of active
120 * completion contexts, in the order in which they were
123 this.contextList = [];
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}.
131 this.contexts = { "": this };
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.
137 this.filterFunc = function filterFunc(items) {
140 reduce(function r(res, filter) res.filter(function f(item) filter.call(self, item)),
144 * @property {Array} An array of predicates on which to filter the
147 this.filters = [CompletionContext.Filter.text];
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).
154 this.keys = { text: 0, description: 1, icon: "icon" };
156 * @property {number} This context's offset from the beginning of
157 * {@link #editor}'s value.
159 this.offset = offset || 0;
161 * @property {function} A function which is called when any subcontext
162 * changes its completion list. Only called when
163 * {@link #updateAsync} is true.
165 this.onUpdate = function onUpdate() true;
170 * @property {CompletionContext} The top-level completion context.
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; });
182 * @property {Object} A general-purpose store for functions which need to
183 * cache data between calls.
189 * @property {Object} A cache for return values of {@link #generate}.
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.
201 * @property {string} A message to be shown before any results.
204 this.name = name || "";
206 this._completions = []; // FIXME
208 * Returns a key, as detailed in {@link #keys}.
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]]
217 __title: Class.Memoize(function __title() this._title.map(function (s)
218 typeof s == "string" ? messages.get("completion.title." + s, s)
223 return this._title = val;
225 get title() this.__title,
227 get activeContexts() this.contextList.filter(function f(c) c.items.length),
233 * An object describing the results from all sub-contexts. Results are
234 * adjusted so that all have the same starting offset.
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;
247 let minStart = Math.min.apply(Math, this.activeContexts.map(function m(c) c.offset));
248 if (minStart == Infinity)
251 this.cache.allItemsResult = memoize({
254 get longestSubstring() self.longestAllSubstring,
256 get items() array.flatten(self.activeContexts.map(function m(context) {
257 let prefix = self.value.substring(minStart, context.offset);
259 return context.items.map(function m(item) ({
260 text: prefix + item.text,
261 result: prefix + item.result,
267 return this.cache.allItemsResult;
271 return { start: 0, items: [], longestAllSubstring: "" };
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);
283 /* TODO: Deal with sub-substrings for multiple contexts again.
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)),
289 if (!substrings) // FIXME: How is this undefined?
291 return array.uniq(Array.slice(substrings));
294 get longestAllSubstring() {
295 return this.allSubstrings.reduce(function r(a, b) a.length > b.length ? a : b, "");
298 get caret() this._caret - this.offset,
299 set caret(val) this._caret = val + this.offset,
301 get compare() this._compare || function compare() 0,
302 set compare(val) this._compare = val,
304 get completions() this._completions || [],
305 set completions(items) {
306 if (items && isArray(items.array))
308 // Accept a generator
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;
319 if (this._completions)
320 this.hasItems = this._completions.length > 0;
322 if (this.updateAsync && !this.noUpdate)
323 util.trapErrors("onUpdate", this);
326 get createRow() this._createRow || template.completionRow, // XXX
327 set createRow(createRow) this._createRow = createRow,
329 get filterFunc() this._filterFunc || util.identity,
330 set filterFunc(val) this._filterFunc = val,
332 get filter() this._filter != null ? this._filter : this.value.substr(this.offset, this.caret),
334 delete this.ignoreCase;
335 return this._filter = val;
339 anchored: this.anchored,
342 process: this.process
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;
352 * @property {string | xml | null}
353 * The message displayed at the head of the completions for the
356 get message() this._message || (this.waitingForTab && this.hasItems !== false ? _("completion.waitingFor", "<Tab>") : null),
357 set message(val) this._message = val,
360 * The prototype object for items returned by {@link items}.
362 get itemPrototype() {
364 let res = { highlight: "" };
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)];
373 for (let i in iter(this.keys, result(this.quote))) {
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)));
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));
389 * Returns true when the completions generated by {@link #generate}
390 * must be regenerated. May be set to true to invalidate the current
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]; },
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.
402 get generate() this._generate || null,
404 this.hasItems = true;
405 this._generate = arg;
408 * Generates the item list in {@link #completions} via the
409 * {@link #generate} method if the previously generated value is no
412 generateCompletions: function generateCompletions() {
413 if (this.offset != this._cache.offset || this.lastActivated != this.top.runCount) {
415 this._cache.offset = this.offset;
416 this.lastActivated = this.top.runCount;
418 if (!this.itemCache[this.key] && !this.waitingForTab) {
420 let res = this._generate();
422 this.itemCache[this.key] = res;
426 this.message = _("error.error", e);
430 this.noUpdate = true;
431 this.completions = this.itemCache[this.key];
432 this.noUpdate = false;
435 ignoreCase: Class.Memoize(function M() {
436 let mode = this.wildcase;
439 else if (mode == "ignore")
442 return !/[A-Z]/.test(this.filter);
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.
454 // Don't return any items if completions or generator haven't
455 // been set during this completion cycle.
459 // Regenerate completions if we must
461 this.generateCompletions();
462 let items = this.completions;
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;
471 if (this.cache.filtered && this.cache.filter == this.filter)
472 return this.cache.filtered;
474 this.cache.rows = [];
475 this.cache.filter = this.filter;
480 delete this._substrings;
482 if (!this.forceAnchored && this.options)
483 this.anchored = this.options.get("wildanchor").getKey(this.name, this.anchored);
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;
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;
496 this.processor = Array.slice(this.process);
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));
503 if (!this._cache.constructed) {
504 let proto = this.itemPrototype;
505 this._cache.constructed = items.map(function m(item) ({ __proto__: proto, item: item }));
509 let filtered = this.filterFunc(this._cache.constructed);
511 filtered = filtered.slice(0, this.maxItems);
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));
522 return this.cache.filtered = filtered;
525 this.message = _("error.error", e);
532 * Returns a list of all substrings common to all items which
533 * include the current filter.
536 let items = this.items;
537 if (items.length == 0 || !this.hasItems)
539 if (this._substrings)
540 return this._substrings;
542 let fixCase = this.ignoreCase ? String.toLowerCase : util.identity;
543 let text = fixCase(items[0].text);
544 let filter = fixCase(this.filter);
546 // Exceedingly long substrings cause Gecko to go into convulsions
547 if (text.length > 100)
548 text = text.substr(0, 100);
551 var compare = function compare(text, s) text.substr(0, s.length) == s;
552 var substrings = [text];
555 var compare = function compare(text, s) text.indexOf(s) >= 0;
559 let length = filter.length;
560 while ((idx = text.indexOf(filter, start)) > -1 && idx < text.length) {
561 substrings.push(text.substring(idx));
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
571 let len = substring.length;
572 let i = 0, n = len + 1;
573 let result = n && fixCase(item.result);
575 let m = Math.floor(n / 2);
576 let keep = compare(result, substring.substring(0, i + m));
586 return len == substring.length ? substring : substring.substr(0, Math.max(len, 0));
590 let quote = this.quote;
592 substrings = substrings.map(function m(str) quote[0] + quote[1](str));
593 return this._substrings = substrings;
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
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.
607 * @param {number} count The number of characters to advance the context.
609 advance: function advance(count) {
610 delete this.ignoreCase;
612 if (this.quote && count) {
613 advance = this.quote[1](this.filter.substr(0, count)).length;
614 count = this.quote[0].length + advance;
618 this.offset += count;
620 this._filter = this._filter.substr(arguments[0] || 0);
624 * Calls the {@link #cancel} method of all currently active
627 cancelAll: function cancelAll() {
628 for (let [, context] in Iterator(this.contextList)) {
635 * Gets a key from {@link #cache}, setting it to *defVal* if it doesn't
638 * @param {string} key
641 getCache: function getCache(key, defVal) {
642 if (!(key in this.cache))
643 this.cache[key] = defVal();
644 return this.cache[key];
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]);
655 getRow: function getRow(idx, doc) {
656 let cache = this.cache.rows;
658 if (idx in this.items && !(idx in this.cache.rows))
660 cache[idx] = DOM.fromJSON(this.createRow(this.items[idx]),
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"]],
676 getRows: function getRows(start, end, doc) {
678 let items = this.items;
679 let cache = this.cache.rows;
680 let step = start > end ? -1 : 1;
682 start = Math.max(0, start || 0);
683 end = Math.min(items.length, end != null ? end : items.length);
686 for (let i in util.range(start, end, step))
687 yield [i, this.getRow(i)];
691 * Forks this completion context to create a new sub-context named
692 * as {this.name}/{name}. The new context is automatically advanced
693 * *offset* characters. If *completer* is provided, it is called
694 * with *self* as its 'this' object, the new context as its first
695 * argument, and any subsequent arguments after *completer* as its
696 * following arguments.
698 * If *completer* is provided, this function returns its return
699 * value, otherwise it returns the new completion context.
701 * @param {string} name The name of the new context.
702 * @param {number} offset The offset of the new context relative to
703 * the current context's offset.
704 * @param {object} self *completer*'s 'this' object. @optional
705 * @param {function|string} completer A completer function to call
706 * for the new context. If a string is provided, it is
707 * interpreted as a method to access on *self*.
709 fork: function fork(name, offset, self, completer) {
710 return this.forkapply(name, offset, self, completer, Array.slice(arguments, fork.length));
713 forkapply: function forkapply(name, offset, self, completer, args) {
714 if (isString(completer))
715 completer = self[completer];
716 let context = this.constructor(this, name, offset);
717 if (this.contextList.indexOf(context) < 0)
718 this.contextList.push(context);
720 if (!context.autoComplete && !context.tabPressed && context.editor)
721 context.waitingForTab = true;
722 else if (completer) {
723 let res = completer.apply(self || this, [context].concat(args));
724 if (res && !isArray(res) && !isArray(res.__proto__))
725 res = [k for (k in res)];
727 context.completions = res;
735 split: function split(name, obj, fn) {
738 let context = this.fork(name);
739 function alias(prop) {
740 context.__defineGetter__(prop, function get_() self[prop]);
741 context.__defineSetter__(prop, function set_(val) self[prop] = val);
744 alias("_completions");
746 alias("_regenerate");
748 alias("lastActivated");
749 context.hasItems = true;
750 this.hasItems = false;
752 return fn.apply(obj || this, [context].concat(Array.slice(arguments, split.length)));
757 * Highlights text in the nsIEditor associated with this completion
758 * context. *length* characters are highlighted from the position
759 * *start*, relative to the current context's offset, with the
760 * selection type *type* as defined in nsISelectionController.
762 * When called with no arguments, all highlights are removed. When
763 * called with a 0 length, all highlights of type *type* are
766 * @param {number} start The position at which to start
768 * @param {number} length The length of the substring to highlight.
769 * @param {string} type The selection type to highlight with.
771 highlight: function highlight(start, length, type) {
772 if (arguments.length == 0) {
773 for (let type in this.selectionTypes)
774 this.highlight(0, 0, type);
775 this.selectionTypes = {};
778 // Requires Gecko >= 1.9.1
779 this.selectionTypes[type] = true;
780 const selType = Ci.nsISelectionController["SELECTION_" + type];
781 let sel = this.editor.selectionController.getSelection(selType);
783 sel.removeAllRanges();
785 let range = this.editor.selection.getRangeAt(0).cloneRange();
786 range.setStart(range.startContainer, this.offset + start);
787 range.setEnd(range.startContainer, this.offset + start + length);
795 * Tests the given string for a match against the current filter,
796 * taking into account anchoring and case sensitivity rules.
798 * @param {string} str The string to match.
799 * @returns {boolean} True if the string matches, false otherwise.
801 match: function match(str) this.matchString(this.filter, str),
804 * Pushes a new output processor onto the processor chain of
805 * {@link #process}. The provided function is called with the item
806 * and text to process along with a reference to the processor
807 * previously installed in the given *index* of {@link #process}.
809 * @param {number} index The index into {@link #process}.
810 * @param {function(object, string, function)} func The new
813 pushProcessor: function pushProcess(index, func) {
814 let next = this.process[index];
815 this.process[index] = function process_(item, text) func(item, text, next);
819 * Resets this completion context and all sub-contexts for use in a
820 * new completion cycle. May only be called on the top-level
823 reset: function reset() {
829 this.process = [template.icon, function process_1(item, k) k];
830 this.filters = [CompletionContext.Filter.text];
831 this.tabPressed = false;
832 this.title = ["Completions"];
833 this.updateAsync = false;
838 this.value = this.editor.selection.focusNode.textContent;
839 this._caret = this.editor.selection.focusOffset;
842 this.value = this._value;
843 this._caret = this.value.length;
845 //for (let key in (k for ([k, v] in Iterator(self.contexts)) if (v.offset > this.caret)))
846 // delete this.contexts[key];
847 for each (let context in this.contexts) {
848 context.hasItems = false;
849 context.incomplete = false;
851 this.waitingForTab = false;
853 for each (let context in this.contextList)
854 context.lastActivated = this.runCount;
855 this.contextList = [];
859 * Wait for all subcontexts to complete.
861 * @param {number} timeout The maximum time, in milliseconds, to wait.
862 * If 0 or null, wait indefinitely.
863 * @param {boolean} interruptible When true, the call may be interrupted
864 * via <C-c>, in which case, "Interrupted" may be thrown.
866 wait: function wait(timeout, interruptable) {
868 return util.waitFor(function wf() !this.incomplete, this, timeout, interruptable);
872 number: function S_number(a, b) parseInt(a.text) - parseInt(b.text)
873 || String.localeCompare(a.text, b.text),
878 text: function F_text(item) {
879 let text = item.texts;
880 for (let [i, str] in Iterator(text)) {
881 if (this.match(String(str))) {
882 item.text = String(text[i]);
888 textDescription: function F_textDescription(item) {
889 return CompletionContext.Filter.text.call(this, item) || this.match(item.description);
895 * @instance completion
897 var Completion = Module("completion", {
898 init: function init() {
901 get setFunctionCompleter() JavaScript.setCompleter, // Backward compatibility
903 Local: function Local(dactyl, modules, window) ({
906 get modules() modules,
907 get options() modules.options,
910 _runCompleter: function _runCompleter(name, filter, maxItems) {
911 let context = modules.CompletionContext(filter);
912 context.maxItems = maxItems;
913 let res = context.fork.apply(context, ["run", 0, this, name].concat(Array.slice(arguments, 3)));
915 if (Components.stack.caller.name === "runCompleter") // FIXME
916 return { items: res.map(function m(i) ({ item: i })) };
917 context.contexts["/run"].completions = res;
919 context.wait(null, true);
920 return context.allItems;
923 runCompleter: function runCompleter(name, filter, maxItems) {
924 return this._runCompleter.apply(this, Array.slice(arguments))
925 .items.map(function m(i) i.item);
928 listCompleter: function listCompleter(name, filter, maxItems) {
929 let context = modules.CompletionContext(filter || "");
930 context.maxItems = maxItems;
931 context.fork.apply(context, ["list", 0, this, name].concat(Array.slice(arguments, 3)));
932 context = context.contexts["/list"];
933 context.wait(null, true);
935 let contexts = context.activeContexts;
936 if (!contexts.length)
937 contexts = context.contextList.filter(function f(c) c.hasItems).slice(0, 1);
938 if (!contexts.length)
939 contexts = context.contextList.slice(-1);
941 modules.commandline.commandOutput(
942 ["div", { highlight: "Completions" },
943 template.map(contexts, function m(context)
944 [template.completionRow(context.title, "CompTitle"),
945 template.map(context.items, function m(item) context.createRow(item), null, 100)])]);
949 ////////////////////////////////////////////////////////////////////////////////
950 ////////////////////// COMPLETION TYPES ////////////////////////////////////////
951 /////////////////////////////////////////////////////////////////////////////{{{
953 // filter a list of urls
955 // may consist of search engines, filenames, bookmarks and history,
956 // depending on the 'complete' option
957 // if the 'complete' argument is passed like "h", it temporarily overrides the complete option
958 url: function url(context, complete) {
959 if (/^jar:[^!]*$/.test(context.filter)) {
962 context.quote = context.quote || ["", util.identity, ""];
963 let quote = context.quote[1];
964 context.quote[1] = function quote_1(str) quote(str.replace(/!/g, escape));
967 if (this.options["urlseparator"])
968 var skip = util.regexp("^.*" + this.options["urlseparator"] + "\\s*")
969 .exec(context.filter);
972 context.advance(skip[0].length);
974 if (/^about:/.test(context.filter))
975 context.fork("about", 6, this, function fork_(context) {
976 context.title = ["about:"];
977 context.generate = function generate_() {
978 return [[k.substr(services.ABOUT.length), ""]
980 if (k.indexOf(services.ABOUT) == 0)];
984 if (complete == null)
985 complete = this.options["complete"];
987 // Will, and should, throw an error if !(c in opts)
988 Array.forEach(complete, function fe(c) {
989 let completer = this.urlCompleters[c] || { args: [], completer: this.autocomplete(c.replace(/^native:/, "")) };
990 context.forkapply(c, 0, this, completer.completer, completer.args);
994 addUrlCompleter: function addUrlCompleter(opt) {
995 let completer = Completion.UrlCompleter.apply(null, Array.slice(arguments));
996 completer.args = Array.slice(arguments, completer.length);
997 this.urlCompleters[opt] = completer;
1000 autocomplete: curry(function autocomplete(provider, context) {
1001 let running = context.getCache("autocomplete-search-running", Object);
1003 let name = "autocomplete:" + provider;
1004 if (!services.has(name))
1005 services.add(name, services.AUTOCOMPLETE + provider, "nsIAutoCompleteSearch");
1006 let service = services[name];
1008 util.assert(service, _("autocomplete.noSuchProvider", provider), false);
1010 if (running[provider]) {
1011 this.completions = this.completions;
1015 context.anchored = false;
1016 context.compare = CompletionContext.Sort.unsorted;
1017 context.filterFunc = null;
1019 let words = context.filter.toLowerCase().split(/\s+/g);
1020 context.hasItems = true;
1021 context.completions = context.completions.filter(function f({ url, title })
1022 words.every(function e(w) (url + " " + title).toLowerCase().indexOf(w) >= 0))
1024 context.format = this.modules.bookmarks.format;
1025 context.keys.extra = function k_extra(item) {
1027 return bookmarkcache.get(item.url).extra;
1032 context.title = [_("autocomplete.title", provider)];
1034 context.cancel = function cancel_() {
1035 this.incomplete = false;
1036 if (running[provider])
1037 service.stopSearch();
1038 running[provider] = false;
1041 if (!context.waitingForTab) {
1042 context.incomplete = true;
1044 service.startSearch(context.filter, "", context.result, {
1045 onSearchResult: util.wrapCallback(function onSearchResult(search, result) {
1046 if (result.searchResult <= result.RESULT_SUCCESS)
1047 running[provider] = null;
1049 context.incomplete = result.searchResult >= result.RESULT_NOMATCH_ONGOING;
1050 context.completions = [
1051 { url: result.getValueAt(i), title: result.getCommentAt(i), icon: result.getImageAt(i) }
1052 for (i in util.range(0, result.matchCount))
1055 get onUpdateSearchResult() this.onSearchResult
1057 running[provider] = true;
1061 urls: function urls(context, tags) {
1062 let compare = String.localeCompare;
1063 let contains = String.indexOf;
1064 if (context.ignoreCase) {
1065 compare = util.compareIgnoreCase;
1066 contains = function contains_(a, b) a && a.toLowerCase().indexOf(b.toLowerCase()) > -1;
1070 context.filters.push(function filter_(item) tags.
1071 every(function e(tag) (item.tags || []).
1072 some(function s(t) !compare(tag, t))));
1074 context.anchored = false;
1076 context.title = ["URL", "Title"];
1078 context.fork("additional", 0, this, function fork_(context) {
1079 context.title[0] += " " + _("completion.additional");
1080 context.filter = context.parent.filter; // FIXME
1081 context.completions = context.parent.completions;
1083 // For items whose URL doesn't exactly match the filter,
1084 // accept them if all tokens match either the URL or the title.
1085 // Filter out all directly matching strings.
1086 let match = context.filters[0];
1087 context.filters[0] = function filters_0(item) !match.call(this, item);
1089 // and all that don't match the tokens.
1090 let tokens = context.filter.split(/\s+/);
1091 context.filters.push(function filter_(item) tokens.every(
1092 function e(tok) contains(item.url, tok) ||
1093 contains(item.title, tok)));
1095 let re = RegExp(tokens.filter(util.identity).map(util.regexp.escape).join("|"), "g");
1096 function highlight(item, text, i) process[i].call(this, item, template.highlightRegexp(text, re));
1097 let process = context.process;
1099 function process_0(item, text) highlight.call(this, item, item.text, 0),
1100 function process_1(item, text) highlight.call(this, item, text, 1)
1106 UrlCompleter: Struct("name", "description", "completer")
1108 init: function init(dactyl, modules, window) {
1109 init.superapply(this, arguments);
1111 modules.CompletionContext = Class("CompletionContext", CompletionContext, {
1112 init: function init() {
1113 this.modules = modules;
1114 return init.superapply(this, arguments);
1117 get options() this.modules.options
1120 commands: function initCommands(dactyl, modules, window) {
1121 const { commands, completion } = modules;
1122 commands.add(["contexts"],
1123 "List the completion contexts used during completion of an Ex command",
1125 modules.commandline.commandOutput(
1126 ["div", { highlight: "Completions" },
1127 template.completionRow(["Context", "Title"], "CompTitle"),
1128 template.map(completion.contextList || [],
1129 function m(item) template.completionRow(item, "CompItem"))]);
1133 completer: function (context) {
1134 let PREFIX = "/ex/contexts";
1135 context.fork("ex", 0, completion, "ex");
1136 completion.contextList = [[k.substr(PREFIX.length), v.title[0]] for ([k, v] in iter(context.contexts)) if (k.substr(0, PREFIX.length) == PREFIX)];
1141 options: function initOptions(dactyl, modules, window) {
1142 const { completion, options } = modules;
1145 // Why do we need ""?
1146 // Because its description is useful during completion. --Kris
1147 "": "Complete only the first match",
1148 "full": "Complete the next full match",
1149 "longest": "Complete the longest common string",
1150 "list": "If more than one match, list all matches",
1151 "list:full": "List all and complete first match",
1152 "list:longest": "List all and complete the longest common string"
1154 checkHas: function (value, val) {
1155 let [first, second] = value.split(":", 2);
1156 return first == val || second == val;
1159 let test = function test(val) this.value.some(function s(value) this.checkHas(value, val), this);
1160 return Array.some(arguments, test, this);
1164 options.add(["altwildmode", "awim"],
1165 "Define the behavior of the c_<A-Tab> key in command-line completion",
1166 "stringlist", "list:full",
1169 options.add(["autocomplete", "au"],
1170 "Automatically update the completion list on any key press",
1171 "regexplist", ".*");
1173 options.add(["complete", "cpt"],
1174 "Items which are completed at the :open prompts",
1175 "stringlist", "slf",
1186 get values() values(completion.urlCompleters).toArray()
1187 .concat([let (name = k.substr(services.AUTOCOMPLETE.length))
1188 ["native:" + name, _("autocomplete.description", name)]
1190 if (k.indexOf(services.AUTOCOMPLETE) == 0)]),
1192 setter: function setter(values) {
1193 if (values.length == 1 && !Set.has(values[0], this.values)
1194 && Array.every(values[0], Set.has(this.valueMap)))
1195 return Array.map(values[0], function m(v) this[v], this.valueMap);
1199 validator: function validator(values) validator.supercall(this, this.setter(values))
1202 options.add(["wildanchor", "wia"],
1203 "Define which completion groups only match at the beginning of their text",
1204 "regexplist", "!/ex/(back|buffer|ext|forward|help|undo)");
1206 options.add(["wildcase", "wic"],
1207 "Completion case matching mode",
1208 "regexpmap", ".?:smart",
1211 "smart": "Case is significant when capital letters are typed",
1212 "match": "Case is always significant",
1213 "ignore": "Case is never significant"
1217 options.add(["wildmode", "wim"],
1218 "Define the behavior of the c_<Tab> key in command-line completion",
1219 "stringlist", "list:full",
1222 options.add(["wildsort", "wis"],
1223 "Define which completion groups are sorted",
1224 "regexplist", ".*");
1230 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
1232 // vim: set fdm=marker sw=4 ts=4 et ft=javascript: