]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/static/main.js
3174c1be3adc80a26824d8dbfc2f7569e15c1834
[rust.git] / src / librustdoc / html / static / main.js
1 /*!
2  * Copyright 2014 The Rust Project Developers. See the COPYRIGHT
3  * file at the top-level directory of this distribution and at
4  * http://rust-lang.org/COPYRIGHT.
5  *
6  * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
7  * http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
8  * <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
9  * option. This file may not be copied, modified, or distributed
10  * except according to those terms.
11  */
12
13 /*jslint browser: true, es5: true */
14 /*globals $: true, rootPath: true */
15
16 (function() {
17     "use strict";
18
19     // This mapping table should match the discriminants of
20     // `rustdoc::html::item_type::ItemType` type in Rust.
21     var itemTypes = ["mod",
22                      "externcrate",
23                      "import",
24                      "struct",
25                      "enum",
26                      "fn",
27                      "type",
28                      "static",
29                      "trait",
30                      "impl",
31                      "tymethod",
32                      "method",
33                      "structfield",
34                      "variant",
35                      "macro",
36                      "primitive",
37                      "associatedtype",
38                      "constant",
39                      "associatedconstant",
40                      "union",
41                      "foreigntype",
42                      "keyword",
43                      "existential",
44                      "attr",
45                      "derive"];
46
47     var search_input = document.getElementsByClassName('search-input')[0];
48
49     // On the search screen, so you remain on the last tab you opened.
50     //
51     // 0 for "In Names"
52     // 1 for "In Parameters"
53     // 2 for "In Return Types"
54     var currentTab = 0;
55
56     var themesWidth = null;
57
58     var titleBeforeSearch = document.title;
59
60     if (!String.prototype.startsWith) {
61         String.prototype.startsWith = function(searchString, position) {
62             position = position || 0;
63             return this.indexOf(searchString, position) === position;
64         };
65     }
66     if (!String.prototype.endsWith) {
67         String.prototype.endsWith = function(suffix, length) {
68             var l = length || this.length;
69             return this.indexOf(suffix, l - suffix.length) !== -1;
70         };
71     }
72
73     function getPageId() {
74         var id = document.location.href.split('#')[1];
75         if (id) {
76             return id.split('?')[0].split('&')[0];
77         }
78         return null;
79     }
80
81     function hasClass(elem, className) {
82         if (elem && className && elem.className) {
83             var elemClass = elem.className;
84             var start = elemClass.indexOf(className);
85             if (start === -1) {
86                 return false;
87             } else if (elemClass.length === className.length) {
88                 return true;
89             } else {
90                 if (start > 0 && elemClass[start - 1] !== ' ') {
91                     return false;
92                 }
93                 var end = start + className.length;
94                 return !(end < elemClass.length && elemClass[end] !== ' ');
95             }
96         }
97         return false;
98     }
99
100     function addClass(elem, className) {
101         if (elem && className && !hasClass(elem, className)) {
102             if (elem.className && elem.className.length > 0) {
103                 elem.className += ' ' + className;
104             } else {
105                 elem.className = className;
106             }
107         }
108     }
109
110     function removeClass(elem, className) {
111         if (elem && className && elem.className) {
112             elem.className = (" " + elem.className + " ").replace(" " + className + " ", " ")
113                                                          .trim();
114         }
115     }
116
117     function isHidden(elem) {
118         return (elem.offsetParent === null)
119     }
120
121     function showSidebar() {
122         var elems = document.getElementsByClassName("sidebar-elems")[0];
123         if (elems) {
124             addClass(elems, "show-it");
125         }
126         var sidebar = document.getElementsByClassName('sidebar')[0];
127         if (sidebar) {
128             addClass(sidebar, 'mobile');
129             var filler = document.getElementById("sidebar-filler");
130             if (!filler) {
131                 var div = document.createElement("div");
132                 div.id = "sidebar-filler";
133                 sidebar.appendChild(div);
134             }
135         }
136         var themePicker = document.getElementsByClassName("theme-picker");
137         if (themePicker && themePicker.length > 0) {
138             themePicker[0].style.display = "none";
139         }
140     }
141
142     function hideSidebar() {
143         var elems = document.getElementsByClassName("sidebar-elems")[0];
144         if (elems) {
145             removeClass(elems, "show-it");
146         }
147         var sidebar = document.getElementsByClassName('sidebar')[0];
148         removeClass(sidebar, 'mobile');
149         var filler = document.getElementById("sidebar-filler");
150         if (filler) {
151             filler.remove();
152         }
153         document.getElementsByTagName("body")[0].style.marginTop = '';
154         var themePicker = document.getElementsByClassName("theme-picker");
155         if (themePicker && themePicker.length > 0) {
156             themePicker[0].style.display = null;
157         }
158     }
159
160     // used for special search precedence
161     var TY_PRIMITIVE = itemTypes.indexOf("primitive");
162     var TY_KEYWORD = itemTypes.indexOf("keyword");
163
164     onEach(document.getElementsByClassName('js-only'), function(e) {
165         removeClass(e, 'js-only');
166     });
167
168     function getQueryStringParams() {
169         var params = {};
170         window.location.search.substring(1).split("&").
171             map(function(s) {
172                 var pair = s.split("=");
173                 params[decodeURIComponent(pair[0])] =
174                     typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
175             });
176         return params;
177     }
178
179     function browserSupportsHistoryApi() {
180         return document.location.protocol != "file:" &&
181           window.history && typeof window.history.pushState === "function";
182     }
183
184     function highlightSourceLines(ev) {
185         // If we're in mobile mode, we should add the sidebar in any case.
186         hideSidebar();
187         var search = document.getElementById("search");
188         var i, from, to, match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
189         if (match) {
190             from = parseInt(match[1], 10);
191             to = Math.min(50000, parseInt(match[2] || match[1], 10));
192             from = Math.min(from, to);
193             var elem = document.getElementById(from);
194             if (!elem) {
195                 return;
196             }
197             if (ev === null) {
198                 var x = document.getElementById(from);
199                 if (x) {
200                     x.scrollIntoView();
201                 }
202             }
203             onEach(document.getElementsByClassName('line-numbers'), function(e) {
204                 onEach(e.getElementsByTagName('span'), function(i_e) {
205                     removeClass(i_e, 'line-highlighted');
206                 });
207             });
208             for (i = from; i <= to; ++i) {
209                 addClass(document.getElementById(i), 'line-highlighted');
210             }
211         } else if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
212             addClass(search, "hidden");
213             removeClass(document.getElementById("main"), "hidden");
214             var hash = ev.newURL.slice(ev.newURL.indexOf('#') + 1);
215             if (browserSupportsHistoryApi()) {
216                 history.replaceState(hash, "", "?search=#" + hash);
217             }
218             var elem = document.getElementById(hash);
219             if (elem) {
220                 elem.scrollIntoView();
221             }
222         }
223     }
224
225     function expandSection(id) {
226         var elem = document.getElementById(id);
227         if (elem && isHidden(elem)) {
228             var h3 = elem.parentNode.previousSibling;
229             if (h3 && h3.tagName !== 'H3') {
230                 h3 = h3.previousSibling; // skip div.docblock
231             }
232
233             if (h3) {
234                 var collapses = h3.getElementsByClassName("collapse-toggle");
235                 if (collapses.length > 0) {
236                     // The element is not visible, we need to make it appear!
237                     collapseDocs(collapses[0], "show");
238                 }
239             }
240         }
241     }
242
243     highlightSourceLines(null);
244     window.onhashchange = highlightSourceLines;
245
246     // Gets the human-readable string for the virtual-key code of the
247     // given KeyboardEvent, ev.
248     //
249     // This function is meant as a polyfill for KeyboardEvent#key,
250     // since it is not supported in Trident.  We also test for
251     // KeyboardEvent#keyCode because the handleShortcut handler is
252     // also registered for the keydown event, because Blink doesn't fire
253     // keypress on hitting the Escape key.
254     //
255     // So I guess you could say things are getting pretty interoperable.
256     function getVirtualKey(ev) {
257         if ("key" in ev && typeof ev.key != "undefined")
258             return ev.key;
259
260         var c = ev.charCode || ev.keyCode;
261         if (c == 27)
262             return "Escape";
263         return String.fromCharCode(c);
264     }
265
266     function displayHelp(display, ev) {
267         if (display === true) {
268             if (hasClass(help, "hidden")) {
269                 ev.preventDefault();
270                 removeClass(help, "hidden");
271                 addClass(document.body, "blur");
272             }
273         } else if (!hasClass(help, "hidden")) {
274             ev.preventDefault();
275             addClass(help, "hidden");
276             removeClass(document.body, "blur");
277         }
278     }
279
280     function handleEscape(ev, help) {
281         hideModal();
282         var search = document.getElementById("search");
283         if (!hasClass(help, "hidden")) {
284             displayHelp(false, ev);
285         } else if (!hasClass(search, "hidden")) {
286             ev.preventDefault();
287             addClass(search, "hidden");
288             removeClass(document.getElementById("main"), "hidden");
289             document.title = titleBeforeSearch;
290         }
291         defocusSearchBar();
292     }
293
294     function handleShortcut(ev) {
295         // Don't interfere with browser shortcuts
296         if (ev.ctrlKey || ev.altKey || ev.metaKey) {
297             return;
298         }
299
300         var help = document.getElementById("help");
301         if (document.activeElement.tagName === "INPUT") {
302             switch (getVirtualKey(ev)) {
303             case "Escape":
304                 handleEscape(ev, help);
305                 break;
306             }
307         } else {
308             switch (getVirtualKey(ev)) {
309             case "Escape":
310                 handleEscape(ev, help);
311                 break;
312
313             case "s":
314             case "S":
315                 displayHelp(false, ev);
316                 hideModal();
317                 ev.preventDefault();
318                 focusSearchBar();
319                 break;
320
321             case "+":
322             case "-":
323                 ev.preventDefault();
324                 toggleAllDocs();
325                 break;
326
327             case "?":
328                 if (ev.shiftKey) {
329                     hideModal();
330                     displayHelp(true, ev);
331                 }
332                 break;
333             }
334         }
335     }
336
337     function findParentElement(elem, tagName) {
338         do {
339             if (elem && elem.tagName === tagName) {
340                 return elem;
341             }
342         } while (elem = elem.parentNode);
343         return null;
344     }
345
346     document.onkeypress = handleShortcut;
347     document.onkeydown = handleShortcut;
348     document.onclick = function(ev) {
349         if (hasClass(ev.target, 'collapse-toggle')) {
350             collapseDocs(ev.target, "toggle");
351         } else if (hasClass(ev.target.parentNode, 'collapse-toggle')) {
352             collapseDocs(ev.target.parentNode, "toggle");
353         } else if (ev.target.tagName === 'SPAN' && hasClass(ev.target.parentNode, 'line-numbers')) {
354             var prev_id = 0;
355
356             var set_fragment = function(name) {
357                 if (browserSupportsHistoryApi()) {
358                     history.replaceState(null, null, '#' + name);
359                     window.hashchange();
360                 } else {
361                     location.replace('#' + name);
362                 }
363             };
364
365             var cur_id = parseInt(ev.target.id, 10);
366
367             if (ev.shiftKey && prev_id) {
368                 if (prev_id > cur_id) {
369                     var tmp = prev_id;
370                     prev_id = cur_id;
371                     cur_id = tmp;
372                 }
373
374                 set_fragment(prev_id + '-' + cur_id);
375             } else {
376                 prev_id = cur_id;
377
378                 set_fragment(cur_id);
379             }
380         } else if (!hasClass(document.getElementById("help"), "hidden")) {
381             addClass(document.getElementById("help"), "hidden");
382             removeClass(document.body, "blur");
383         } else {
384             // Making a collapsed element visible on onhashchange seems
385             // too late
386             var a = findParentElement(ev.target, 'A');
387             if (a && a.hash) {
388                 expandSection(a.hash.replace(/^#/, ''));
389             }
390         }
391     };
392
393     var x = document.getElementsByClassName('version-selector');
394     if (x.length > 0) {
395         x[0].onchange = function() {
396             var i, match,
397                 url = document.location.href,
398                 stripped = '',
399                 len = rootPath.match(/\.\.\//g).length + 1;
400
401             for (i = 0; i < len; ++i) {
402                 match = url.match(/\/[^\/]*$/);
403                 if (i < len - 1) {
404                     stripped = match[0] + stripped;
405                 }
406                 url = url.substring(0, url.length - match[0].length);
407             }
408
409             url += '/' + document.getElementsByClassName('version-selector')[0].value + stripped;
410
411             document.location.href = url;
412         };
413     }
414
415     /**
416      * A function to compute the Levenshtein distance between two strings
417      * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
418      * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
419      * This code is an unmodified version of the code written by Marco de Wit
420      * and was found at http://stackoverflow.com/a/18514751/745719
421      */
422     var levenshtein_row2 = [];
423     function levenshtein(s1, s2) {
424         if (s1 === s2) {
425             return 0;
426         }
427         var s1_len = s1.length, s2_len = s2.length;
428         if (s1_len && s2_len) {
429             var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
430             while (i1 < s1_len) {
431                 row[i1] = ++i1;
432             }
433             while (i2 < s2_len) {
434                 c2 = s2.charCodeAt(i2);
435                 a = i2;
436                 ++i2;
437                 b = i2;
438                 for (i1 = 0; i1 < s1_len; ++i1) {
439                     c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
440                     a = row[i1];
441                     b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
442                     row[i1] = b;
443                 }
444             }
445             return b;
446         }
447         return s1_len + s2_len;
448     }
449
450     function initSearch(rawSearchIndex) {
451         var currentResults, index, searchIndex;
452         var MAX_LEV_DISTANCE = 3;
453         var MAX_RESULTS = 200;
454         var GENERICS_DATA = 1;
455         var NAME = 0;
456         var INPUTS_DATA = 0;
457         var OUTPUT_DATA = 1;
458         var params = getQueryStringParams();
459
460         // Populate search bar with query string search term when provided,
461         // but only if the input bar is empty. This avoid the obnoxious issue
462         // where you start trying to do a search, and the index loads, and
463         // suddenly your search is gone!
464         if (search_input.value === "") {
465             search_input.value = params.search || '';
466         }
467
468         /**
469          * Executes the query and builds an index of results
470          * @param  {[Object]} query     [The user query]
471          * @param  {[type]} searchWords [The list of search words to query
472          *                               against]
473          * @return {[type]}             [A search index of results]
474          */
475         function execQuery(query, searchWords) {
476             function itemTypeFromName(typename) {
477                 for (var i = 0; i < itemTypes.length; ++i) {
478                     if (itemTypes[i] === typename) {
479                         return i;
480                     }
481                 }
482                 return -1;
483             }
484
485             var valLower = query.query.toLowerCase(),
486                 val = valLower,
487                 typeFilter = itemTypeFromName(query.type),
488                 results = {}, results_in_args = {}, results_returned = {},
489                 split = valLower.split("::");
490
491             for (var z = 0; z < split.length; ++z) {
492                 if (split[z] === "") {
493                     split.splice(z, 1);
494                     z -= 1;
495                 }
496             }
497
498             function transformResults(results, isType) {
499                 var out = [];
500                 for (i = 0; i < results.length; ++i) {
501                     if (results[i].id > -1) {
502                         var obj = searchIndex[results[i].id];
503                         obj.lev = results[i].lev;
504                         if (isType !== true || obj.type) {
505                             var res = buildHrefAndPath(obj);
506                             obj.displayPath = pathSplitter(res[0]);
507                             obj.fullPath = obj.displayPath + obj.name;
508                             // To be sure than it some items aren't considered as duplicate.
509                             obj.fullPath += '|' + obj.ty;
510                             obj.href = res[1];
511                             out.push(obj);
512                             if (out.length >= MAX_RESULTS) {
513                                 break;
514                             }
515                         }
516                     }
517                 }
518                 return out;
519             }
520
521             function sortResults(results, isType) {
522                 var ar = [];
523                 for (var entry in results) {
524                     if (results.hasOwnProperty(entry)) {
525                         ar.push(results[entry]);
526                     }
527                 }
528                 results = ar;
529                 var nresults = results.length;
530                 for (var i = 0; i < nresults; ++i) {
531                     results[i].word = searchWords[results[i].id];
532                     results[i].item = searchIndex[results[i].id] || {};
533                 }
534                 // if there are no results then return to default and fail
535                 if (results.length === 0) {
536                     return [];
537                 }
538
539                 results.sort(function(aaa, bbb) {
540                     var a, b;
541
542                     // Sort by non levenshtein results and then levenshtein results by the distance
543                     // (less changes required to match means higher rankings)
544                     a = (aaa.lev);
545                     b = (bbb.lev);
546                     if (a !== b) { return a - b; }
547
548                     // sort by crate (non-current crate goes later)
549                     a = (aaa.item.crate !== window.currentCrate);
550                     b = (bbb.item.crate !== window.currentCrate);
551                     if (a !== b) { return a - b; }
552
553                     // sort by exact match (mismatch goes later)
554                     a = (aaa.word !== valLower);
555                     b = (bbb.word !== valLower);
556                     if (a !== b) { return a - b; }
557
558                     // sort by item name length (longer goes later)
559                     a = aaa.word.length;
560                     b = bbb.word.length;
561                     if (a !== b) { return a - b; }
562
563                     // sort by item name (lexicographically larger goes later)
564                     a = aaa.word;
565                     b = bbb.word;
566                     if (a !== b) { return (a > b ? +1 : -1); }
567
568                     // sort by index of keyword in item name (no literal occurrence goes later)
569                     a = (aaa.index < 0);
570                     b = (bbb.index < 0);
571                     if (a !== b) { return a - b; }
572                     // (later literal occurrence, if any, goes later)
573                     a = aaa.index;
574                     b = bbb.index;
575                     if (a !== b) { return a - b; }
576
577                     // special precedence for primitive and keyword pages
578                     if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
579                         (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
580                         return -1;
581                     }
582                     if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
583                         (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
584                         return 1;
585                     }
586
587                     // sort by description (no description goes later)
588                     a = (aaa.item.desc === '');
589                     b = (bbb.item.desc === '');
590                     if (a !== b) { return a - b; }
591
592                     // sort by type (later occurrence in `itemTypes` goes later)
593                     a = aaa.item.ty;
594                     b = bbb.item.ty;
595                     if (a !== b) { return a - b; }
596
597                     // sort by path (lexicographically larger goes later)
598                     a = aaa.item.path;
599                     b = bbb.item.path;
600                     if (a !== b) { return (a > b ? +1 : -1); }
601
602                     // que sera, sera
603                     return 0;
604                 });
605
606                 for (var i = 0; i < results.length; ++i) {
607                     var result = results[i];
608
609                     // this validation does not make sense when searching by types
610                     if (result.dontValidate) {
611                         continue;
612                     }
613                     var name = result.item.name.toLowerCase(),
614                         path = result.item.path.toLowerCase(),
615                         parent = result.item.parent;
616
617                     if (isType !== true &&
618                         validateResult(name, path, split, parent) === false)
619                     {
620                         result.id = -1;
621                     }
622                 }
623                 return transformResults(results);
624             }
625
626             function extractGenerics(val) {
627                 val = val.toLowerCase();
628                 if (val.indexOf('<') !== -1) {
629                     var values = val.substring(val.indexOf('<') + 1, val.lastIndexOf('>'));
630                     return {
631                         name: val.substring(0, val.indexOf('<')),
632                         generics: values.split(/\s*,\s*/),
633                     };
634                 }
635                 return {
636                     name: val,
637                     generics: [],
638                 };
639             }
640
641             function checkGenerics(obj, val) {
642                 // The names match, but we need to be sure that all generics kinda
643                 // match as well.
644                 var lev_distance = MAX_LEV_DISTANCE + 1;
645                 if (val.generics.length > 0) {
646                     if (obj.length > GENERICS_DATA &&
647                           obj[GENERICS_DATA].length >= val.generics.length) {
648                         var elems = obj[GENERICS_DATA].slice(0);
649                         var total = 0;
650                         var done = 0;
651                         // We need to find the type that matches the most to remove it in order
652                         // to move forward.
653                         for (var y = 0; y < val.generics.length; ++y) {
654                             var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
655                             for (var x = 0; x < elems.length; ++x) {
656                                 var tmp_lev = levenshtein(elems[x], val.generics[y]);
657                                 if (tmp_lev < lev.lev) {
658                                     lev.lev = tmp_lev;
659                                     lev.pos = x;
660                                 }
661                             }
662                             if (lev.pos !== -1) {
663                                 elems.splice(lev.pos, 1);
664                                 lev_distance = Math.min(lev.lev, lev_distance);
665                                 total += lev.lev;
666                                 done += 1;
667                             } else {
668                                 return MAX_LEV_DISTANCE + 1;
669                             }
670                         }
671                         return lev_distance;//Math.ceil(total / done);
672                     }
673                 }
674                 return MAX_LEV_DISTANCE + 1;
675             }
676
677             // Check for type name and type generics (if any).
678             function checkType(obj, val, literalSearch) {
679                 var lev_distance = MAX_LEV_DISTANCE + 1;
680                 if (obj[NAME] === val.name) {
681                     if (literalSearch === true) {
682                         if (val.generics && val.generics.length !== 0) {
683                             if (obj.length > GENERICS_DATA &&
684                                   obj[GENERICS_DATA].length >= val.generics.length) {
685                                 var elems = obj[GENERICS_DATA].slice(0);
686                                 var allFound = true;
687                                 var x;
688
689                                 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
690                                     allFound = false;
691                                     for (x = 0; allFound === false && x < elems.length; ++x) {
692                                         allFound = elems[x] === val.generics[y];
693                                     }
694                                     if (allFound === true) {
695                                         elems.splice(x - 1, 1);
696                                     }
697                                 }
698                                 if (allFound === true) {
699                                     return true;
700                                 }
701                             } else {
702                                 return false;
703                             }
704                         }
705                         return true;
706                     }
707                     // If the type has generics but don't match, then it won't return at this point.
708                     // Otherwise, `checkGenerics` will return 0 and it'll return.
709                     if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
710                         var tmp_lev = checkGenerics(obj, val);
711                         if (tmp_lev <= MAX_LEV_DISTANCE) {
712                             return tmp_lev;
713                         }
714                     } else {
715                         return 0;
716                     }
717                 }
718                 // Names didn't match so let's check if one of the generic types could.
719                 if (literalSearch === true) {
720                      if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
721                         for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
722                             if (obj[GENERICS_DATA][x] === val.name) {
723                                 return true;
724                             }
725                         }
726                     }
727                     return false;
728                 }
729                 var lev_distance = Math.min(levenshtein(obj[NAME], val.name),
730                                             lev_distance);
731                 if (lev_distance <= MAX_LEV_DISTANCE) {
732                     lev_distance = Math.min(checkGenerics(obj, val), lev_distance);
733                 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
734                     // We can check if the type we're looking for is inside the generics!
735                     for (var x = 0; x < obj[GENERICS_DATA].length; ++x) {
736                         lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
737                                                 lev_distance);
738                     }
739                 }
740                 // Now whatever happens, the returned distance is "less good" so we should mark it
741                 // as such, and so we add 1 to the distance to make it "less good".
742                 return lev_distance + 1;
743             }
744
745             function findArg(obj, val, literalSearch) {
746                 var lev_distance = MAX_LEV_DISTANCE + 1;
747
748                 if (obj && obj.type && obj.type[INPUTS_DATA] &&
749                       obj.type[INPUTS_DATA].length > 0) {
750                     for (var i = 0; i < obj.type[INPUTS_DATA].length; i++) {
751                         var tmp = checkType(obj.type[INPUTS_DATA][i], val, literalSearch);
752                         if (literalSearch === true && tmp === true) {
753                             return true;
754                         }
755                         lev_distance = Math.min(tmp, lev_distance);
756                         if (lev_distance === 0) {
757                             return 0;
758                         }
759                     }
760                 }
761                 return literalSearch === true ? false : lev_distance;
762             }
763
764             function checkReturned(obj, val, literalSearch) {
765                 var lev_distance = MAX_LEV_DISTANCE + 1;
766
767                 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
768                     var tmp = checkType(obj.type[OUTPUT_DATA], val, literalSearch);
769                     if (literalSearch === true && tmp === true) {
770                         return true;
771                     }
772                     lev_distance = Math.min(tmp, lev_distance);
773                     if (lev_distance === 0) {
774                         return 0;
775                     }
776                 }
777                 return literalSearch === true ? false : lev_distance;
778             }
779
780             function checkPath(contains, lastElem, ty) {
781                 if (contains.length === 0) {
782                     return 0;
783                 }
784                 var ret_lev = MAX_LEV_DISTANCE + 1;
785                 var path = ty.path.split("::");
786
787                 if (ty.parent && ty.parent.name) {
788                     path.push(ty.parent.name.toLowerCase());
789                 }
790
791                 if (contains.length > path.length) {
792                     return MAX_LEV_DISTANCE + 1;
793                 }
794                 for (var i = 0; i < path.length; ++i) {
795                     if (i + contains.length > path.length) {
796                         break;
797                     }
798                     var lev_total = 0;
799                     var aborted = false;
800                     for (var x = 0; x < contains.length; ++x) {
801                         var lev = levenshtein(path[i + x], contains[x]);
802                         if (lev > MAX_LEV_DISTANCE) {
803                             aborted = true;
804                             break;
805                         }
806                         lev_total += lev;
807                     }
808                     if (aborted === false) {
809                         ret_lev = Math.min(ret_lev, Math.round(lev_total / contains.length));
810                     }
811                 }
812                 return ret_lev;
813             }
814
815             function typePassesFilter(filter, type) {
816                 // No filter
817                 if (filter < 0) return true;
818
819                 // Exact match
820                 if (filter === type) return true;
821
822                 // Match related items
823                 var name = itemTypes[type];
824                 switch (itemTypes[filter]) {
825                     case "constant":
826                         return (name == "associatedconstant");
827                     case "fn":
828                         return (name == "method" || name == "tymethod");
829                     case "type":
830                         return (name == "primitive" || name == "keyword");
831                 }
832
833                 // No match
834                 return false;
835             }
836
837             function generateId(ty) {
838                 if (ty.parent && ty.parent.name) {
839                     return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
840                 }
841                 return itemTypes[ty.ty] + ty.path + ty.name;
842             }
843
844             // quoted values mean literal search
845             var nSearchWords = searchWords.length;
846             if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
847                 val.charAt(val.length - 1) === val.charAt(0))
848             {
849                 val = extractGenerics(val.substr(1, val.length - 2));
850                 for (var i = 0; i < nSearchWords; ++i) {
851                     var in_args = findArg(searchIndex[i], val, true);
852                     var returned = checkReturned(searchIndex[i], val, true);
853                     var ty = searchIndex[i];
854                     var fullId = generateId(ty);
855
856                     if (searchWords[i] === val.name) {
857                         // filter type: ... queries
858                         if (typePassesFilter(typeFilter, searchIndex[i].ty) &&
859                             results[fullId] === undefined)
860                         {
861                             results[fullId] = {id: i, index: -1};
862                         }
863                     } else if ((in_args === true || returned === true) &&
864                                typePassesFilter(typeFilter, searchIndex[i].ty)) {
865                         if (in_args === true || returned === true) {
866                             if (in_args === true) {
867                                 results_in_args[fullId] = {
868                                     id: i,
869                                     index: -1,
870                                     dontValidate: true,
871                                 };
872                             }
873                             if (returned === true) {
874                                 results_returned[fullId] = {
875                                     id: i,
876                                     index: -1,
877                                     dontValidate: true,
878                                 };
879                             }
880                         } else {
881                             results[fullId] = {
882                                 id: i,
883                                 index: -1,
884                                 dontValidate: true,
885                             };
886                         }
887                     }
888                 }
889                 query.inputs = [val];
890                 query.output = val;
891                 query.search = val;
892             // searching by type
893             } else if (val.search("->") > -1) {
894                 var trimmer = function(s) { return s.trim(); };
895                 var parts = val.split("->").map(trimmer);
896                 var input = parts[0];
897                 // sort inputs so that order does not matter
898                 var inputs = input.split(",").map(trimmer).sort();
899                 for (var i = 0; i < inputs.length; ++i) {
900                     inputs[i] = extractGenerics(inputs[i]);
901                 }
902                 var output = extractGenerics(parts[1]);
903
904                 for (var i = 0; i < nSearchWords; ++i) {
905                     var type = searchIndex[i].type;
906                     var ty = searchIndex[i];
907                     if (!type) {
908                         continue;
909                     }
910                     var fullId = generateId(ty);
911
912                     // allow searching for void (no output) functions as well
913                     var typeOutput = type.length > OUTPUT_DATA ? type[OUTPUT_DATA].name : "";
914                     var returned = checkReturned(ty, output, true);
915                     if (output.name === "*" || returned === true) {
916                         var in_args = false;
917                         var module = false;
918
919                         if (input === "*") {
920                             module = true;
921                         } else {
922                             var allFound = true;
923                             for (var it = 0; allFound === true && it < inputs.length; it++) {
924                                 allFound = checkType(type, inputs[it], true);
925                             }
926                             in_args = allFound;
927                         }
928                         if (in_args === true) {
929                             results_in_args[fullId] = {
930                                 id: i,
931                                 index: -1,
932                                 dontValidate: true,
933                             };
934                         }
935                         if (returned === true) {
936                             results_returned[fullId] = {
937                                 id: i,
938                                 index: -1,
939                                 dontValidate: true,
940                             };
941                         }
942                         if (module === true) {
943                             results[fullId] = {
944                                 id: i,
945                                 index: -1,
946                                 dontValidate: true,
947                             };
948                         }
949                     }
950                 }
951                 query.inputs = inputs.map(function(input) {
952                     return input.name;
953                 });
954                 query.output = output.name;
955             } else {
956                 query.inputs = [val];
957                 query.output = val;
958                 query.search = val;
959                 // gather matching search results up to a certain maximum
960                 val = val.replace(/\_/g, "");
961
962                 var valGenerics = extractGenerics(val);
963
964                 var paths = valLower.split("::");
965                 var j;
966                 for (j = 0; j < paths.length; ++j) {
967                     if (paths[j] === "") {
968                         paths.splice(j, 1);
969                         j -= 1;
970                     }
971                 }
972                 val = paths[paths.length - 1];
973                 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
974
975                 for (j = 0; j < nSearchWords; ++j) {
976                     var lev_distance;
977                     var ty = searchIndex[j];
978                     if (!ty) {
979                         continue;
980                     }
981                     var lev_add = 0;
982                     if (paths.length > 1) {
983                         var lev = checkPath(contains, paths[paths.length - 1], ty);
984                         if (lev > MAX_LEV_DISTANCE) {
985                             continue;
986                         } else if (lev > 0) {
987                             lev_add = 1;
988                         }
989                     }
990
991                     var returned = MAX_LEV_DISTANCE + 1;
992                     var in_args = MAX_LEV_DISTANCE + 1;
993                     var index = -1;
994                     // we want lev results to go lower than others
995                     var lev = MAX_LEV_DISTANCE + 1;
996                     var fullId = generateId(ty);
997
998                     if (searchWords[j].indexOf(split[i]) > -1 ||
999                         searchWords[j].indexOf(val) > -1 ||
1000                         searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1001                     {
1002                         // filter type: ... queries
1003                         if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1004                             index = searchWords[j].replace(/_/g, "").indexOf(val);
1005                         }
1006                     }
1007                     if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1008                         if (typePassesFilter(typeFilter, ty.ty) === false) {
1009                             lev = MAX_LEV_DISTANCE + 1;
1010                         } else {
1011                             lev += 1;
1012                         }
1013                     }
1014                     if ((in_args = findArg(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1015                         if (typePassesFilter(typeFilter, ty.ty) === false) {
1016                             in_args = MAX_LEV_DISTANCE + 1;
1017                         }
1018                     }
1019                     if ((returned = checkReturned(ty, valGenerics)) <= MAX_LEV_DISTANCE) {
1020                         if (typePassesFilter(typeFilter, ty.ty) === false) {
1021                             returned = MAX_LEV_DISTANCE + 1;
1022                         }
1023                     }
1024
1025                     lev += lev_add;
1026                     if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1027                         if (val.length < 6) {
1028                             lev -= 1;
1029                         } else {
1030                             lev = 0;
1031                         }
1032                     }
1033                     if (in_args <= MAX_LEV_DISTANCE) {
1034                         if (results_in_args[fullId] === undefined) {
1035                             results_in_args[fullId] = {
1036                                 id: j,
1037                                 index: index,
1038                                 lev: in_args,
1039                             };
1040                         }
1041                         results_in_args[fullId].lev =
1042                             Math.min(results_in_args[fullId].lev, in_args);
1043                     }
1044                     if (returned <= MAX_LEV_DISTANCE) {
1045                         if (results_returned[fullId] === undefined) {
1046                             results_returned[fullId] = {
1047                                 id: j,
1048                                 index: index,
1049                                 lev: returned,
1050                             };
1051                         }
1052                         results_returned[fullId].lev =
1053                             Math.min(results_returned[fullId].lev, returned);
1054                     }
1055                     if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1056                         if (index !== -1 && paths.length < 2) {
1057                             lev = 0;
1058                         }
1059                         if (results[fullId] === undefined) {
1060                             results[fullId] = {
1061                                 id: j,
1062                                 index: index,
1063                                 lev: lev,
1064                             };
1065                         }
1066                         results[fullId].lev = Math.min(results[fullId].lev, lev);
1067                     }
1068                 }
1069             }
1070
1071             var ret = {
1072                 'in_args': sortResults(results_in_args, true),
1073                 'returned': sortResults(results_returned, true),
1074                 'others': sortResults(results),
1075             };
1076             if (ALIASES && ALIASES[window.currentCrate] &&
1077                     ALIASES[window.currentCrate][query.raw]) {
1078                 var aliases = ALIASES[window.currentCrate][query.raw];
1079                 for (var i = 0; i < aliases.length; ++i) {
1080                     aliases[i].is_alias = true;
1081                     aliases[i].alias = query.raw;
1082                     aliases[i].path = aliases[i].p;
1083                     var res = buildHrefAndPath(aliases[i]);
1084                     aliases[i].displayPath = pathSplitter(res[0]);
1085                     aliases[i].fullPath = aliases[i].displayPath + aliases[i].name;
1086                     aliases[i].href = res[1];
1087                     ret['others'].unshift(aliases[i]);
1088                     if (ret['others'].length > MAX_RESULTS) {
1089                         ret['others'].pop();
1090                     }
1091                 }
1092             }
1093             return ret;
1094         }
1095
1096         /**
1097          * Validate performs the following boolean logic. For example:
1098          * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1099          * exists in (name || path || parent) OR => ("file" && "open") exists in
1100          * (name || path )
1101          *
1102          * This could be written functionally, but I wanted to minimise
1103          * functions on stack.
1104          *
1105          * @param  {[string]} name   [The name of the result]
1106          * @param  {[string]} path   [The path of the result]
1107          * @param  {[string]} keys   [The keys to be used (["file", "open"])]
1108          * @param  {[object]} parent [The parent of the result]
1109          * @return {[boolean]}       [Whether the result is valid or not]
1110          */
1111         function validateResult(name, path, keys, parent) {
1112             for (var i = 0; i < keys.length; ++i) {
1113                 // each check is for validation so we negate the conditions and invalidate
1114                 if (!(
1115                     // check for an exact name match
1116                     name.indexOf(keys[i]) > -1 ||
1117                     // then an exact path match
1118                     path.indexOf(keys[i]) > -1 ||
1119                     // next if there is a parent, check for exact parent match
1120                     (parent !== undefined &&
1121                         parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1122                     // lastly check to see if the name was a levenshtein match
1123                     levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1124                     return false;
1125                 }
1126             }
1127             return true;
1128         }
1129
1130         function getQuery(raw) {
1131             var matches, type, query;
1132             query = raw;
1133
1134             matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1135             if (matches) {
1136                 type = matches[1].replace(/^const$/, 'constant');
1137                 query = query.substring(matches[0].length);
1138             }
1139
1140             return {
1141                 raw: raw,
1142                 query: query,
1143                 type: type,
1144                 id: query + type
1145             };
1146         }
1147
1148         function initSearchNav() {
1149             var hoverTimeout;
1150
1151             var click_func = function(e) {
1152                 var el = e.target;
1153                 // to retrieve the real "owner" of the event.
1154                 while (el.tagName !== 'TR') {
1155                     el = el.parentNode;
1156                 }
1157                 var dst = e.target.getElementsByTagName('a');
1158                 if (dst.length < 1) {
1159                     return;
1160                 }
1161                 dst = dst[0];
1162                 if (window.location.pathname === dst.pathname) {
1163                     addClass(document.getElementById('search'), 'hidden');
1164                     removeClass(document.getElementById('main'), 'hidden');
1165                     document.location.href = dst.href;
1166                 }
1167             };
1168             var mouseover_func = function(e) {
1169                 var el = e.target;
1170                 // to retrieve the real "owner" of the event.
1171                 while (el.tagName !== 'TR') {
1172                     el = el.parentNode;
1173                 }
1174                 clearTimeout(hoverTimeout);
1175                 hoverTimeout = setTimeout(function() {
1176                     onEach(document.getElementsByClassName('search-results'), function(e) {
1177                         onEach(e.getElementsByClassName('result'), function(i_e) {
1178                             removeClass(i_e, 'highlighted');
1179                         });
1180                     });
1181                     addClass(el, 'highlighted');
1182                 }, 20);
1183             };
1184             onEach(document.getElementsByClassName('search-results'), function(e) {
1185                 onEach(e.getElementsByClassName('result'), function(i_e) {
1186                     i_e.onclick = click_func;
1187                     i_e.onmouseover = mouseover_func;
1188                 });
1189             });
1190
1191             search_input.onkeydown = function(e) {
1192                 // "actives" references the currently highlighted item in each search tab.
1193                 // Each array in "actives" represents a tab.
1194                 var actives = [[], [], []];
1195                 // "current" is used to know which tab we're looking into.
1196                 var current = 0;
1197                 onEach(document.getElementsByClassName('search-results'), function(e) {
1198                     onEach(e.getElementsByClassName('highlighted'), function(e) {
1199                         actives[current].push(e);
1200                     });
1201                     current += 1;
1202                 });
1203
1204                 if (e.which === 38) { // up
1205                     if (!actives[currentTab].length ||
1206                         !actives[currentTab][0].previousElementSibling) {
1207                         return;
1208                     }
1209
1210                     addClass(actives[currentTab][0].previousElementSibling, 'highlighted');
1211                     removeClass(actives[currentTab][0], 'highlighted');
1212                 } else if (e.which === 40) { // down
1213                     if (!actives[currentTab].length) {
1214                         var results = document.getElementsByClassName('search-results');
1215                         if (results.length > 0) {
1216                             var res = results[currentTab].getElementsByClassName('result');
1217                             if (res.length > 0) {
1218                                 addClass(res[0], 'highlighted');
1219                             }
1220                         }
1221                     } else if (actives[currentTab][0].nextElementSibling) {
1222                         addClass(actives[currentTab][0].nextElementSibling, 'highlighted');
1223                         removeClass(actives[currentTab][0], 'highlighted');
1224                     }
1225                 } else if (e.which === 13) { // return
1226                     if (actives[currentTab].length) {
1227                         document.location.href =
1228                             actives[currentTab][0].getElementsByTagName('a')[0].href;
1229                     }
1230                 } else if (e.which === 9) { // tab
1231                     if (e.shiftKey) {
1232                         printTab(currentTab > 0 ? currentTab - 1 : 2);
1233                     } else {
1234                         printTab(currentTab > 1 ? 0 : currentTab + 1);
1235                     }
1236                     e.preventDefault();
1237                 } else if (e.which === 16) { // shift
1238                     // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1239                 } else if (e.which === 27) { // escape
1240                     removeClass(actives[currentTab][0], 'highlighted');
1241                     search_input.value = '';
1242                     defocusSearchBar();
1243                 } else if (actives[currentTab].length > 0) {
1244                     removeClass(actives[currentTab][0], 'highlighted');
1245                 }
1246             };
1247         }
1248
1249         function buildHrefAndPath(item) {
1250             var displayPath;
1251             var href;
1252             var type = itemTypes[item.ty];
1253             var name = item.name;
1254
1255             if (type === 'mod') {
1256                 displayPath = item.path + '::';
1257                 href = rootPath + item.path.replace(/::/g, '/') + '/' +
1258                        name + '/index.html';
1259             } else if (type === "primitive" || type === "keyword") {
1260                 displayPath = "";
1261                 href = rootPath + item.path.replace(/::/g, '/') +
1262                        '/' + type + '.' + name + '.html';
1263             } else if (type === "externcrate") {
1264                 displayPath = "";
1265                 href = rootPath + name + '/index.html';
1266             } else if (item.parent !== undefined) {
1267                 var myparent = item.parent;
1268                 var anchor = '#' + type + '.' + name;
1269                 var parentType = itemTypes[myparent.ty];
1270                 if (parentType === "primitive") {
1271                     displayPath = myparent.name + '::';
1272                 } else {
1273                     displayPath = item.path + '::' + myparent.name + '::';
1274                 }
1275                 href = rootPath + item.path.replace(/::/g, '/') +
1276                        '/' + parentType +
1277                        '.' + myparent.name +
1278                        '.html' + anchor;
1279             } else {
1280                 displayPath = item.path + '::';
1281                 href = rootPath + item.path.replace(/::/g, '/') +
1282                        '/' + type + '.' + name + '.html';
1283             }
1284             return [displayPath, href];
1285         }
1286
1287         function escape(content) {
1288             var h1 = document.createElement('h1');
1289             h1.textContent = content;
1290             return h1.innerHTML;
1291         }
1292
1293         function pathSplitter(path) {
1294             var tmp = '<span>' + path.replace(/::/g, '::</span><span>');
1295             if (tmp.endsWith("<span>")) {
1296                 return tmp.slice(0, tmp.length - 6);
1297             }
1298             return tmp;
1299         }
1300
1301         function addTab(array, query, display) {
1302             var extraStyle = '';
1303             if (display === false) {
1304                 extraStyle = ' style="display: none;"';
1305             }
1306
1307             var output = '';
1308             var duplicates = {};
1309             var length = 0;
1310             if (array.length > 0) {
1311                 output = '<table class="search-results"' + extraStyle + '>';
1312
1313                 array.forEach(function(item) {
1314                     var name, type;
1315
1316                     name = item.name;
1317                     type = itemTypes[item.ty];
1318
1319                     if (item.is_alias !== true) {
1320                         if (duplicates[item.fullPath]) {
1321                             return;
1322                         }
1323                         duplicates[item.fullPath] = true;
1324                     }
1325                     length += 1;
1326
1327                     output += '<tr class="' + type + ' result"><td>' +
1328                               '<a href="' + item.href + '">' +
1329                               (item.is_alias === true ?
1330                                ('<span class="alias"><b>' + item.alias + ' </b></span><span ' +
1331                                   'class="grey"><i>&nbsp;- see&nbsp;</i></span>') : '') +
1332                               item.displayPath + '<span class="' + type + '">' +
1333                               name + '</span></a></td><td>' +
1334                               '<a href="' + item.href + '">' +
1335                               '<span class="desc">' + escape(item.desc) +
1336                               '&nbsp;</span></a></td></tr>';
1337                 });
1338                 output += '</table>';
1339             } else {
1340                 output = '<div class="search-failed"' + extraStyle + '>No results :(<br/>' +
1341                     'Try on <a href="https://duckduckgo.com/?q=' +
1342                     encodeURIComponent('rust ' + query.query) +
1343                     '">DuckDuckGo</a>?</div>';
1344             }
1345             return [output, length];
1346         }
1347
1348         function makeTabHeader(tabNb, text, nbElems) {
1349             if (currentTab === tabNb) {
1350                 return '<div class="selected">' + text +
1351                        ' <div class="count">(' + nbElems + ')</div></div>';
1352             }
1353             return '<div>' + text + ' <div class="count">(' + nbElems + ')</div></div>';
1354         }
1355
1356         function showResults(results) {
1357             if (results['others'].length === 1 &&
1358                 getCurrentValue('rustdoc-go-to-only-result') === "true") {
1359                 var elem = document.createElement('a');
1360                 elem.href = results['others'][0].href;
1361                 elem.style.display = 'none';
1362                 // For firefox, we need the element to be in the DOM so it can be clicked.
1363                 document.body.appendChild(elem);
1364                 elem.click();
1365             }
1366             var query = getQuery(search_input.value);
1367
1368             currentResults = query.id;
1369
1370             var ret_others = addTab(results['others'], query);
1371             var ret_in_args = addTab(results['in_args'], query, false);
1372             var ret_returned = addTab(results['returned'], query, false);
1373
1374             var output = '<h1>Results for ' + escape(query.query) +
1375                 (query.type ? ' (type: ' + escape(query.type) + ')' : '') + '</h1>' +
1376                 '<div id="titles">' +
1377                 makeTabHeader(0, "In Names", ret_others[1]) +
1378                 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1379                 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1380                 '</div><div id="results">' +
1381                 ret_others[0] + ret_in_args[0] + ret_returned[0] + '</div>';
1382
1383             addClass(document.getElementById('main'), 'hidden');
1384             var search = document.getElementById('search');
1385             removeClass(search, 'hidden');
1386             search.innerHTML = output;
1387             var tds = search.getElementsByTagName('td');
1388             var td_width = 0;
1389             if (tds.length > 0) {
1390                 td_width = tds[0].offsetWidth;
1391             }
1392             var width = search.offsetWidth - 40 - td_width;
1393             onEach(search.getElementsByClassName('desc'), function(e) {
1394                 e.style.width = width + 'px';
1395             });
1396             initSearchNav();
1397             var elems = document.getElementById('titles').childNodes;
1398             elems[0].onclick = function() { printTab(0); };
1399             elems[1].onclick = function() { printTab(1); };
1400             elems[2].onclick = function() { printTab(2); };
1401             printTab(currentTab);
1402         }
1403
1404         function execSearch(query, searchWords) {
1405             var queries = query.raw.split(",");
1406             var results = {
1407                 'in_args': [],
1408                 'returned': [],
1409                 'others': [],
1410             };
1411
1412             for (var i = 0; i < queries.length; ++i) {
1413                 var query = queries[i].trim();
1414                 if (query.length !== 0) {
1415                     var tmp = execQuery(getQuery(query), searchWords);
1416
1417                     results['in_args'].push(tmp['in_args']);
1418                     results['returned'].push(tmp['returned']);
1419                     results['others'].push(tmp['others']);
1420                 }
1421             }
1422             if (queries.length > 1) {
1423                 function getSmallest(arrays, positions, notDuplicates) {
1424                     var start = null;
1425
1426                     for (var it = 0; it < positions.length; ++it) {
1427                         if (arrays[it].length > positions[it] &&
1428                             (start === null || start > arrays[it][positions[it]].lev) &&
1429                             !notDuplicates[arrays[it][positions[it]].fullPath]) {
1430                             start = arrays[it][positions[it]].lev;
1431                         }
1432                     }
1433                     return start;
1434                 }
1435
1436                 function mergeArrays(arrays) {
1437                     var ret = [];
1438                     var positions = [];
1439                     var notDuplicates = {};
1440
1441                     for (var x = 0; x < arrays.length; ++x) {
1442                         positions.push(0);
1443                     }
1444                     while (ret.length < MAX_RESULTS) {
1445                         var smallest = getSmallest(arrays, positions, notDuplicates);
1446
1447                         if (smallest === null) {
1448                             break;
1449                         }
1450                         for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1451                             if (arrays[x].length > positions[x] &&
1452                                     arrays[x][positions[x]].lev === smallest &&
1453                                     !notDuplicates[arrays[x][positions[x]].fullPath]) {
1454                                 ret.push(arrays[x][positions[x]]);
1455                                 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1456                                 positions[x] += 1;
1457                             }
1458                         }
1459                     }
1460                     return ret;
1461                 }
1462
1463                 return {
1464                     'in_args': mergeArrays(results['in_args']),
1465                     'returned': mergeArrays(results['returned']),
1466                     'others': mergeArrays(results['others']),
1467                 };
1468             } else {
1469                 return {
1470                     'in_args': results['in_args'][0],
1471                     'returned': results['returned'][0],
1472                     'others': results['others'][0],
1473                 };
1474             }
1475         }
1476
1477         function search(e) {
1478             var params = getQueryStringParams();
1479             var query = getQuery(search_input.value.trim());
1480
1481             if (e) {
1482                 e.preventDefault();
1483             }
1484
1485             if (query.query.length === 0 || query.id === currentResults) {
1486                 if (query.query.length > 0) {
1487                     putBackSearch(search_input);
1488                 }
1489                 return;
1490             }
1491
1492             // Update document title to maintain a meaningful browser history
1493             document.title = "Results for " + query.query + " - Rust";
1494
1495             // Because searching is incremental by character, only the most
1496             // recent search query is added to the browser history.
1497             if (browserSupportsHistoryApi()) {
1498                 if (!history.state && !params.search) {
1499                     history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1500                 } else {
1501                     history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1502                 }
1503             }
1504
1505             showResults(execSearch(query, index));
1506         }
1507
1508         function buildIndex(rawSearchIndex) {
1509             searchIndex = [];
1510             var searchWords = [];
1511             for (var crate in rawSearchIndex) {
1512                 if (!rawSearchIndex.hasOwnProperty(crate)) { continue; }
1513
1514                 searchWords.push(crate);
1515                 searchIndex.push({
1516                     crate: crate,
1517                     ty: 1, // == ExternCrate
1518                     name: crate,
1519                     path: "",
1520                     desc: rawSearchIndex[crate].doc,
1521                     type: null,
1522                 });
1523
1524                 // an array of [(Number) item type,
1525                 //              (String) name,
1526                 //              (String) full path or empty string for previous path,
1527                 //              (String) description,
1528                 //              (Number | null) the parent path index to `paths`]
1529                 //              (Object | null) the type of the function (if any)
1530                 var items = rawSearchIndex[crate].items;
1531                 // an array of [(Number) item type,
1532                 //              (String) name]
1533                 var paths = rawSearchIndex[crate].paths;
1534
1535                 // convert `paths` into an object form
1536                 var len = paths.length;
1537                 for (var i = 0; i < len; ++i) {
1538                     paths[i] = {ty: paths[i][0], name: paths[i][1]};
1539                 }
1540
1541                 // convert `items` into an object form, and construct word indices.
1542                 //
1543                 // before any analysis is performed lets gather the search terms to
1544                 // search against apart from the rest of the data.  This is a quick
1545                 // operation that is cached for the life of the page state so that
1546                 // all other search operations have access to this cached data for
1547                 // faster analysis operations
1548                 var len = items.length;
1549                 var lastPath = "";
1550                 for (var i = 0; i < len; ++i) {
1551                     var rawRow = items[i];
1552                     var row = {crate: crate, ty: rawRow[0], name: rawRow[1],
1553                                path: rawRow[2] || lastPath, desc: rawRow[3],
1554                                parent: paths[rawRow[4]], type: rawRow[5]};
1555                     searchIndex.push(row);
1556                     if (typeof row.name === "string") {
1557                         var word = row.name.toLowerCase();
1558                         searchWords.push(word);
1559                     } else {
1560                         searchWords.push("");
1561                     }
1562                     lastPath = row.path;
1563                 }
1564             }
1565             return searchWords;
1566         }
1567
1568         function startSearch() {
1569             var searchTimeout;
1570             var callback = function() {
1571                 clearTimeout(searchTimeout);
1572                 if (search_input.value.length === 0) {
1573                     if (browserSupportsHistoryApi()) {
1574                         history.replaceState("", "std - Rust", "?search=");
1575                     }
1576                     var main = document.getElementById('main');
1577                     if (hasClass(main, 'content')) {
1578                         removeClass(main, 'hidden');
1579                     }
1580                     var search_c = document.getElementById('search');
1581                     if (hasClass(search_c, 'content')) {
1582                         addClass(search_c, 'hidden');
1583                     }
1584                 } else {
1585                     searchTimeout = setTimeout(search, 500);
1586                 }
1587             };
1588             search_input.onkeyup = callback;
1589             search_input.oninput = callback;
1590             document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1591                 e.preventDefault();
1592                 clearTimeout(searchTimeout);
1593                 search();
1594             };
1595             search_input.onchange = function(e) {
1596                 // Do NOT e.preventDefault() here. It will prevent pasting.
1597                 clearTimeout(searchTimeout);
1598                 // zero-timeout necessary here because at the time of event handler execution the
1599                 // pasted content is not in the input field yet. Shouldn’t make any difference for
1600                 // change, though.
1601                 setTimeout(search, 0);
1602             };
1603             search_input.onpaste = search_input.onchange;
1604
1605             // Push and pop states are used to add search results to the browser
1606             // history.
1607             if (browserSupportsHistoryApi()) {
1608                 // Store the previous <title> so we can revert back to it later.
1609                 var previousTitle = document.title;
1610
1611                 window.onpopstate = function(e) {
1612                     var params = getQueryStringParams();
1613                     // When browsing back from search results the main page
1614                     // visibility must be reset.
1615                     if (!params.search) {
1616                         var main = document.getElementById('main');
1617                         if (hasClass(main, 'content')) {
1618                             removeClass(main, 'hidden');
1619                         }
1620                         var search_c = document.getElementById('search');
1621                         if (hasClass(search_c, 'content')) {
1622                             addClass(search_c, 'hidden');
1623                         }
1624                     }
1625                     // Revert to the previous title manually since the History
1626                     // API ignores the title parameter.
1627                     document.title = previousTitle;
1628                     // When browsing forward to search results the previous
1629                     // search will be repeated, so the currentResults are
1630                     // cleared to ensure the search is successful.
1631                     currentResults = null;
1632                     // Synchronize search bar with query string state and
1633                     // perform the search. This will empty the bar if there's
1634                     // nothing there, which lets you really go back to a
1635                     // previous state with nothing in the bar.
1636                     if (params.search) {
1637                         search_input.value = params.search;
1638                     } else {
1639                         search_input.value = '';
1640                     }
1641                     // Some browsers fire 'onpopstate' for every page load
1642                     // (Chrome), while others fire the event only when actually
1643                     // popping a state (Firefox), which is why search() is
1644                     // called both here and at the end of the startSearch()
1645                     // function.
1646                     search();
1647                 };
1648             }
1649             search();
1650         }
1651
1652         index = buildIndex(rawSearchIndex);
1653         startSearch();
1654
1655         // Draw a convenient sidebar of known crates if we have a listing
1656         if (rootPath === '../' || rootPath === "./") {
1657             var sidebar = document.getElementsByClassName('sidebar-elems')[0];
1658             if (sidebar) {
1659                 var div = document.createElement('div');
1660                 div.className = 'block crate';
1661                 div.innerHTML = '<h3>Crates</h3>';
1662                 var ul = document.createElement('ul');
1663                 div.appendChild(ul);
1664
1665                 var crates = [];
1666                 for (var crate in rawSearchIndex) {
1667                     if (!rawSearchIndex.hasOwnProperty(crate)) {
1668                         continue;
1669                     }
1670                     crates.push(crate);
1671                 }
1672                 crates.sort();
1673                 for (var i = 0; i < crates.length; ++i) {
1674                     var klass = 'crate';
1675                     if (rootPath !== "./" && crates[i] === window.currentCrate) {
1676                         klass += ' current';
1677                     }
1678                     var link = document.createElement('a');
1679                     link.href = rootPath + crates[i] + '/index.html';
1680                     link.title = rawSearchIndex[crates[i]].doc;
1681                     link.className = klass;
1682                     link.textContent = crates[i];
1683
1684                     var li = document.createElement('li');
1685                     li.appendChild(link);
1686                     ul.appendChild(li);
1687                 }
1688                 sidebar.appendChild(div);
1689             }
1690         }
1691     }
1692
1693     window.initSearch = initSearch;
1694
1695     // delayed sidebar rendering.
1696     function initSidebarItems(items) {
1697         var sidebar = document.getElementsByClassName('sidebar-elems')[0];
1698         var current = window.sidebarCurrent;
1699
1700         function block(shortty, longty) {
1701             var filtered = items[shortty];
1702             if (!filtered) { return; }
1703
1704             var div = document.createElement('div');
1705             div.className = 'block ' + shortty;
1706             var h3 = document.createElement('h3');
1707             h3.textContent = longty;
1708             div.appendChild(h3);
1709             var ul = document.createElement('ul');
1710
1711             for (var i = 0; i < filtered.length; ++i) {
1712                 var item = filtered[i];
1713                 var name = item[0];
1714                 var desc = item[1]; // can be null
1715
1716                 var klass = shortty;
1717                 if (name === current.name && shortty === current.ty) {
1718                     klass += ' current';
1719                 }
1720                 var path;
1721                 if (shortty === 'mod') {
1722                     path = name + '/index.html';
1723                 } else {
1724                     path = shortty + '.' + name + '.html';
1725                 }
1726                 var link = document.createElement('a');
1727                 link.href = current.relpath + path;
1728                 link.title = desc;
1729                 link.className = klass;
1730                 link.textContent = name;
1731                 var li = document.createElement('li');
1732                 li.appendChild(link);
1733                 ul.appendChild(li);
1734             }
1735             div.appendChild(ul);
1736             if (sidebar) {
1737                 sidebar.appendChild(div);
1738             }
1739         }
1740
1741         block("primitive", "Primitive Types");
1742         block("mod", "Modules");
1743         block("macro", "Macros");
1744         block("struct", "Structs");
1745         block("enum", "Enums");
1746         block("union", "Unions");
1747         block("constant", "Constants");
1748         block("static", "Statics");
1749         block("trait", "Traits");
1750         block("fn", "Functions");
1751         block("type", "Type Definitions");
1752         block("foreigntype", "Foreign Types");
1753         block("keyword", "Keywords");
1754     }
1755
1756     window.initSidebarItems = initSidebarItems;
1757
1758     window.register_implementors = function(imp) {
1759         var implementors = document.getElementById('implementors-list');
1760         var synthetic_implementors = document.getElementById('synthetic-implementors-list');
1761
1762         var libs = Object.getOwnPropertyNames(imp);
1763         for (var i = 0; i < libs.length; ++i) {
1764             if (libs[i] === currentCrate) { continue; }
1765             var structs = imp[libs[i]];
1766
1767             struct_loop:
1768             for (var j = 0; j < structs.length; ++j) {
1769                 var struct = structs[j];
1770
1771                 var list = struct.synthetic ? synthetic_implementors : implementors;
1772
1773                 if (struct.synthetic) {
1774                     for (var k = 0; k < struct.types.length; k++) {
1775                         if (window.inlined_types.has(struct.types[k])) {
1776                             continue struct_loop;
1777                         }
1778                         window.inlined_types.add(struct.types[k]);
1779                     }
1780                 }
1781
1782                 var code = document.createElement('code');
1783                 code.innerHTML = struct.text;
1784
1785                 var x = code.getElementsByTagName('a');
1786                 for (var k = 0; k < x.length; k++) {
1787                     var href = x[k].getAttribute('href');
1788                     if (href && href.indexOf('http') !== 0) {
1789                         x[k].setAttribute('href', rootPath + href);
1790                     }
1791                 }
1792                 var display = document.createElement('h3');
1793                 addClass(display, "impl");
1794                 display.innerHTML = '<span class="in-band"><table class="table-display"><tbody>\
1795                     <tr><td><code>' + code.outerHTML + '</code></td><td></td></tr></tbody></table>\
1796                     </span>';
1797                 list.appendChild(display);
1798             }
1799         }
1800     };
1801     if (window.pending_implementors) {
1802         window.register_implementors(window.pending_implementors);
1803     }
1804
1805     function labelForToggleButton(sectionIsCollapsed) {
1806         if (sectionIsCollapsed) {
1807             // button will expand the section
1808             return "+";
1809         }
1810         // button will collapse the section
1811         // note that this text is also set in the HTML template in render.rs
1812         return "\u2212"; // "\u2212" is '−' minus sign
1813     }
1814
1815     function onEveryMatchingChild(elem, className, func) {
1816         if (elem && className && func) {
1817             for (var i = 0; i < elem.childNodes.length; i++) {
1818                 if (hasClass(elem.childNodes[i], className)) {
1819                     func(elem.childNodes[i]);
1820                 } else {
1821                     onEveryMatchingChild(elem.childNodes[i], className, func);
1822                 }
1823             }
1824         }
1825     }
1826
1827     function toggleAllDocs(pageId, fromAutoCollapse) {
1828         var toggle = document.getElementById("toggle-all-docs");
1829         if (!toggle) {
1830             return;
1831         }
1832         if (hasClass(toggle, "will-expand")) {
1833             updateLocalStorage("rustdoc-collapse", "false");
1834             removeClass(toggle, "will-expand");
1835             onEveryMatchingChild(toggle, "inner", function(e) {
1836                 e.innerHTML = labelForToggleButton(false);
1837             });
1838             toggle.title = "collapse all docs";
1839             if (fromAutoCollapse !== true) {
1840                 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1841                     collapseDocs(e, "show");
1842                 });
1843             }
1844         } else {
1845             updateLocalStorage("rustdoc-collapse", "true");
1846             addClass(toggle, "will-expand");
1847             onEveryMatchingChild(toggle, "inner", function(e) {
1848                 e.innerHTML = labelForToggleButton(true);
1849             });
1850             toggle.title = "expand all docs";
1851             if (fromAutoCollapse !== true) {
1852                 onEach(document.getElementsByClassName("collapse-toggle"), function(e) {
1853                     collapseDocs(e, "hide", pageId);
1854                 });
1855             }
1856         }
1857     }
1858
1859     function collapseDocs(toggle, mode, pageId) {
1860         if (!toggle || !toggle.parentNode) {
1861             return;
1862         }
1863
1864         function adjustToggle(arg) {
1865             return function(e) {
1866                 if (hasClass(e, 'toggle-label')) {
1867                     if (arg) {
1868                         e.style.display = 'inline-block';
1869                     } else {
1870                         e.style.display = 'none';
1871                     }
1872                 }
1873                 if (hasClass(e, 'inner')) {
1874                     e.innerHTML = labelForToggleButton(arg);
1875                 }
1876             };
1877         };
1878
1879         if (!hasClass(toggle.parentNode, "impl")) {
1880             var relatedDoc = toggle.parentNode.nextElementSibling;
1881             if (hasClass(relatedDoc, "stability")) {
1882                 relatedDoc = relatedDoc.nextElementSibling;
1883             }
1884             if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
1885                 var action = mode;
1886                 if (action === "toggle") {
1887                     if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
1888                         action = "show";
1889                     } else {
1890                         action = "hide";
1891                     }
1892                 }
1893                 if (action === "hide") {
1894                     addClass(relatedDoc, "hidden-by-usual-hider");
1895                     onEach(toggle.childNodes, adjustToggle(true));
1896                     addClass(toggle.parentNode, 'collapsed');
1897                 } else if (action === "show") {
1898                     removeClass(relatedDoc, "hidden-by-usual-hider");
1899                     removeClass(toggle.parentNode, 'collapsed');
1900                     onEach(toggle.childNodes, adjustToggle(false));
1901                 }
1902             }
1903         } else {
1904             // we are collapsing the impl block
1905             function implHider(addOrRemove) {
1906                 return function(n) {
1907                     var is_method = hasClass(n, "method");
1908                     if (is_method || hasClass(n, "type")) {
1909                         if (is_method === true) {
1910                             if (addOrRemove) {
1911                                 addClass(n, "hidden-by-impl-hider");
1912                             } else {
1913                                 removeClass(n, "hidden-by-impl-hider");
1914                             }
1915                         }
1916                         var ns = n.nextElementSibling;
1917                         while (true) {
1918                             if (ns && (
1919                                     hasClass(ns, "docblock") ||
1920                                     hasClass(ns, "stability"))) {
1921                                 if (addOrRemove) {
1922                                     addClass(ns, "hidden-by-impl-hider");
1923                                 } else {
1924                                     removeClass(ns, "hidden-by-impl-hider");
1925                                 }
1926                                 ns = ns.nextElementSibling;
1927                                 continue;
1928                             }
1929                             break;
1930                         }
1931                     }
1932                 }
1933             }
1934
1935             var parentElem = toggle.parentNode;
1936             var relatedDoc = parentElem;
1937             var docblock = relatedDoc.nextElementSibling;
1938
1939             while (!hasClass(relatedDoc, "impl-items")) {
1940                 relatedDoc = relatedDoc.nextElementSibling;
1941             }
1942
1943             if ((!relatedDoc && !hasClass(docblock, "docblock")) ||
1944                 (pageId && onEach(relatedDoc.childNodes, function(e) {
1945                     return e.id === pageId;
1946                 }) === true)) {
1947                 return;
1948             }
1949
1950             // Hide all functions, but not associated types/consts
1951
1952             var action = mode;
1953             if (action === "toggle") {
1954                 if (hasClass(relatedDoc, "fns-now-collapsed") ||
1955                     hasClass(docblock,  "hidden-by-impl-hider")) {
1956                     action = "show";
1957                 } else {
1958                     action = "hide";
1959                 }
1960             }
1961
1962             if (action === "show") {
1963                 removeClass(relatedDoc, "fns-now-collapsed");
1964                 removeClass(docblock, "hidden-by-usual-hider");
1965                 onEach(toggle.childNodes, adjustToggle(false));
1966                 onEach(relatedDoc.childNodes, implHider(false));
1967             } else if (action === "hide") {
1968                 addClass(relatedDoc, "fns-now-collapsed");
1969                 addClass(docblock, "hidden-by-usual-hider");
1970                 onEach(toggle.childNodes, adjustToggle(true));
1971                 onEach(relatedDoc.childNodes, implHider(true));
1972             }
1973         }
1974     }
1975
1976     function autoCollapse(pageId, collapse) {
1977         if (collapse) {
1978             toggleAllDocs(pageId, true);
1979         }
1980         var collapser = function(e) {
1981                 // inherent impl ids are like 'impl' or impl-<number>'.
1982                 // they will never be hidden by default.
1983                 var n = e.parentElement;
1984                 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
1985                     // Automatically minimize all non-inherent impls
1986                     if (collapse || hasClass(n, 'impl')) {
1987                         collapseDocs(e, "hide", pageId);
1988                     }
1989                 }
1990         };
1991         if (getCurrentValue('rustdoc-trait-implementations') !== "false") {
1992             var impl_list = document.getElementById('implementations-list');
1993
1994             if (impl_list !== null) {
1995                 onEach(impl_list.getElementsByClassName("collapse-toggle"), collapser);
1996             }
1997         }
1998         if (getCurrentValue('rustdoc-method-docs') !== "false") {
1999             var implItems = document.getElementsByClassName('impl-items');
2000
2001             if (implItems && implItems.length > 0) {
2002                 onEach(implItems, function(elem) {
2003                     onEach(elem.getElementsByClassName("collapse-toggle"), collapser);
2004                 });
2005             }
2006         }
2007     }
2008
2009     var x = document.getElementById('toggle-all-docs');
2010     if (x) {
2011         x.onclick = toggleAllDocs;
2012     }
2013
2014     function insertAfter(newNode, referenceNode) {
2015         referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2016     }
2017
2018     function checkIfThereAreMethods(elems) {
2019         var areThereMethods = false;
2020
2021         onEach(elems, function(e) {
2022             if (hasClass(e, "method")) {
2023                 areThereMethods = true;
2024                 return true;
2025             }
2026         });
2027         return areThereMethods;
2028     }
2029
2030     var toggle = document.createElement('a');
2031     toggle.href = 'javascript:void(0)';
2032     toggle.className = 'collapse-toggle';
2033     toggle.innerHTML = "[<span class='inner'>" + labelForToggleButton(false) + "</span>]";
2034
2035     var func = function(e) {
2036         var next = e.nextElementSibling;
2037         if (hasClass(e, 'impl') && next && hasClass(next, 'docblock')) {
2038             next = next.nextElementSibling;
2039         }
2040         if (!next) {
2041             return;
2042         }
2043         if ((hasClass(e, 'method') || hasClass(e, 'associatedconstant') ||
2044              checkIfThereAreMethods(next.childNodes)) &&
2045             (hasClass(next, 'docblock') ||
2046              hasClass(e, 'impl') ||
2047              (hasClass(next, 'stability') &&
2048               hasClass(next.nextElementSibling, 'docblock')))) {
2049             insertAfter(toggle.cloneNode(true), e.childNodes[e.childNodes.length - 1]);
2050         }
2051     };
2052     onEach(document.getElementsByClassName('method'), func);
2053     onEach(document.getElementsByClassName('associatedconstant'), func);
2054     onEach(document.getElementsByClassName('impl'), func);
2055
2056     function createToggle(otherMessage, fontSize, extraClass, show) {
2057         var span = document.createElement('span');
2058         span.className = 'toggle-label';
2059         if (show) {
2060             span.style.display = 'none';
2061         }
2062         if (!otherMessage) {
2063             span.innerHTML = '&nbsp;Expand&nbsp;description';
2064         } else {
2065             span.innerHTML = otherMessage;
2066         }
2067
2068         if (fontSize) {
2069             span.style.fontSize = fontSize;
2070         }
2071
2072         var mainToggle = toggle.cloneNode(true);
2073         mainToggle.appendChild(span);
2074
2075         var wrapper = document.createElement('div');
2076         wrapper.className = 'toggle-wrapper';
2077         if (!show) {
2078             addClass(wrapper, 'collapsed');
2079             var inner = mainToggle.getElementsByClassName('inner');
2080             if (inner && inner.length > 0) {
2081                 inner[0].innerHTML = '+';
2082             }
2083         }
2084         if (extraClass) {
2085             addClass(wrapper, extraClass);
2086         }
2087         wrapper.appendChild(mainToggle);
2088         return wrapper;
2089     }
2090
2091     var hideItemDeclarations = getCurrentValue('rustdoc-item-declarations') === "false";
2092     function buildToggleWrapper(e) {
2093         if (hasClass(e, 'autohide')) {
2094             var wrap = e.previousElementSibling;
2095             if (wrap && hasClass(wrap, 'toggle-wrapper')) {
2096                 var toggle = wrap.childNodes[0];
2097                 var extra = e.childNodes[0].tagName === 'H3';
2098
2099                 e.style.display = 'none';
2100                 addClass(wrap, 'collapsed');
2101                 onEach(toggle.getElementsByClassName('inner'), function(e) {
2102                     e.innerHTML = labelForToggleButton(true);
2103                 });
2104                 onEach(toggle.getElementsByClassName('toggle-label'), function(e) {
2105                     e.style.display = 'inline-block';
2106                     if (extra === true) {
2107                         i_e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2108                     }
2109                 });
2110             }
2111         }
2112         if (e.parentNode.id === "main") {
2113             var otherMessage = '';
2114             var fontSize;
2115             var extraClass;
2116
2117             if (hasClass(e, "type-decl")) {
2118                 fontSize = "20px";
2119                 otherMessage = '&nbsp;Show&nbsp;declaration';
2120                 if (hideItemDeclarations === false) {
2121                     extraClass = 'collapsed';
2122                 }
2123             } else if (hasClass(e, "sub-variant")) {
2124                 otherMessage = '&nbsp;Show&nbsp;fields';
2125             } else if (hasClass(e, "non-exhaustive")) {
2126                 otherMessage = '&nbsp;This&nbsp;';
2127                 if (hasClass(e, "non-exhaustive-struct")) {
2128                     otherMessage += 'struct';
2129                 } else if (hasClass(e, "non-exhaustive-enum")) {
2130                     otherMessage += 'enum';
2131                 } else if (hasClass(e, "non-exhaustive-type")) {
2132                     otherMessage += 'type';
2133                 }
2134                 otherMessage += '&nbsp;is&nbsp;marked&nbsp;as&nbsp;non-exhaustive';
2135             } else if (hasClass(e.childNodes[0], "impl-items")) {
2136                 extraClass = "marg-left";
2137             }
2138
2139             e.parentNode.insertBefore(createToggle(otherMessage,
2140                                                    fontSize,
2141                                                    extraClass,
2142                                                    hideItemDeclarations),
2143                                       e);
2144             if (otherMessage.length > 0 && hideItemDeclarations === true) {
2145                 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2146             }
2147         }
2148     }
2149
2150     onEach(document.getElementsByClassName('docblock'), buildToggleWrapper);
2151     onEach(document.getElementsByClassName('sub-variant'), buildToggleWrapper);
2152
2153     function createToggleWrapper(tog) {
2154         var span = document.createElement('span');
2155         span.className = 'toggle-label';
2156         span.style.display = 'none';
2157         span.innerHTML = '&nbsp;Expand&nbsp;attributes';
2158         tog.appendChild(span);
2159
2160         var wrapper = document.createElement('div');
2161         wrapper.className = 'toggle-wrapper toggle-attributes';
2162         wrapper.appendChild(tog);
2163         return wrapper;
2164     }
2165
2166     // In the search display, allows to switch between tabs.
2167     function printTab(nb) {
2168         if (nb === 0 || nb === 1 || nb === 2) {
2169             currentTab = nb;
2170         }
2171         var nb_copy = nb;
2172         onEach(document.getElementById('titles').childNodes, function(elem) {
2173             if (nb_copy === 0) {
2174                 addClass(elem, 'selected');
2175             } else {
2176                 removeClass(elem, 'selected');
2177             }
2178             nb_copy -= 1;
2179         });
2180         onEach(document.getElementById('results').childNodes, function(elem) {
2181             if (nb === 0) {
2182                 elem.style.display = '';
2183             } else {
2184                 elem.style.display = 'none';
2185             }
2186             nb -= 1;
2187         });
2188     }
2189
2190     // To avoid checking on "rustdoc-item-attributes" value on every loop...
2191     var itemAttributesFunc = function() {};
2192     if (getCurrentValue("rustdoc-item-attributes") !== "false") {
2193         itemAttributesFunc = function(x) {
2194             collapseDocs(x.previousSibling.childNodes[0], "toggle");
2195         };
2196     }
2197     onEach(document.getElementById('main').getElementsByClassName('attributes'), function(i_e) {
2198         i_e.parentNode.insertBefore(createToggleWrapper(toggle.cloneNode(true)), i_e);
2199         itemAttributesFunc(i_e);
2200     });
2201
2202     // To avoid checking on "rustdoc-line-numbers" value on every loop...
2203     var lineNumbersFunc = function() {};
2204     if (getCurrentValue("rustdoc-line-numbers") === "true") {
2205         lineNumbersFunc = function(x) {
2206             var count = x.textContent.split('\n').length;
2207             var elems = [];
2208             for (var i = 0; i < count; ++i) {
2209                 elems.push(i + 1);
2210             }
2211             var node = document.createElement('pre');
2212             addClass(node, 'line-number');
2213             node.innerHTML = elems.join('\n');
2214             x.parentNode.insertBefore(node, x);
2215         };
2216     }
2217     onEach(document.getElementsByClassName('rust-example-rendered'), function(e) {
2218         if (hasClass(e, 'compile_fail')) {
2219             e.addEventListener("mouseover", function(event) {
2220                 e.previousElementSibling.childNodes[0].style.color = '#f00';
2221             });
2222             e.addEventListener("mouseout", function(event) {
2223                 e.previousElementSibling.childNodes[0].style.color = '';
2224             });
2225         } else if (hasClass(e, 'ignore')) {
2226             e.addEventListener("mouseover", function(event) {
2227                 e.previousElementSibling.childNodes[0].style.color = '#ff9200';
2228             });
2229             e.addEventListener("mouseout", function(event) {
2230                 e.previousElementSibling.childNodes[0].style.color = '';
2231             });
2232         }
2233         lineNumbersFunc(e);
2234     });
2235
2236     function showModal(content) {
2237         var modal = document.createElement('div');
2238         modal.id = "important";
2239         addClass(modal, 'modal');
2240         modal.innerHTML = '<div class="modal-content"><div class="close" id="modal-close">✕</div>' +
2241                           '<div class="whiter"></div><span class="docblock">' + content +
2242                           '</span></div>';
2243         document.getElementsByTagName('body')[0].appendChild(modal);
2244         document.getElementById('modal-close').onclick = hideModal;
2245         modal.onclick = hideModal;
2246     }
2247
2248     function hideModal() {
2249         var modal = document.getElementById("important");
2250         if (modal) {
2251             modal.parentNode.removeChild(modal);
2252         }
2253     }
2254
2255     onEach(document.getElementsByClassName('important-traits'), function(e) {
2256         e.onclick = function() {
2257             showModal(e.lastElementChild.innerHTML);
2258         };
2259     });
2260
2261     function putBackSearch(search_input) {
2262         if (search_input.value !== "") {
2263             addClass(document.getElementById("main"), "hidden");
2264             removeClass(document.getElementById("search"), "hidden");
2265             if (browserSupportsHistoryApi()) {
2266                 history.replaceState(search_input.value,
2267                                      "",
2268                                      "?search=" + encodeURIComponent(search_input.value));
2269             }
2270         }
2271     }
2272
2273     if (search_input) {
2274         search_input.onfocus = function() {
2275             putBackSearch(this);
2276         };
2277     }
2278
2279     var params = getQueryStringParams();
2280     if (params && params.search) {
2281         addClass(document.getElementById("main"), "hidden");
2282         var search = document.getElementById("search");
2283         removeClass(search, "hidden");
2284         search.innerHTML = '<h3 style="text-align: center;">Loading search results...</h3>';
2285     }
2286
2287     var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2288     if (sidebar_menu) {
2289         sidebar_menu.onclick = function() {
2290             var sidebar = document.getElementsByClassName('sidebar')[0];
2291             if (hasClass(sidebar, "mobile") === true) {
2292                 hideSidebar();
2293             } else {
2294                 showSidebar();
2295             }
2296         };
2297     }
2298
2299     window.onresize = function() {
2300         hideSidebar();
2301     };
2302
2303     autoCollapse(getPageId(), getCurrentValue("rustdoc-collapse") === "true");
2304
2305     if (window.location.hash && window.location.hash.length > 0) {
2306         expandSection(window.location.hash.replace(/^#/, ''));
2307     }
2308 }());
2309
2310 // Sets the focus on the search bar at the top of the page
2311 function focusSearchBar() {
2312     document.getElementsByClassName('search-input')[0].focus();
2313 }
2314
2315 // Removes the focus from the search bar
2316 function defocusSearchBar() {
2317     document.getElementsByClassName('search-input')[0].blur();
2318 }