]> git.donarmstrong.com Git - dactyl.git/blob - common/content/bookmarks.js
d92c62476e5939647b790017da70e96cb907e457
[dactyl.git] / common / content / bookmarks.js
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 // also includes methods for dealing with keywords and search engines
10 var Bookmarks = Module("bookmarks", {
11     init: function () {
12         this.timer = Timer(0, 100, function () {
13             this.checkBookmarked(buffer.uri);
14         }, this);
15
16         storage.addObserver("bookmark-cache", function (key, event, arg) {
17             if (["add", "change", "remove"].indexOf(event) >= 0)
18                 autocommands.trigger("Bookmark" + util.capitalize(event),
19                      iter({
20                          bookmark: {
21                              toString: function () "bookmarkcache.bookmarks[" + arg.id + "]",
22                              valueOf: function () arg
23                          }
24                      }, arg).toObject());
25             bookmarks.timer.tell();
26         }, window);
27     },
28
29     signals: {
30         "browser.locationChange": function (webProgress, request, uri) {
31             statusline.bookmarked = false;
32             this.checkBookmarked(uri);
33         }
34     },
35
36     get format() ({
37         anchored: false,
38         title: ["URL", "Info"],
39         keys: { text: "url", description: "title", icon: "icon", extra: "extra", tags: "tags", isURI: function () true },
40         process: [template.icon, template.bookmarkDescription]
41     }),
42
43     // TODO: why is this a filter? --djk
44     get: function get(filter, tags, maxItems, extra) {
45         return completion.runCompleter("bookmark", filter, maxItems, tags, extra);
46     },
47
48     /**
49      * Adds a new bookmark. The first parameter should be an object with
50      * any of the following properties:
51      *
52      * @param {boolean} unfiled If true, the bookmark is added to the
53      *      Unfiled Bookmarks Folder.
54      * @param {string} title The title of the new bookmark.
55      * @param {string} url The URL of the new bookmark.
56      * @param {string} keyword The keyword of the new bookmark.
57      *      @optional
58      * @param {[string]} tags The tags for the new bookmark.
59      *      @optional
60      * @param {boolean} force If true, a new bookmark is always added.
61      *      Otherwise, if a bookmark for the given URL exists it is
62      *      updated instead.
63      *      @optional
64      * @returns {boolean} True if the bookmark was updated, false if a
65      *      new bookmark was added.
66      */
67     add: function add(unfiled, title, url, keyword, tags, force) {
68         // FIXME
69         if (isObject(unfiled))
70             var { id, unfiled, title, url, keyword, tags, post, charset, force } = unfiled;
71
72         let uri = util.createURI(url);
73         if (id != null)
74             var bmark = bookmarkcache.bookmarks[id];
75         else if (!force) {
76             if (keyword && Set.has(bookmarkcache.keywords, keyword))
77                 bmark = bookmarkcache.keywords[keyword];
78             else if (bookmarkcache.isBookmarked(uri))
79                 for (bmark in bookmarkcache)
80                     if (bmark.url == uri.spec)
81                         break;
82         }
83
84         if (tags) {
85             PlacesUtils.tagging.untagURI(uri, null);
86             PlacesUtils.tagging.tagURI(uri, tags);
87         }
88
89         let updated = !!bmark;
90         if (bmark == undefined)
91             bmark = bookmarkcache.bookmarks[
92                 services.bookmarks.insertBookmark(
93                      services.bookmarks[unfiled ? "unfiledBookmarksFolder" : "bookmarksMenuFolder"],
94                      uri, -1, title || url)];
95         else {
96             if (title)
97                 bmark.title = title;
98             if (!uri.equals(bmark.uri))
99                 bmark.uri = uri;
100         }
101
102         util.assert(bmark);
103
104         if (charset !== undefined)
105             bmark.charset = charset;
106         if (post !== undefined)
107             bmark.post = post;
108         if (keyword)
109             bmark.keyword = keyword;
110
111         return updated;
112     },
113
114     /**
115      * Opens the command line in Ex mode pre-filled with a :bmark
116      * command to add a new search keyword for the given form element.
117      *
118      * @param {Element} elem A form element for which to add a keyword.
119      */
120     addSearchKeyword: function addSearchKeyword(elem) {
121         if (elem instanceof Ci.nsIDOMHTMLFormElement || elem.form)
122             var { url, postData, charset } = DOM(elem).formData;
123         else
124             var [url, postData, charset] = [elem.href || elem.src, null, elem.ownerDocument.characterSet];
125
126         let options = { "-title": "Search " + elem.ownerDocument.title };
127         if (postData != null)
128             options["-post"] = postData;
129         if (charset != null && charset !== "UTF-8")
130             options["-charset"] = charset;
131
132         CommandExMode().open(
133             commands.commandToString({ command: "bmark", options: options, arguments: [url] }) + " -keyword ");
134     },
135
136     checkBookmarked: function checkBookmarked(uri) {
137         if (PlacesUtils.asyncGetBookmarkIds)
138             PlacesUtils.asyncGetBookmarkIds(uri, function withBookmarkIDs(ids) {
139                 statusline.bookmarked = ids.length;
140             });
141         else
142             this.timeout(function () {
143                 statusline.bookmarked = bookmarkcache.isBookmarked(uri);
144             });
145     },
146
147     /**
148      * Toggles the bookmarked state of the given URL. If the URL is
149      * bookmarked, all bookmarks for said URL are removed.
150      * If it is not, a new bookmark is added to the Unfiled Bookmarks
151      * Folder. The new bookmark has the title of the current buffer if
152      * its URL is identical to *url*, otherwise its title will be the
153      * value of *url*.
154      *
155      * @param {string} url The URL of the bookmark to toggle.
156      */
157     toggle: function toggle(url) {
158         if (!url)
159             return;
160
161         let count = this.remove(url);
162         if (count > 0)
163             dactyl.echomsg({ domains: [util.getHost(url)], message: _("bookmark.removed", url) });
164         else {
165             let title = buffer.uri.spec == url && buffer.title || url;
166             let extra = "";
167             if (title != url)
168                 extra = " (" + title + ")";
169
170             this.add({ unfiled: true, title: title, url: url });
171             dactyl.echomsg({ domains: [util.getHost(url)], message: _("bookmark.added", url + extra) });
172         }
173     },
174
175     isBookmarked: deprecated("bookmarkcache.isBookmarked", { get: function isBookmarked() bookmarkcache.closure.isBookmarked }),
176
177     /**
178      * Remove a bookmark or bookmarks. If *ids* is an array, removes the
179      * bookmarks with those IDs. If it is a string, removes all
180      * bookmarks whose URLs match that string.
181      *
182      * @param {string|[number]} ids The IDs or URL of the bookmarks to
183      *      remove.
184      * @returns {number} The number of bookmarks removed.
185      */
186     remove: function remove(ids) {
187         try {
188             if (!isArray(ids)) {
189                 let uri = util.newURI(ids);
190                 ids = services.bookmarks
191                               .getBookmarkIdsForURI(uri, {})
192                               .filter(bookmarkcache.closure.isRegularBookmark);
193             }
194             ids.forEach(function (id) {
195                 let bmark = bookmarkcache.bookmarks[id];
196                 if (bmark) {
197                     PlacesUtils.tagging.untagURI(bmark.uri, null);
198                     bmark.charset = null;
199                 }
200                 services.bookmarks.removeItem(id);
201             });
202             return ids.length;
203         }
204         catch (e) {
205             dactyl.reportError(e, true);
206             return 0;
207         }
208     },
209
210     getSearchEngines: deprecated("bookmarks.searchEngines", function getSearchEngines() this.searchEngines),
211     /**
212      * Returns a list of all visible search engines in the search
213      * services, augmented with keyword, title, and icon properties for
214      * use in completion functions.
215      */
216     get searchEngines() {
217         let searchEngines = [];
218         let aliases = {};
219         return iter(services.browserSearch.getVisibleEngines({})).map(function ([, engine]) {
220             let alias = engine.alias;
221             if (!alias || !/^[a-z0-9-]+$/.test(alias))
222                 alias = engine.name.replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/, "").toLowerCase();
223             if (!alias)
224                 alias = "search"; // for search engines which we can't find a suitable alias
225
226             if (Set.has(aliases, alias))
227                 alias += ++aliases[alias];
228             else
229                 aliases[alias] = 0;
230
231             return [alias, { keyword: alias, __proto__: engine, title: engine.description, icon: engine.iconURI && engine.iconURI.spec }];
232         }).toObject();
233     },
234
235     /**
236      * Retrieves a list of search suggestions from the named search
237      * engine based on the given *query*. The results are always in the
238      * form of an array of strings. If *callback* is provided, the
239      * request is executed asynchronously and *callback* is called on
240      * completion. Otherwise, the request is executed synchronously and
241      * the results are returned.
242      *
243      * @param {string} engineName The name of the search engine from
244      *      which to request suggestions.
245      * @param {string} query The query string for which to request
246      *      suggestions.
247      * @param {function([string])} callback The function to call when
248      *      results are returned.
249      * @returns {[string] | null}
250      */
251     getSuggestions: function getSuggestions(engineName, query, callback) {
252         const responseType = "application/x-suggestions+json";
253
254         if (Set.has(this.suggestionProviders, engineName))
255             return this.suggestionProviders[engineName](query, callback);
256
257         let engine = Set.has(this.searchEngines, engineName) && this.searchEngines[engineName];
258         if (engine && engine.supportsResponseType(responseType))
259             var queryURI = engine.getSubmission(query, responseType).uri.spec;
260         if (!queryURI)
261             return (callback || util.identity)([]);
262
263         function parse(req) JSON.parse(req.responseText)[1].filter(isString);
264         return this.makeSuggestions(queryURI, parse, callback);
265     },
266
267     /**
268      * Given a query URL, response parser, and optionally a callback,
269      * fetch and parse search query results for {@link getSuggestions}.
270      *
271      * @param {string} url The URL to fetch.
272      * @param {function(XMLHttpRequest):[string]} parser The function which
273      *      parses the response.
274      */
275     makeSuggestions: function makeSuggestions(url, parser, callback) {
276         function process(req) {
277             let results = [];
278             try {
279                 results = parser(req);
280             }
281             catch (e) {
282                 util.reportError(e);
283             }
284             if (callback)
285                 return callback(results);
286             return results;
287         }
288
289         let req = util.httpGet(url, callback && process);
290         if (callback)
291             return req;
292         return process(req);
293     },
294
295     suggestionProviders: {},
296
297     /**
298      * Returns an array containing a search URL and POST data for the
299      * given search string. If *useDefsearch* is true, the string is
300      * always passed to the default search engine. If it is not, the
301      * search engine name is retrieved from the first space-separated
302      * token of the given string.
303      *
304      * Returns null if no search engine is found for the passed string.
305      *
306      * @param {string} text The text for which to retrieve a search URL.
307      * @param {boolean} useDefsearch Whether to use the default search
308      *      engine.
309      * @returns {[string, string | null] | null}
310      */
311     getSearchURL: function getSearchURL(text, useDefsearch) {
312         let query = (useDefsearch ? options["defsearch"] + " " : "") + text;
313
314         // ripped from Firefox
315         var keyword = query;
316         var param = "";
317         var offset = query.indexOf(" ");
318         if (offset > 0) {
319             keyword = query.substr(0, offset);
320             param = query.substr(offset + 1);
321         }
322
323         var engine = Set.has(bookmarks.searchEngines, keyword) && bookmarks.searchEngines[keyword];
324         if (engine) {
325             if (engine.searchForm && !param)
326                 return engine.searchForm;
327             let submission = engine.getSubmission(param, null);
328             return [submission.uri.spec, submission.postData];
329         }
330
331         let [url, postData] = PlacesUtils.getURLAndPostDataForKeyword(keyword);
332         if (!url)
333             return null;
334
335         let data = window.unescape(postData || "");
336         if (/%s/i.test(url) || /%s/i.test(data)) {
337             var charset = "";
338             var matches = url.match(/^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/);
339             if (matches)
340                 [, url, charset] = matches;
341             else
342                 try {
343                     charset = services.history.getCharsetForURI(util.newURI(url));
344                 }
345                 catch (e) {}
346
347             if (charset)
348                 var encodedParam = escape(window.convertFromUnicode(charset, param)).replace(/\+/g, encodeURIComponent);
349             else
350                 encodedParam = bookmarkcache.keywords[keyword.toLowerCase()].encodeURIComponent(param);
351
352             url = url.replace(/%s/g, function () encodedParam)
353                      .replace(/%S/g, function () param);
354             if (/%s/i.test(data))
355                 postData = window.getPostDataStream(data, param, encodedParam, "application/x-www-form-urlencoded");
356         }
357         else if (param)
358             postData = null;
359
360         if (postData)
361             return [url, postData];
362         return url;
363     },
364
365     /**
366      * Lists all bookmarks whose URLs match *filter*, tags match *tags*,
367      * and other properties match the properties of *extra*. If
368      * *openItems* is true, the items are opened in tabs rather than
369      * listed.
370      *
371      * @param {string} filter A URL filter string which the URLs of all
372      *      matched items must contain.
373      * @param {[string]} tags An array of tags each of which all matched
374      *      items must contain.
375      * @param {boolean} openItems If true, items are opened rather than
376      *      listed.
377      * @param {object} extra Extra properties which must be matched.
378      */
379     list: function list(filter, tags, openItems, maxItems, extra) {
380         // FIXME: returning here doesn't make sense
381         //   Why the hell doesn't it make sense? --Kris
382         // Because it unconditionally bypasses the final error message
383         // block and does so only when listing items, not opening them. In
384         // short it breaks the :bmarks command which doesn't make much
385         // sense to me but I'm old-fashioned. --djk
386         if (!openItems)
387             return completion.listCompleter("bookmark", filter, maxItems, tags, extra);
388         let items = completion.runCompleter("bookmark", filter, maxItems, tags, extra);
389
390         if (items.length)
391             return dactyl.open(items.map(function (i) i.url), dactyl.NEW_TAB);
392
393         if (filter.length > 0 && tags.length > 0)
394             dactyl.echoerr(_("bookmark.noMatching", tags.map(String.quote), filter.quote()));
395         else if (filter.length > 0)
396             dactyl.echoerr(_("bookmark.noMatchingString", filter.quote()));
397         else if (tags.length > 0)
398             dactyl.echoerr(_("bookmark.noMatchingTags", tags.map(String.quote)));
399         else
400             dactyl.echoerr(_("bookmark.none"));
401         return null;
402     }
403 }, {
404 }, {
405     commands: function initCommands() {
406         // TODO: Clean this up.
407         const tags = {
408             names: ["-tags", "-T"],
409             description: "A comma-separated list of tags",
410             completer: function tags(context, args) {
411                 context.generate = function () array(b.tags for (b in bookmarkcache) if (b.tags)).flatten().uniq().array;
412                 context.keys = { text: util.identity, description: util.identity };
413             },
414             type: CommandOption.LIST
415         };
416
417         const title = {
418             names: ["-title", "-t"],
419             description: "Bookmark page title or description",
420             completer: function title(context, args) {
421                 let frames = buffer.allFrames();
422                 if (!args.bang)
423                     return [
424                         [win.document.title, frames.length == 1 ? /*L*/"Current Location" : /*L*/"Frame: " + win.location.href]
425                         for ([, win] in Iterator(frames))];
426                 context.keys.text = "title";
427                 context.keys.description = "url";
428                 return bookmarks.get(args.join(" "), args["-tags"], null, { keyword: args["-keyword"], title: context.filter });
429             },
430             type: CommandOption.STRING
431         };
432
433         const post = {
434             names: ["-post", "-p"],
435             description: "Bookmark POST data",
436             completer: function post(context, args) {
437                 context.keys.text = "post";
438                 context.keys.description = "url";
439                 return bookmarks.get(args.join(" "), args["-tags"], null, { keyword: args["-keyword"], post: context.filter });
440             },
441             type: CommandOption.STRING
442         };
443
444         const keyword = {
445             names: ["-keyword", "-k"],
446             description: "Keyword by which this bookmark may be opened (:open {keyword})",
447             completer: function keyword(context, args) {
448                 context.keys.text = "keyword";
449                 return bookmarks.get(args.join(" "), args["-tags"], null, { keyword: context.filter, title: args["-title"] });
450             },
451             type: CommandOption.STRING,
452             validator: bind("test", /^\S+$/)
453         };
454
455         commands.add(["bma[rk]"],
456             "Add a bookmark",
457             function (args) {
458                 dactyl.assert(!args.bang || args["-id"] == null,
459                               _("bookmark.bangOrID"));
460
461                 let opts = {
462                     force: args.bang,
463                     unfiled: false,
464                     id: args["-id"],
465                     keyword: args["-keyword"] || null,
466                     charset: args["-charset"],
467                     post: args["-post"],
468                     tags: args["-tags"] || [],
469                     title: args["-title"] || (args.length === 0 ? buffer.title : null),
470                     url: args.length === 0 ? buffer.uri.spec : args[0]
471                 };
472
473                 let updated = bookmarks.add(opts);
474                 let action  = updated ? "updated" : "added";
475
476                 let extra   = (opts.title && opts.title != opts.url) ? " (" + opts.title + ")" : "";
477
478                 dactyl.echomsg({ domains: [util.getHost(opts.url)], message: _("bookmark." + action, opts.url + extra) },
479                                1, commandline.FORCE_SINGLELINE);
480             }, {
481                 argCount: "?",
482                 bang: true,
483                 completer: function (context, args) {
484                     if (!args.bang) {
485                         context.title = ["Page URL"];
486                         let frames = buffer.allFrames();
487                         context.completions = [
488                             [win.document.documentURI, frames.length == 1 ? /*L*/"Current Location" : /*L*/"Frame: " + win.document.title]
489                             for ([, win] in Iterator(frames))];
490                         return;
491                     }
492                     completion.bookmark(context, args["-tags"], { keyword: args["-keyword"], title: args["-title"] });
493                 },
494                 options: [keyword, title, tags, post,
495                     {
496                         names: ["-charset", "-c"],
497                         description: "The character encoding of the bookmark",
498                         type: CommandOption.STRING,
499                         completer: function (context) completion.charset(context),
500                         validator: Option.validateCompleter
501                     },
502                     {
503                         names: ["-id"],
504                         description: "The ID of the bookmark to update",
505                         type: CommandOption.INT
506                     }
507                 ]
508             });
509
510         commands.add(["bmarks"],
511             "List or open multiple bookmarks",
512             function (args) {
513                 bookmarks.list(args.join(" "), args["-tags"] || [], args.bang, args["-max"],
514                                { keyword: args["-keyword"], title: args["-title"] });
515             },
516             {
517                 bang: true,
518                 completer: function completer(context, args) {
519                     context.filter = args.join(" ");
520                     completion.bookmark(context, args["-tags"], { keyword: args["-keyword"], title: args["-title"] });
521                 },
522                 options: [tags, keyword, title,
523                     {
524                         names: ["-max", "-m"],
525                         description: "The maximum number of items to list or open",
526                         type: CommandOption.INT
527                     }
528                 ]
529                 // Not privateData, since we don't treat bookmarks as private
530             });
531
532         commands.add(["delbm[arks]"],
533             "Delete a bookmark",
534             function (args) {
535                 if (args.bang)
536                     commandline.input(_("bookmark.prompt.deleteAll") + " ",
537                         function (resp) {
538                             if (resp && resp.match(/^y(es)?$/i)) {
539                                 bookmarks.remove(Object.keys(bookmarkcache.bookmarks));
540                                 dactyl.echomsg(_("bookmark.allDeleted"));
541                             }
542                         });
543                 else {
544                     if (!(args.length || args["-tags"] || args["-keyword"] || args["-title"]))
545                         var deletedCount = bookmarks.remove(buffer.uri.spec);
546                     else {
547                         let context = CompletionContext(args.join(" "));
548                         context.fork("bookmark", 0, completion, "bookmark",
549                                      args["-tags"], { keyword: args["-keyword"], title: args["-title"] });
550                         deletedCount = bookmarks.remove(context.allItems.items.map(function (item) item.item.id));
551                     }
552
553                     dactyl.echomsg({ message: _("bookmark.deleted", deletedCount) });
554                 }
555
556             },
557             {
558                 argCount: "?",
559                 bang: true,
560                 completer: function completer(context, args)
561                     completion.bookmark(context, args["-tags"], { keyword: args["-keyword"], title: args["-title"] }),
562                 domains: function (args) array.compact(args.map(util.getHost)),
563                 literal: 0,
564                 options: [tags, title, keyword],
565                 privateData: true
566             });
567     },
568     mappings: function initMappings() {
569         var myModes = config.browserModes;
570
571         mappings.add(myModes, ["a"],
572             "Open a prompt to bookmark the current URL",
573             function () {
574                 let options = {};
575
576                 let url = buffer.uri.spec;
577                 let bmarks = bookmarks.get(url).filter(function (bmark) bmark.url == url);
578
579                 if (bmarks.length == 1) {
580                     let bmark = bmarks[0];
581
582                     options["-id"] = bmark.id;
583                     options["-title"] = bmark.title;
584                     if (bmark.charset)
585                         options["-charset"] = bmark.charset;
586                     if (bmark.keyword)
587                         options["-keyword"] = bmark.keyword;
588                     if (bmark.post)
589                         options["-post"] = bmark.post;
590                     if (bmark.tags.length > 0)
591                         options["-tags"] = bmark.tags;
592                 }
593                 else {
594                     if (buffer.title != buffer.uri.spec)
595                         options["-title"] = buffer.title;
596                     if (content.document.characterSet !== "UTF-8")
597                         options["-charset"] = content.document.characterSet;
598                 }
599
600                 CommandExMode().open(
601                     commands.commandToString({ command: "bmark", options: options, arguments: [buffer.uri.spec] }));
602             });
603
604         mappings.add(myModes, ["A"],
605             "Toggle bookmarked state of current URL",
606             function () { bookmarks.toggle(buffer.uri.spec); });
607     },
608     options: function initOptions() {
609         options.add(["defsearch", "ds"],
610             "The default search engine",
611             "string", "google",
612             {
613                 completer: function completer(context) {
614                     completion.search(context, true);
615                     context.completions = [{ keyword: "", title: "Don't perform searches by default" }].concat(context.completions);
616                 }
617             });
618
619         options.add(["suggestengines"],
620              "Search engines used for search suggestions",
621              "stringlist", "google",
622              { completer: function completer(context) completion.searchEngine(context, true), });
623     },
624
625     completion: function initCompletion() {
626         completion.bookmark = function bookmark(context, tags, extra) {
627             context.title = ["Bookmark", "Title"];
628             context.format = bookmarks.format;
629             iter(extra || {}).forEach(function ([k, v]) {
630                 if (v != null)
631                     context.filters.push(function (item) item.item[k] != null && this.matchString(v, item.item[k]));
632             });
633             context.generate = function () values(bookmarkcache.bookmarks);
634             completion.urls(context, tags);
635         };
636
637         completion.search = function search(context, noSuggest) {
638             let [, keyword, space, args] = context.filter.match(/^\s*(\S*)(\s*)(.*)$/);
639             let keywords = bookmarkcache.keywords;
640             let engines = bookmarks.searchEngines;
641
642             context.title = ["Search Keywords"];
643             context.completions = iter(values(keywords), values(engines));
644             context.keys = { text: "keyword", description: "title", icon: "icon" };
645
646             if (!space || noSuggest)
647                 return;
648
649             context.fork("suggest", keyword.length + space.length, this, "searchEngineSuggest",
650                          keyword, true);
651
652             let item = keywords[keyword];
653             if (item && item.url.indexOf("%s") > -1)
654                 context.fork("keyword/" + keyword, keyword.length + space.length, null, function (context) {
655                     context.format = history.format;
656                     context.title = [/*L*/keyword + " Quick Search"];
657                     context.keys = { text: "url", description: "title", icon: "icon" };
658                     // context.background = true;
659                     context.compare = CompletionContext.Sort.unsorted;
660                     context.generate = function () {
661                         let [begin, end] = item.url.split("%s");
662
663                         return history.get({ uri: util.newURI(begin), uriIsPrefix: true }).map(function (item) {
664                             let rest = item.url.length - end.length;
665                             let query = item.url.substring(begin.length, rest);
666                             if (item.url.substr(rest) == end && query.indexOf("&") == -1)
667                                 try {
668                                     item.url = decodeURIComponent(query.replace(/#.*/, "").replace(/\+/g, " "));
669                                     return item;
670                                 }
671                                 catch (e) {}
672                             return null;
673                         }).filter(util.identity);
674                     };
675                 });
676         };
677
678         completion.searchEngine = function searchEngine(context, suggest) {
679              context.title = ["Suggest Engine", "Description"];
680              context.keys = { text: "keyword", description: "title", icon: "icon" };
681              context.completions = values(bookmarks.searchEngines);
682              if (suggest)
683                  context.filters.push(function ({ item }) item.supportsResponseType("application/x-suggestions+json"));
684
685         };
686
687         completion.searchEngineSuggest = function searchEngineSuggest(context, engineAliases, kludge) {
688             if (!context.filter)
689                 return;
690
691             let engineList = (engineAliases || options["suggestengines"].join(",") || "google").split(",");
692
693             engineList.forEach(function (name) {
694                 var desc = name;
695                 let engine = bookmarks.searchEngines[name];
696                 if (engine)
697                     var desc = engine.description;
698                 else if (!Set.has(bookmarks.suggestionProviders, name))
699                     return;
700
701                 let [, word] = /^\s*(\S+)/.exec(context.filter) || [];
702                 if (!kludge && word == name) // FIXME: Check for matching keywords
703                     return;
704                 let ctxt = context.fork(name, 0);
705
706                 ctxt.title = [/*L*/desc + " Suggestions"];
707                 ctxt.keys = { text: util.identity, description: function () "" };
708                 ctxt.compare = CompletionContext.Sort.unsorted;
709                 ctxt.filterFunc = null;
710
711                 if (ctxt.waitingForTab)
712                     return;
713
714                 let words = ctxt.filter.toLowerCase().split(/\s+/g);
715                 ctxt.completions = ctxt.completions.filter(function (i) words.every(function (w) i.toLowerCase().indexOf(w) >= 0));
716
717                 ctxt.hasItems = ctxt.completions.length;
718                 ctxt.incomplete = true;
719                 ctxt.cache.request = bookmarks.getSuggestions(name, ctxt.filter, function (compl) {
720                     ctxt.incomplete = false;
721                     ctxt.completions = array.uniq(ctxt.completions.filter(function (c) compl.indexOf(c) >= 0)
722                                                       .concat(compl), true);
723                 });
724             });
725         };
726
727         completion.addUrlCompleter("suggestion", "Search engine suggestions", completion.searchEngineSuggest);
728         completion.addUrlCompleter("bookmark", "Bookmarks", completion.bookmark);
729         completion.addUrlCompleter("search", "Search engines and keyword URLs", completion.search);
730     }
731 });
732
733 // vim: set fdm=marker sw=4 sts=4 ts=8 et: