]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/js/search.js
Added docs to internal_macro const
[rust.git] / src / librustdoc / html / static / js / search.js
1 /* global addClass, getNakedUrl, getSettingValue, hasOwnPropertyRustdoc, initSearch, onEach */
2 /* global onEachLazy, removeClass, searchState, updateLocalStorage */
3
4 (function() {
5 // This mapping table should match the discriminants of
6 // `rustdoc::html::item_type::ItemType` type in Rust.
7 var itemTypes = ["mod",
8                     "externcrate",
9                     "import",
10                     "struct",
11                     "enum",
12                     "fn",
13                     "type",
14                     "static",
15                     "trait",
16                     "impl",
17                     "tymethod",
18                     "method",
19                     "structfield",
20                     "variant",
21                     "macro",
22                     "primitive",
23                     "associatedtype",
24                     "constant",
25                     "associatedconstant",
26                     "union",
27                     "foreigntype",
28                     "keyword",
29                     "existential",
30                     "attr",
31                     "derive",
32                     "traitalias"];
33
34 // used for special search precedence
35 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
36 var TY_KEYWORD = itemTypes.indexOf("keyword");
37
38 // In the search display, allows to switch between tabs.
39 function printTab(nb) {
40     if (nb === 0 || nb === 1 || nb === 2) {
41         searchState.currentTab = nb;
42     }
43     var nb_copy = nb;
44     onEachLazy(document.getElementById("titles").childNodes, function(elem) {
45         if (nb_copy === 0) {
46             addClass(elem, "selected");
47         } else {
48             removeClass(elem, "selected");
49         }
50         nb_copy -= 1;
51     });
52     onEachLazy(document.getElementById("results").childNodes, function(elem) {
53         if (nb === 0) {
54             addClass(elem, "active");
55         } else {
56             removeClass(elem, "active");
57         }
58         nb -= 1;
59     });
60 }
61
62 function removeEmptyStringsFromArray(x) {
63     for (var i = 0, len = x.length; i < len; ++i) {
64         if (x[i] === "") {
65             x.splice(i, 1);
66             i -= 1;
67         }
68     }
69 }
70
71 /**
72  * A function to compute the Levenshtein distance between two strings
73  * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
74  * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
75  * This code is an unmodified version of the code written by Marco de Wit
76  * and was found at https://stackoverflow.com/a/18514751/745719
77  */
78 var levenshtein_row2 = [];
79 function levenshtein(s1, s2) {
80     if (s1 === s2) {
81         return 0;
82     }
83     var s1_len = s1.length, s2_len = s2.length;
84     if (s1_len && s2_len) {
85         var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
86         while (i1 < s1_len) {
87             row[i1] = ++i1;
88         }
89         while (i2 < s2_len) {
90             c2 = s2.charCodeAt(i2);
91             a = i2;
92             ++i2;
93             b = i2;
94             for (i1 = 0; i1 < s1_len; ++i1) {
95                 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
96                 a = row[i1];
97                 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
98                 row[i1] = b;
99             }
100         }
101         return b;
102     }
103     return s1_len + s2_len;
104 }
105
106 window.initSearch = function(rawSearchIndex) {
107     var MAX_LEV_DISTANCE = 3;
108     var MAX_RESULTS = 200;
109     var GENERICS_DATA = 2;
110     var NAME = 0;
111     var INPUTS_DATA = 0;
112     var OUTPUT_DATA = 1;
113     var NO_TYPE_FILTER = -1;
114     var currentResults, index, searchIndex;
115     var ALIASES = {};
116     var params = searchState.getQueryStringParams();
117
118     // Populate search bar with query string search term when provided,
119     // but only if the input bar is empty. This avoid the obnoxious issue
120     // where you start trying to do a search, and the index loads, and
121     // suddenly your search is gone!
122     if (searchState.input.value === "") {
123         searchState.input.value = params.search || "";
124     }
125
126     /**
127      * Executes the query and builds an index of results
128      * @param  {[Object]} query      [The user query]
129      * @param  {[type]} searchWords  [The list of search words to query
130      *                                against]
131      * @param  {[type]} filterCrates [Crate to search in if defined]
132      * @return {[type]}              [A search index of results]
133      */
134     function execQuery(query, searchWords, filterCrates) {
135         function itemTypeFromName(typename) {
136             for (var i = 0, len = itemTypes.length; i < len; ++i) {
137                 if (itemTypes[i] === typename) {
138                     return i;
139                 }
140             }
141             return NO_TYPE_FILTER;
142         }
143
144         var valLower = query.query.toLowerCase(),
145             val = valLower,
146             typeFilter = itemTypeFromName(query.type),
147             results = {}, results_in_args = {}, results_returned = {},
148             split = valLower.split("::");
149
150         removeEmptyStringsFromArray(split);
151
152         function transformResults(results) {
153             var out = [];
154             for (var i = 0, len = results.length; i < len; ++i) {
155                 if (results[i].id > -1) {
156                     var obj = searchIndex[results[i].id];
157                     obj.lev = results[i].lev;
158                     var res = buildHrefAndPath(obj);
159                     obj.displayPath = pathSplitter(res[0]);
160                     obj.fullPath = obj.displayPath + obj.name;
161                     // To be sure than it some items aren't considered as duplicate.
162                     obj.fullPath += "|" + obj.ty;
163                     obj.href = res[1];
164                     out.push(obj);
165                     if (out.length >= MAX_RESULTS) {
166                         break;
167                     }
168                 }
169             }
170             return out;
171         }
172
173         function sortResults(results, isType) {
174             var ar = [];
175             for (var entry in results) {
176                 if (hasOwnPropertyRustdoc(results, entry)) {
177                     ar.push(results[entry]);
178                 }
179             }
180             results = ar;
181             var i, len, result;
182             for (i = 0, len = results.length; i < len; ++i) {
183                 result = results[i];
184                 result.word = searchWords[result.id];
185                 result.item = searchIndex[result.id] || {};
186             }
187             // if there are no results then return to default and fail
188             if (results.length === 0) {
189                 return [];
190             }
191
192             results.sort(function(aaa, bbb) {
193                 var a, b;
194
195                 // sort by exact match with regard to the last word (mismatch goes later)
196                 a = (aaa.word !== val);
197                 b = (bbb.word !== val);
198                 if (a !== b) { return a - b; }
199
200                 // Sort by non levenshtein results and then levenshtein results by the distance
201                 // (less changes required to match means higher rankings)
202                 a = (aaa.lev);
203                 b = (bbb.lev);
204                 if (a !== b) { return a - b; }
205
206                 // sort by crate (non-current crate goes later)
207                 a = (aaa.item.crate !== window.currentCrate);
208                 b = (bbb.item.crate !== window.currentCrate);
209                 if (a !== b) { return a - b; }
210
211                 // sort by item name length (longer goes later)
212                 a = aaa.word.length;
213                 b = bbb.word.length;
214                 if (a !== b) { return a - b; }
215
216                 // sort by item name (lexicographically larger goes later)
217                 a = aaa.word;
218                 b = bbb.word;
219                 if (a !== b) { return (a > b ? +1 : -1); }
220
221                 // sort by index of keyword in item name (no literal occurrence goes later)
222                 a = (aaa.index < 0);
223                 b = (bbb.index < 0);
224                 if (a !== b) { return a - b; }
225                 // (later literal occurrence, if any, goes later)
226                 a = aaa.index;
227                 b = bbb.index;
228                 if (a !== b) { return a - b; }
229
230                 // special precedence for primitive and keyword pages
231                 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
232                     (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
233                     return -1;
234                 }
235                 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
236                     (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
237                     return 1;
238                 }
239
240                 // sort by description (no description goes later)
241                 a = (aaa.item.desc === "");
242                 b = (bbb.item.desc === "");
243                 if (a !== b) { return a - b; }
244
245                 // sort by type (later occurrence in `itemTypes` goes later)
246                 a = aaa.item.ty;
247                 b = bbb.item.ty;
248                 if (a !== b) { return a - b; }
249
250                 // sort by path (lexicographically larger goes later)
251                 a = aaa.item.path;
252                 b = bbb.item.path;
253                 if (a !== b) { return (a > b ? +1 : -1); }
254
255                 // que sera, sera
256                 return 0;
257             });
258
259             for (i = 0, len = results.length; i < len; ++i) {
260                 result = results[i];
261
262                 // this validation does not make sense when searching by types
263                 if (result.dontValidate) {
264                     continue;
265                 }
266                 var name = result.item.name.toLowerCase(),
267                     path = result.item.path.toLowerCase(),
268                     parent = result.item.parent;
269
270                 if (!isType && !validateResult(name, path, split, parent)) {
271                     result.id = -1;
272                 }
273             }
274             return transformResults(results);
275         }
276
277         function extractGenerics(val) {
278             val = val.toLowerCase();
279             if (val.indexOf("<") !== -1) {
280                 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
281                 return {
282                     name: val.substring(0, val.indexOf("<")),
283                     generics: values.split(/\s*,\s*/),
284                 };
285             }
286             return {
287                 name: val,
288                 generics: [],
289             };
290         }
291
292         function checkGenerics(obj, val) {
293             // The names match, but we need to be sure that all generics kinda
294             // match as well.
295             var tmp_lev, elem_name;
296             if (val.generics.length > 0) {
297                 if (obj.length > GENERICS_DATA &&
298                       obj[GENERICS_DATA].length >= val.generics.length) {
299                     var elems = Object.create(null);
300                     var elength = obj[GENERICS_DATA].length;
301                     for (var x = 0; x < elength; ++x) {
302                         if (!elems[obj[GENERICS_DATA][x]]) {
303                             elems[obj[GENERICS_DATA][x]] = 0;
304                         }
305                         elems[obj[GENERICS_DATA][x]] += 1;
306                     }
307                     var total = 0;
308                     var done = 0;
309                     // We need to find the type that matches the most to remove it in order
310                     // to move forward.
311                     var vlength = val.generics.length;
312                     for (x = 0; x < vlength; ++x) {
313                         var lev = MAX_LEV_DISTANCE + 1;
314                         var firstGeneric = val.generics[x];
315                         var match = null;
316                         if (elems[firstGeneric]) {
317                             match = firstGeneric;
318                             lev = 0;
319                         } else {
320                             for (elem_name in elems) {
321                                 tmp_lev = levenshtein(elem_name, firstGeneric);
322                                 if (tmp_lev < lev) {
323                                     lev = tmp_lev;
324                                     match = elem_name;
325                                 }
326                             }
327                         }
328                         if (match !== null) {
329                             elems[match] -= 1;
330                             if (elems[match] == 0) {
331                                 delete elems[match];
332                             }
333                             total += lev;
334                             done += 1;
335                         } else {
336                             return MAX_LEV_DISTANCE + 1;
337                         }
338                     }
339                     return Math.ceil(total / done);
340                 }
341             }
342             return MAX_LEV_DISTANCE + 1;
343         }
344
345         // Check for type name and type generics (if any).
346         function checkType(obj, val, literalSearch) {
347             var lev_distance = MAX_LEV_DISTANCE + 1;
348             var len, x, firstGeneric;
349             if (obj[NAME] === val.name) {
350                 if (literalSearch) {
351                     if (val.generics && val.generics.length !== 0) {
352                         if (obj.length > GENERICS_DATA &&
353                              obj[GENERICS_DATA].length > 0) {
354                             var elems = Object.create(null);
355                             len = obj[GENERICS_DATA].length;
356                             for (x = 0; x < len; ++x) {
357                                 if (!elems[obj[GENERICS_DATA][x]]) {
358                                     elems[obj[GENERICS_DATA][x]] = 0;
359                                 }
360                                 elems[obj[GENERICS_DATA][x]] += 1;
361                             }
362
363                             var allFound = true;
364                             len = val.generics.length;
365                             for (x = 0; x < len; ++x) {
366                                 firstGeneric = val.generics[x];
367                                 if (elems[firstGeneric]) {
368                                     elems[firstGeneric] -= 1;
369                                 } else {
370                                     allFound = false;
371                                     break;
372                                 }
373                             }
374                             if (allFound) {
375                                 return true;
376                             }
377                         }
378                         return false;
379                     }
380                     return true;
381                 } else {
382                     // If the type has generics but don't match, then it won't return at this point.
383                     // Otherwise, `checkGenerics` will return 0 and it'll return.
384                     if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
385                         var tmp_lev = checkGenerics(obj, val);
386                         if (tmp_lev <= MAX_LEV_DISTANCE) {
387                             return tmp_lev;
388                         }
389                     }
390                 }
391             } else if (literalSearch) {
392                 if ((!val.generics || val.generics.length === 0) &&
393                       obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
394                     return obj[GENERICS_DATA].some(
395                         function(name) {
396                             return name === val.name;
397                         });
398                 }
399                 return false;
400             }
401             lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
402             if (lev_distance <= MAX_LEV_DISTANCE) {
403                 // The generics didn't match but the name kinda did so we give it
404                 // a levenshtein distance value that isn't *this* good so it goes
405                 // into the search results but not too high.
406                 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
407             } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
408                 // We can check if the type we're looking for is inside the generics!
409                 var olength = obj[GENERICS_DATA].length;
410                 for (x = 0; x < olength; ++x) {
411                     lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
412                                             lev_distance);
413                 }
414             }
415             // Now whatever happens, the returned distance is "less good" so we should mark it
416             // as such, and so we add 1 to the distance to make it "less good".
417             return lev_distance + 1;
418         }
419
420         function findArg(obj, val, literalSearch, typeFilter) {
421             var lev_distance = MAX_LEV_DISTANCE + 1;
422
423             if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
424                 var length = obj.type[INPUTS_DATA].length;
425                 for (var i = 0; i < length; i++) {
426                     var tmp = obj.type[INPUTS_DATA][i];
427                     if (!typePassesFilter(typeFilter, tmp[1])) {
428                         continue;
429                     }
430                     tmp = checkType(tmp, val, literalSearch);
431                     if (literalSearch) {
432                         if (tmp) {
433                             return true;
434                         }
435                         continue;
436                     }
437                     lev_distance = Math.min(tmp, lev_distance);
438                     if (lev_distance === 0) {
439                         return 0;
440                     }
441                 }
442             }
443             return literalSearch ? false : lev_distance;
444         }
445
446         function checkReturned(obj, val, literalSearch, typeFilter) {
447             var lev_distance = MAX_LEV_DISTANCE + 1;
448
449             if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
450                 var ret = obj.type[OUTPUT_DATA];
451                 if (typeof ret[0] === "string") {
452                     ret = [ret];
453                 }
454                 for (var x = 0, len = ret.length; x < len; ++x) {
455                     var tmp = ret[x];
456                     if (!typePassesFilter(typeFilter, tmp[1])) {
457                         continue;
458                     }
459                     tmp = checkType(tmp, val, literalSearch);
460                     if (literalSearch) {
461                         if (tmp) {
462                             return true;
463                         }
464                         continue;
465                     }
466                     lev_distance = Math.min(tmp, lev_distance);
467                     if (lev_distance === 0) {
468                         return 0;
469                     }
470                 }
471             }
472             return literalSearch ? false : lev_distance;
473         }
474
475         function checkPath(contains, lastElem, ty) {
476             if (contains.length === 0) {
477                 return 0;
478             }
479             var ret_lev = MAX_LEV_DISTANCE + 1;
480             var path = ty.path.split("::");
481
482             if (ty.parent && ty.parent.name) {
483                 path.push(ty.parent.name.toLowerCase());
484             }
485
486             var length = path.length;
487             var clength = contains.length;
488             if (clength > length) {
489                 return MAX_LEV_DISTANCE + 1;
490             }
491             for (var i = 0; i < length; ++i) {
492                 if (i + clength > length) {
493                     break;
494                 }
495                 var lev_total = 0;
496                 var aborted = false;
497                 for (var x = 0; x < clength; ++x) {
498                     var lev = levenshtein(path[i + x], contains[x]);
499                     if (lev > MAX_LEV_DISTANCE) {
500                         aborted = true;
501                         break;
502                     }
503                     lev_total += lev;
504                 }
505                 if (!aborted) {
506                     ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
507                 }
508             }
509             return ret_lev;
510         }
511
512         function typePassesFilter(filter, type) {
513             // No filter
514             if (filter <= NO_TYPE_FILTER) return true;
515
516             // Exact match
517             if (filter === type) return true;
518
519             // Match related items
520             var name = itemTypes[type];
521             switch (itemTypes[filter]) {
522                 case "constant":
523                     return name === "associatedconstant";
524                 case "fn":
525                     return name === "method" || name === "tymethod";
526                 case "type":
527                     return name === "primitive" || name === "associatedtype";
528                 case "trait":
529                     return name === "traitalias";
530             }
531
532             // No match
533             return false;
534         }
535
536         function createAliasFromItem(item) {
537             return {
538                 crate: item.crate,
539                 name: item.name,
540                 path: item.path,
541                 desc: item.desc,
542                 ty: item.ty,
543                 parent: item.parent,
544                 type: item.type,
545                 is_alias: true,
546             };
547         }
548
549         function handleAliases(ret, query, filterCrates) {
550             // We separate aliases and crate aliases because we want to have current crate
551             // aliases to be before the others in the displayed results.
552             var aliases = [];
553             var crateAliases = [];
554             if (filterCrates !== undefined) {
555                 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
556                     var query_aliases = ALIASES[filterCrates][query.search];
557                     var len = query_aliases.length;
558                     for (var i = 0; i < len; ++i) {
559                         aliases.push(createAliasFromItem(searchIndex[query_aliases[i]]));
560                     }
561                 }
562             } else {
563                 Object.keys(ALIASES).forEach(function(crate) {
564                     if (ALIASES[crate][query.search]) {
565                         var pushTo = crate === window.currentCrate ? crateAliases : aliases;
566                         var query_aliases = ALIASES[crate][query.search];
567                         var len = query_aliases.length;
568                         for (var i = 0; i < len; ++i) {
569                             pushTo.push(createAliasFromItem(searchIndex[query_aliases[i]]));
570                         }
571                     }
572                 });
573             }
574
575             var sortFunc = function(aaa, bbb) {
576                 if (aaa.path < bbb.path) {
577                     return 1;
578                 } else if (aaa.path === bbb.path) {
579                     return 0;
580                 }
581                 return -1;
582             };
583             crateAliases.sort(sortFunc);
584             aliases.sort(sortFunc);
585
586             var pushFunc = function(alias) {
587                 alias.alias = query.raw;
588                 var res = buildHrefAndPath(alias);
589                 alias.displayPath = pathSplitter(res[0]);
590                 alias.fullPath = alias.displayPath + alias.name;
591                 alias.href = res[1];
592
593                 ret.others.unshift(alias);
594                 if (ret.others.length > MAX_RESULTS) {
595                     ret.others.pop();
596                 }
597             };
598             onEach(aliases, pushFunc);
599             onEach(crateAliases, pushFunc);
600         }
601
602         // quoted values mean literal search
603         var nSearchWords = searchWords.length;
604         var i, it;
605         var ty;
606         var fullId;
607         var returned;
608         var in_args;
609         var len;
610         if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
611             val.charAt(val.length - 1) === val.charAt(0))
612         {
613             val = extractGenerics(val.substr(1, val.length - 2));
614             for (i = 0; i < nSearchWords; ++i) {
615                 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
616                     continue;
617                 }
618                 in_args = findArg(searchIndex[i], val, true, typeFilter);
619                 returned = checkReturned(searchIndex[i], val, true, typeFilter);
620                 ty = searchIndex[i];
621                 fullId = ty.id;
622
623                 if (searchWords[i] === val.name
624                     && typePassesFilter(typeFilter, searchIndex[i].ty)
625                     && results[fullId] === undefined) {
626                     results[fullId] = {
627                         id: i,
628                         index: -1,
629                         dontValidate: true,
630                     };
631                 }
632                 if (in_args && results_in_args[fullId] === undefined) {
633                     results_in_args[fullId] = {
634                         id: i,
635                         index: -1,
636                         dontValidate: true,
637                     };
638                 }
639                 if (returned && results_returned[fullId] === undefined) {
640                     results_returned[fullId] = {
641                         id: i,
642                         index: -1,
643                         dontValidate: true,
644                     };
645                 }
646             }
647             query.inputs = [val];
648             query.output = val;
649             query.search = val;
650         // searching by type
651         } else if (val.search("->") > -1) {
652             var trimmer = function(s) { return s.trim(); };
653             var parts = val.split("->").map(trimmer);
654             var input = parts[0];
655             // sort inputs so that order does not matter
656             var inputs = input.split(",").map(trimmer).sort();
657             for (i = 0, len = inputs.length; i < len; ++i) {
658                 inputs[i] = extractGenerics(inputs[i]);
659             }
660             var output = extractGenerics(parts[1]);
661
662             for (i = 0; i < nSearchWords; ++i) {
663                 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
664                     continue;
665                 }
666                 var type = searchIndex[i].type;
667                 ty = searchIndex[i];
668                 if (!type) {
669                     continue;
670                 }
671                 fullId = ty.id;
672
673                 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
674                 if (output.name === "*" || returned) {
675                     in_args = false;
676                     var is_module = false;
677
678                     if (input === "*") {
679                         is_module = true;
680                     } else {
681                         var allFound = true;
682                         for (it = 0, len = inputs.length; allFound && it < len; it++) {
683                             allFound = checkType(type, inputs[it], true);
684                         }
685                         in_args = allFound;
686                     }
687                     if (in_args) {
688                         results_in_args[fullId] = {
689                             id: i,
690                             index: -1,
691                             dontValidate: true,
692                         };
693                     }
694                     if (returned) {
695                         results_returned[fullId] = {
696                             id: i,
697                             index: -1,
698                             dontValidate: true,
699                         };
700                     }
701                     if (is_module) {
702                         results[fullId] = {
703                             id: i,
704                             index: -1,
705                             dontValidate: true,
706                         };
707                     }
708                 }
709             }
710             query.inputs = inputs.map(function(input) {
711                 return input.name;
712             });
713             query.output = output.name;
714         } else {
715             query.inputs = [val];
716             query.output = val;
717             query.search = val;
718             // gather matching search results up to a certain maximum
719             val = val.replace(/_/g, "");
720
721             var valGenerics = extractGenerics(val);
722
723             var paths = valLower.split("::");
724             removeEmptyStringsFromArray(paths);
725             val = paths[paths.length - 1];
726             var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
727
728             var lev, j;
729             for (j = 0; j < nSearchWords; ++j) {
730                 ty = searchIndex[j];
731                 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
732                     continue;
733                 }
734                 var lev_add = 0;
735                 if (paths.length > 1) {
736                     lev = checkPath(contains, paths[paths.length - 1], ty);
737                     if (lev > MAX_LEV_DISTANCE) {
738                         continue;
739                     } else if (lev > 0) {
740                         lev_add = lev / 10;
741                     }
742                 }
743
744                 returned = MAX_LEV_DISTANCE + 1;
745                 in_args = MAX_LEV_DISTANCE + 1;
746                 var index = -1;
747                 // we want lev results to go lower than others
748                 lev = MAX_LEV_DISTANCE + 1;
749                 fullId = ty.id;
750
751                 if (searchWords[j].indexOf(split[i]) > -1 ||
752                     searchWords[j].indexOf(val) > -1 ||
753                     ty.normalizedName.indexOf(val) > -1)
754                 {
755                     // filter type: ... queries
756                     if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
757                         index = ty.normalizedName.indexOf(val);
758                     }
759                 }
760                 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
761                     if (typePassesFilter(typeFilter, ty.ty)) {
762                         lev += 1;
763                     } else {
764                         lev = MAX_LEV_DISTANCE + 1;
765                     }
766                 }
767                 in_args = findArg(ty, valGenerics, false, typeFilter);
768                 returned = checkReturned(ty, valGenerics, false, typeFilter);
769
770                 lev += lev_add;
771                 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
772                     if (val.length < 6) {
773                         lev -= 1;
774                     } else {
775                         lev = 0;
776                     }
777                 }
778                 if (in_args <= MAX_LEV_DISTANCE) {
779                     if (results_in_args[fullId] === undefined) {
780                         results_in_args[fullId] = {
781                             id: j,
782                             index: index,
783                             lev: in_args,
784                         };
785                     }
786                     results_in_args[fullId].lev =
787                         Math.min(results_in_args[fullId].lev, in_args);
788                 }
789                 if (returned <= MAX_LEV_DISTANCE) {
790                     if (results_returned[fullId] === undefined) {
791                         results_returned[fullId] = {
792                             id: j,
793                             index: index,
794                             lev: returned,
795                         };
796                     }
797                     results_returned[fullId].lev =
798                         Math.min(results_returned[fullId].lev, returned);
799                 }
800                 if (typePassesFilter(typeFilter, ty.ty) &&
801                         (index !== -1 || lev <= MAX_LEV_DISTANCE)) {
802                     if (index !== -1 && paths.length < 2) {
803                         lev = 0;
804                     }
805                     if (results[fullId] === undefined) {
806                         results[fullId] = {
807                             id: j,
808                             index: index,
809                             lev: lev,
810                         };
811                     }
812                     results[fullId].lev = Math.min(results[fullId].lev, lev);
813                 }
814             }
815         }
816
817         var ret = {
818             "in_args": sortResults(results_in_args, true),
819             "returned": sortResults(results_returned, true),
820             "others": sortResults(results, false),
821         };
822         handleAliases(ret, query, filterCrates);
823         return ret;
824     }
825
826     /**
827      * Validate performs the following boolean logic. For example:
828      * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
829      * exists in (name || path || parent) OR => ("file" && "open") exists in
830      * (name || path )
831      *
832      * This could be written functionally, but I wanted to minimise
833      * functions on stack.
834      *
835      * @param  {[string]} name   [The name of the result]
836      * @param  {[string]} path   [The path of the result]
837      * @param  {[string]} keys   [The keys to be used (["file", "open"])]
838      * @param  {[object]} parent [The parent of the result]
839      * @return {boolean}       [Whether the result is valid or not]
840      */
841     function validateResult(name, path, keys, parent) {
842         for (var i = 0, len = keys.length; i < len; ++i) {
843             // each check is for validation so we negate the conditions and invalidate
844             if (!(
845                 // check for an exact name match
846                 name.indexOf(keys[i]) > -1 ||
847                 // then an exact path match
848                 path.indexOf(keys[i]) > -1 ||
849                 // next if there is a parent, check for exact parent match
850                 (parent !== undefined && parent.name !== undefined &&
851                     parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
852                 // lastly check to see if the name was a levenshtein match
853                 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
854                 return false;
855             }
856         }
857         return true;
858     }
859
860     function getQuery(raw) {
861         var matches, type, query;
862         query = raw;
863
864         matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
865         if (matches) {
866             type = matches[1].replace(/^const$/, "constant");
867             query = query.substring(matches[0].length);
868         }
869
870         return {
871             raw: raw,
872             query: query,
873             type: type,
874             id: query + type
875         };
876     }
877
878     function nextTab(direction) {
879         var next = (searchState.currentTab + direction + 3) % searchState.focusedByTab.length;
880         searchState.focusedByTab[searchState.currentTab] = document.activeElement;
881         printTab(next);
882         focusSearchResult();
883     }
884
885     // Focus the first search result on the active tab, or the result that
886     // was focused last time this tab was active.
887     function focusSearchResult() {
888         var target = searchState.focusedByTab[searchState.currentTab] ||
889             document.querySelectorAll(".search-results.active a").item(0) ||
890             document.querySelectorAll("#titles > button").item(searchState.currentTab);
891         if (target) {
892             target.focus();
893         }
894     }
895
896     function buildHrefAndPath(item) {
897         var displayPath;
898         var href;
899         var type = itemTypes[item.ty];
900         var name = item.name;
901         var path = item.path;
902
903         if (type === "mod") {
904             displayPath = path + "::";
905             href = window.rootPath + path.replace(/::/g, "/") + "/" +
906                    name + "/index.html";
907         } else if (type === "primitive" || type === "keyword") {
908             displayPath = "";
909             href = window.rootPath + path.replace(/::/g, "/") +
910                    "/" + type + "." + name + ".html";
911         } else if (type === "externcrate") {
912             displayPath = "";
913             href = window.rootPath + name + "/index.html";
914         } else if (item.parent !== undefined) {
915             var myparent = item.parent;
916             var anchor = "#" + type + "." + name;
917             var parentType = itemTypes[myparent.ty];
918             var pageType = parentType;
919             var pageName = myparent.name;
920
921             if (parentType === "primitive") {
922                 displayPath = myparent.name + "::";
923             } else if (type === "structfield" && parentType === "variant") {
924                 // Structfields belonging to variants are special: the
925                 // final path element is the enum name.
926                 var enumNameIdx = item.path.lastIndexOf("::");
927                 var enumName = item.path.substr(enumNameIdx + 2);
928                 path = item.path.substr(0, enumNameIdx);
929                 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
930                 anchor = "#variant." + myparent.name + ".field." + name;
931                 pageType = "enum";
932                 pageName = enumName;
933             } else {
934                 displayPath = path + "::" + myparent.name + "::";
935             }
936             href = window.rootPath + path.replace(/::/g, "/") +
937                    "/" + pageType +
938                    "." + pageName +
939                    ".html" + anchor;
940         } else {
941             displayPath = item.path + "::";
942             href = window.rootPath + item.path.replace(/::/g, "/") +
943                    "/" + type + "." + name + ".html";
944         }
945         return [displayPath, href];
946     }
947
948     function escape(content) {
949         var h1 = document.createElement("h1");
950         h1.textContent = content;
951         return h1.innerHTML;
952     }
953
954     function pathSplitter(path) {
955         var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
956         if (tmp.endsWith("<span>")) {
957             return tmp.slice(0, tmp.length - 6);
958         }
959         return tmp;
960     }
961
962     function addTab(array, query, display) {
963         var extraClass = "";
964         if (display === true) {
965             extraClass = " active";
966         }
967
968         var output = document.createElement("div");
969         var duplicates = {};
970         var length = 0;
971         if (array.length > 0) {
972             output.className = "search-results " + extraClass;
973
974             array.forEach(function(item) {
975                 if (item.is_alias !== true) {
976                     if (duplicates[item.fullPath]) {
977                         return;
978                     }
979                     duplicates[item.fullPath] = true;
980                 }
981
982                 var name = item.name;
983                 var type = itemTypes[item.ty];
984
985                 length += 1;
986
987                 var extra = "";
988                 if (type === "primitive") {
989                     extra = " <i>(primitive type)</i>";
990                 } else if (type === "keyword") {
991                     extra = " <i>(keyword)</i>";
992                 }
993
994                 var link = document.createElement("a");
995                 link.className = "result-" + type;
996                 link.href = item.href;
997
998                 var wrapper = document.createElement("div");
999                 var resultName = document.createElement("div");
1000                 resultName.className = "result-name";
1001
1002                 if (item.is_alias) {
1003                     var alias = document.createElement("span");
1004                     alias.className = "alias";
1005
1006                     var bold = document.createElement("b");
1007                     bold.innerText = item.alias;
1008                     alias.appendChild(bold);
1009
1010                     alias.insertAdjacentHTML(
1011                         "beforeend",
1012                         "<span class=\"grey\"><i>&nbsp;- see&nbsp;</i></span>");
1013
1014                     resultName.appendChild(alias);
1015                 }
1016                 resultName.insertAdjacentHTML(
1017                     "beforeend",
1018                     item.displayPath + "<span class=\"" + type + "\">" + name + extra + "</span>");
1019                 wrapper.appendChild(resultName);
1020
1021                 var description = document.createElement("div");
1022                 description.className = "desc";
1023                 var spanDesc = document.createElement("span");
1024                 spanDesc.insertAdjacentHTML("beforeend", item.desc);
1025
1026                 description.appendChild(spanDesc);
1027                 wrapper.appendChild(description);
1028                 link.appendChild(wrapper);
1029                 output.appendChild(link);
1030             });
1031         } else {
1032             output.className = "search-failed" + extraClass;
1033             output.innerHTML = "No results :(<br/>" +
1034                 "Try on <a href=\"https://duckduckgo.com/?q=" +
1035                 encodeURIComponent("rust " + query.query) +
1036                 "\">DuckDuckGo</a>?<br/><br/>" +
1037                 "Or try looking in one of these:<ul><li>The <a " +
1038                 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1039                 " for technical details about the language.</li><li><a " +
1040                 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1041                 "Example</a> for expository code examples.</a></li><li>The <a " +
1042                 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1043                 "introductions to language features and the language itself.</li><li><a " +
1044                 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1045                 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul>";
1046         }
1047         return [output, length];
1048     }
1049
1050     function makeTabHeader(tabNb, text, nbElems) {
1051         if (searchState.currentTab === tabNb) {
1052             return "<button class=\"selected\">" + text +
1053                    " <div class=\"count\">(" + nbElems + ")</div></button>";
1054         }
1055         return "<button>" + text + " <div class=\"count\">(" + nbElems + ")</div></button>";
1056     }
1057
1058     function showResults(results, go_to_first) {
1059         var search = searchState.outputElement();
1060         if (go_to_first || (results.others.length === 1
1061             && getSettingValue("go-to-only-result") === "true"
1062             // By default, the search DOM element is "empty" (meaning it has no children not
1063             // text content). Once a search has been run, it won't be empty, even if you press
1064             // ESC or empty the search input (which also "cancels" the search).
1065             && (!search.firstChild || search.firstChild.innerText !== searchState.loadingText)))
1066         {
1067             var elem = document.createElement("a");
1068             elem.href = results.others[0].href;
1069             removeClass(elem, "active");
1070             // For firefox, we need the element to be in the DOM so it can be clicked.
1071             document.body.appendChild(elem);
1072             elem.click();
1073             return;
1074         }
1075         var query = getQuery(searchState.input.value);
1076
1077         currentResults = query.id;
1078
1079         var ret_others = addTab(results.others, query);
1080         var ret_in_args = addTab(results.in_args, query, false);
1081         var ret_returned = addTab(results.returned, query, false);
1082
1083         // Navigate to the relevant tab if the current tab is empty, like in case users search
1084         // for "-> String". If they had selected another tab previously, they have to click on
1085         // it again.
1086         var currentTab = searchState.currentTab;
1087         if ((currentTab === 0 && ret_others[1] === 0) ||
1088                 (currentTab === 1 && ret_in_args[1] === 0) ||
1089                 (currentTab === 2 && ret_returned[1] === 0)) {
1090             if (ret_others[1] !== 0) {
1091                 currentTab = 0;
1092             } else if (ret_in_args[1] !== 0) {
1093                 currentTab = 1;
1094             } else if (ret_returned[1] !== 0) {
1095                 currentTab = 2;
1096             }
1097         }
1098
1099         var output = "<h1>Results for " + escape(query.query) +
1100             (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1101             "<div id=\"titles\">" +
1102             makeTabHeader(0, "In Names", ret_others[1]) +
1103             makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1104             makeTabHeader(2, "In Return Types", ret_returned[1]) +
1105             "</div>";
1106
1107         var resultsElem = document.createElement("div");
1108         resultsElem.id = "results";
1109         resultsElem.appendChild(ret_others[0]);
1110         resultsElem.appendChild(ret_in_args[0]);
1111         resultsElem.appendChild(ret_returned[0]);
1112
1113         search.innerHTML = output;
1114         search.appendChild(resultsElem);
1115         // Reset focused elements.
1116         searchState.focusedByTab = [null, null, null];
1117         searchState.showResults(search);
1118         var elems = document.getElementById("titles").childNodes;
1119         elems[0].onclick = function() { printTab(0); };
1120         elems[1].onclick = function() { printTab(1); };
1121         elems[2].onclick = function() { printTab(2); };
1122         printTab(currentTab);
1123     }
1124
1125     function execSearch(query, searchWords, filterCrates) {
1126         function getSmallest(arrays, positions, notDuplicates) {
1127             var start = null;
1128
1129             for (var it = 0, len = positions.length; it < len; ++it) {
1130                 if (arrays[it].length > positions[it] &&
1131                     (start === null || start > arrays[it][positions[it]].lev) &&
1132                     !notDuplicates[arrays[it][positions[it]].fullPath]) {
1133                     start = arrays[it][positions[it]].lev;
1134                 }
1135             }
1136             return start;
1137         }
1138
1139         function mergeArrays(arrays) {
1140             var ret = [];
1141             var positions = [];
1142             var notDuplicates = {};
1143
1144             for (var x = 0, arrays_len = arrays.length; x < arrays_len; ++x) {
1145                 positions.push(0);
1146             }
1147             while (ret.length < MAX_RESULTS) {
1148                 var smallest = getSmallest(arrays, positions, notDuplicates);
1149
1150                 if (smallest === null) {
1151                     break;
1152                 }
1153                 for (x = 0; x < arrays_len && ret.length < MAX_RESULTS; ++x) {
1154                     if (arrays[x].length > positions[x] &&
1155                             arrays[x][positions[x]].lev === smallest &&
1156                             !notDuplicates[arrays[x][positions[x]].fullPath]) {
1157                         ret.push(arrays[x][positions[x]]);
1158                         notDuplicates[arrays[x][positions[x]].fullPath] = true;
1159                         positions[x] += 1;
1160                     }
1161                 }
1162             }
1163             return ret;
1164         }
1165
1166         // Split search query by ",", while respecting angle bracket nesting.
1167         // Since "<" is an alias for the Ord family of traits, it also uses
1168         // lookahead to distinguish "<"-as-less-than from "<"-as-angle-bracket.
1169         //
1170         // tokenizeQuery("A<B, C>, D") == ["A<B, C>", "D"]
1171         // tokenizeQuery("A<B, C, D") == ["A<B", "C", "D"]
1172         function tokenizeQuery(raw) {
1173             var i, matched;
1174             var l = raw.length;
1175             var depth = 0;
1176             var nextAngle = /(<|>)/g;
1177             var ret = [];
1178             var start = 0;
1179             for (i = 0; i < l; ++i) {
1180                 switch (raw[i]) {
1181                     case "<":
1182                         nextAngle.lastIndex = i + 1;
1183                         matched = nextAngle.exec(raw);
1184                         if (matched && matched[1] === '>') {
1185                             depth += 1;
1186                         }
1187                         break;
1188                     case ">":
1189                         if (depth > 0) {
1190                             depth -= 1;
1191                         }
1192                         break;
1193                     case ",":
1194                         if (depth === 0) {
1195                             ret.push(raw.substring(start, i));
1196                             start = i + 1;
1197                         }
1198                         break;
1199                 }
1200             }
1201             if (start !== i) {
1202                 ret.push(raw.substring(start, i));
1203             }
1204             return ret;
1205         }
1206
1207         var queries = tokenizeQuery(query.raw);
1208         var results = {
1209             "in_args": [],
1210             "returned": [],
1211             "others": [],
1212         };
1213
1214         for (var i = 0, len = queries.length; i < len; ++i) {
1215             query = queries[i].trim();
1216             if (query.length !== 0) {
1217                 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1218
1219                 results.in_args.push(tmp.in_args);
1220                 results.returned.push(tmp.returned);
1221                 results.others.push(tmp.others);
1222             }
1223         }
1224         if (queries.length > 1) {
1225             return {
1226                 "in_args": mergeArrays(results.in_args),
1227                 "returned": mergeArrays(results.returned),
1228                 "others": mergeArrays(results.others),
1229             };
1230         }
1231         return {
1232             "in_args": results.in_args[0],
1233             "returned": results.returned[0],
1234             "others": results.others[0],
1235         };
1236     }
1237
1238     function getFilterCrates() {
1239         var elem = document.getElementById("crate-search");
1240
1241         if (elem && elem.value !== "All crates" &&
1242             hasOwnPropertyRustdoc(rawSearchIndex, elem.value))
1243         {
1244             return elem.value;
1245         }
1246         return undefined;
1247     }
1248
1249     function search(e, forced) {
1250         var params = searchState.getQueryStringParams();
1251         var query = getQuery(searchState.input.value.trim());
1252
1253         if (e) {
1254             e.preventDefault();
1255         }
1256
1257         if (query.query.length === 0) {
1258             return;
1259         }
1260         if (!forced && query.id === currentResults) {
1261             if (query.query.length > 0) {
1262                 searchState.putBackSearch(searchState.input);
1263             }
1264             return;
1265         }
1266
1267         // Update document title to maintain a meaningful browser history
1268         searchState.title = "Results for " + query.query + " - Rust";
1269
1270         // Because searching is incremental by character, only the most
1271         // recent search query is added to the browser history.
1272         if (searchState.browserSupportsHistoryApi()) {
1273             var newURL = getNakedUrl() + "?search=" + encodeURIComponent(query.raw) +
1274                 window.location.hash;
1275             if (!history.state && !params.search) {
1276                 history.pushState(query, "", newURL);
1277             } else {
1278                 history.replaceState(query, "", newURL);
1279             }
1280         }
1281
1282         var filterCrates = getFilterCrates();
1283         showResults(execSearch(query, index, filterCrates), params.go_to_first);
1284     }
1285
1286     function buildIndex(rawSearchIndex) {
1287         searchIndex = [];
1288         var searchWords = [];
1289         var i, word;
1290         var currentIndex = 0;
1291         var id = 0;
1292
1293         for (var crate in rawSearchIndex) {
1294             if (!hasOwnPropertyRustdoc(rawSearchIndex, crate)) {
1295                 continue;
1296             }
1297
1298             var crateSize = 0;
1299
1300             searchWords.push(crate);
1301             // This object should have exactly the same set of fields as the "row"
1302             // object defined below. Your JavaScript runtime will thank you.
1303             // https://mathiasbynens.be/notes/shapes-ics
1304             var crateRow = {
1305                 crate: crate,
1306                 ty: 1, // == ExternCrate
1307                 name: crate,
1308                 path: "",
1309                 desc: rawSearchIndex[crate].doc,
1310                 parent: undefined,
1311                 type: null,
1312                 id: id,
1313                 normalizedName: crate.indexOf("_") === -1 ? crate : crate.replace(/_/g, ""),
1314             };
1315             id += 1;
1316             searchIndex.push(crateRow);
1317             currentIndex += 1;
1318
1319             // an array of (Number) item types
1320             var itemTypes = rawSearchIndex[crate].t;
1321             // an array of (String) item names
1322             var itemNames = rawSearchIndex[crate].n;
1323             // an array of (String) full paths (or empty string for previous path)
1324             var itemPaths = rawSearchIndex[crate].q;
1325             // an array of (String) descriptions
1326             var itemDescs = rawSearchIndex[crate].d;
1327             // an array of (Number) the parent path index + 1 to `paths`, or 0 if none
1328             var itemParentIdxs = rawSearchIndex[crate].i;
1329             // an array of (Object | null) the type of the function, if any
1330             var itemFunctionSearchTypes = rawSearchIndex[crate].f;
1331             // an array of [(Number) item type,
1332             //              (String) name]
1333             var paths = rawSearchIndex[crate].p;
1334             // an array of [(String) alias name
1335             //             [Number] index to items]
1336             var aliases = rawSearchIndex[crate].a;
1337
1338             // convert `rawPaths` entries into object form
1339             var len = paths.length;
1340             for (i = 0; i < len; ++i) {
1341                 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1342             }
1343
1344             // convert `item*` into an object form, and construct word indices.
1345             //
1346             // before any analysis is performed lets gather the search terms to
1347             // search against apart from the rest of the data.  This is a quick
1348             // operation that is cached for the life of the page state so that
1349             // all other search operations have access to this cached data for
1350             // faster analysis operations
1351             len = itemTypes.length;
1352             var lastPath = "";
1353             for (i = 0; i < len; ++i) {
1354                 // This object should have exactly the same set of fields as the "crateRow"
1355                 // object defined above.
1356                 if (typeof itemNames[i] === "string") {
1357                     word = itemNames[i].toLowerCase();
1358                     searchWords.push(word);
1359                 } else {
1360                     word = "";
1361                     searchWords.push("");
1362                 }
1363                 var row = {
1364                     crate: crate,
1365                     ty: itemTypes[i],
1366                     name: itemNames[i],
1367                     path: itemPaths[i] ? itemPaths[i] : lastPath,
1368                     desc: itemDescs[i],
1369                     parent: itemParentIdxs[i] > 0 ? paths[itemParentIdxs[i] - 1] : undefined,
1370                     type: itemFunctionSearchTypes[i],
1371                     id: id,
1372                     normalizedName: word.indexOf("_") === -1 ? word : word.replace(/_/g, ""),
1373                 };
1374                 id += 1;
1375                 searchIndex.push(row);
1376                 lastPath = row.path;
1377                 crateSize += 1;
1378             }
1379
1380             if (aliases) {
1381                 ALIASES[crate] = {};
1382                 var j, local_aliases;
1383                 for (var alias_name in aliases) {
1384                     if (!hasOwnPropertyRustdoc(aliases, alias_name)) {
1385                         continue;
1386                     }
1387
1388                     if (!hasOwnPropertyRustdoc(ALIASES[crate], alias_name)) {
1389                         ALIASES[crate][alias_name] = [];
1390                     }
1391                     local_aliases = aliases[alias_name];
1392                     for (j = 0, len = local_aliases.length; j < len; ++j) {
1393                         ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1394                     }
1395                 }
1396             }
1397             currentIndex += crateSize;
1398         }
1399         return searchWords;
1400     }
1401
1402     function registerSearchEvents() {
1403         var searchAfter500ms = function() {
1404             searchState.clearInputTimeout();
1405             if (searchState.input.value.length === 0) {
1406                 if (searchState.browserSupportsHistoryApi()) {
1407                     history.replaceState("", window.currentCrate + " - Rust",
1408                         getNakedUrl() + window.location.hash);
1409                 }
1410                 searchState.hideResults();
1411             } else {
1412                 searchState.timeout = setTimeout(search, 500);
1413             }
1414         };
1415         searchState.input.onkeyup = searchAfter500ms;
1416         searchState.input.oninput = searchAfter500ms;
1417         document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1418             e.preventDefault();
1419             searchState.clearInputTimeout();
1420             search();
1421         };
1422         searchState.input.onchange = function(e) {
1423             if (e.target !== document.activeElement) {
1424                 // To prevent doing anything when it's from a blur event.
1425                 return;
1426             }
1427             // Do NOT e.preventDefault() here. It will prevent pasting.
1428             searchState.clearInputTimeout();
1429             // zero-timeout necessary here because at the time of event handler execution the
1430             // pasted content is not in the input field yet. Shouldn’t make any difference for
1431             // change, though.
1432             setTimeout(search, 0);
1433         };
1434         searchState.input.onpaste = searchState.input.onchange;
1435
1436         searchState.outputElement().addEventListener("keydown", function(e) {
1437             // We only handle unmodified keystrokes here. We don't want to interfere with,
1438             // for instance, alt-left and alt-right for history navigation.
1439             if (e.altKey || e.ctrlKey || e.shiftKey || e.metaKey) {
1440                 return;
1441             }
1442             // up and down arrow select next/previous search result, or the
1443             // search box if we're already at the top.
1444             if (e.which === 38) { // up
1445                 var previous = document.activeElement.previousElementSibling;
1446                 if (previous) {
1447                     previous.focus();
1448                 } else {
1449                     searchState.focus();
1450                 }
1451                 e.preventDefault();
1452             } else if (e.which === 40) { // down
1453                 var next = document.activeElement.nextElementSibling;
1454                 if (next) {
1455                     next.focus();
1456                 }
1457                 var rect = document.activeElement.getBoundingClientRect();
1458                 if (window.innerHeight - rect.bottom < rect.height) {
1459                     window.scrollBy(0, rect.height);
1460                 }
1461                 e.preventDefault();
1462             } else if (e.which === 37) { // left
1463                 nextTab(-1);
1464                 e.preventDefault();
1465             } else if (e.which === 39) { // right
1466                 nextTab(1);
1467                 e.preventDefault();
1468             }
1469         });
1470
1471         searchState.input.addEventListener("keydown", function(e) {
1472             if (e.which === 40) { // down
1473                 focusSearchResult();
1474                 e.preventDefault();
1475             }
1476         });
1477
1478
1479         var selectCrate = document.getElementById("crate-search");
1480         if (selectCrate) {
1481             selectCrate.onchange = function() {
1482                 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1483                 // In case you "cut" the entry from the search input, then change the crate filter
1484                 // before paste back the previous search, you get the old search results without
1485                 // the filter. To prevent this, we need to remove the previous results.
1486                 currentResults = null;
1487                 search(undefined, true);
1488             };
1489         }
1490
1491         // Push and pop states are used to add search results to the browser
1492         // history.
1493         if (searchState.browserSupportsHistoryApi()) {
1494             // Store the previous <title> so we can revert back to it later.
1495             var previousTitle = document.title;
1496
1497             window.addEventListener("popstate", function(e) {
1498                 var params = searchState.getQueryStringParams();
1499                 // Revert to the previous title manually since the History
1500                 // API ignores the title parameter.
1501                 document.title = previousTitle;
1502                 // When browsing forward to search results the previous
1503                 // search will be repeated, so the currentResults are
1504                 // cleared to ensure the search is successful.
1505                 currentResults = null;
1506                 // Synchronize search bar with query string state and
1507                 // perform the search. This will empty the bar if there's
1508                 // nothing there, which lets you really go back to a
1509                 // previous state with nothing in the bar.
1510                 if (params.search && params.search.length > 0) {
1511                     searchState.input.value = params.search;
1512                     // Some browsers fire "onpopstate" for every page load
1513                     // (Chrome), while others fire the event only when actually
1514                     // popping a state (Firefox), which is why search() is
1515                     // called both here and at the end of the startSearch()
1516                     // function.
1517                     search(e);
1518                 } else {
1519                     searchState.input.value = "";
1520                     // When browsing back from search results the main page
1521                     // visibility must be reset.
1522                     searchState.hideResults();
1523                 }
1524             });
1525         }
1526
1527         // This is required in firefox to avoid this problem: Navigating to a search result
1528         // with the keyboard, hitting enter, and then hitting back would take you back to
1529         // the doc page, rather than the search that should overlay it.
1530         // This was an interaction between the back-forward cache and our handlers
1531         // that try to sync state between the URL and the search input. To work around it,
1532         // do a small amount of re-init on page show.
1533         window.onpageshow = function(){
1534             var qSearch = searchState.getQueryStringParams().search;
1535             if (searchState.input.value === "" && qSearch) {
1536                 searchState.input.value = qSearch;
1537             }
1538             search();
1539         };
1540     }
1541
1542     index = buildIndex(rawSearchIndex);
1543     registerSearchEvents();
1544     // If there's a search term in the URL, execute the search now.
1545     if (searchState.getQueryStringParams().search) {
1546         search();
1547     }
1548 };
1549
1550 if (window.searchIndex !== undefined) {
1551     initSearch(window.searchIndex);
1552 }
1553
1554 })();