2 /* global ALIASES, currentCrate, rootPath */
4 // Local js definitions:
5 /* global addClass, getCurrentValue, hasClass */
6 /* global onEachLazy, hasOwnProperty, removeClass, updateLocalStorage */
7 /* global hideThemeButtonState, showThemeButtonState */
9 if (!String.prototype.startsWith) {
10 String.prototype.startsWith = function(searchString, position) {
11 position = position || 0;
12 return this.indexOf(searchString, position) === position;
15 if (!String.prototype.endsWith) {
16 String.prototype.endsWith = function(suffix, length) {
17 var l = length || this.length;
18 return this.indexOf(suffix, l - suffix.length) !== -1;
22 if (!DOMTokenList.prototype.add) {
23 DOMTokenList.prototype.add = function(className) {
24 if (className && !hasClass(this, className)) {
25 if (this.className && this.className.length > 0) {
26 this.className += " " + className;
28 this.className = className;
34 if (!DOMTokenList.prototype.remove) {
35 DOMTokenList.prototype.remove = function(className) {
36 if (className && this.className) {
37 this.className = (" " + this.className + " ").replace(" " + className + " ", " ")
43 function getSearchInput() {
44 return document.getElementsByClassName("search-input")[0];
47 function getSearchElement() {
48 return document.getElementById("search");
51 function getThemesElement() {
52 return document.getElementById("theme-choices");
55 function getThemePickerElement() {
56 return document.getElementById("theme-picker");
59 // Sets the focus on the search bar at the top of the page
60 function focusSearchBar() {
61 getSearchInput().focus();
64 // Removes the focus from the search bar
65 function defocusSearchBar() {
66 getSearchInput().blur();
72 // This mapping table should match the discriminants of
73 // `rustdoc::html::item_type::ItemType` type in Rust.
74 var itemTypes = ["mod",
101 var disableShortcuts = getSettingValue("disable-shortcuts") === "true";
102 var search_input = getSearchInput();
103 var searchTimeout = null;
104 var toggleAllDocsId = "toggle-all-docs";
106 // On the search screen, so you remain on the last tab you opened.
109 // 1 for "In Parameters"
110 // 2 for "In Return Types"
113 var mouseMovedAfterSearch = true;
115 var titleBeforeSearch = document.title;
116 var searchTitle = null;
118 function clearInputTimeout() {
119 if (searchTimeout !== null) {
120 clearTimeout(searchTimeout);
121 searchTimeout = null;
125 function getPageId() {
126 if (window.location.hash) {
127 var tmp = window.location.hash.replace(/^#/, "");
128 if (tmp.length > 0) {
135 function showSidebar() {
136 var elems = document.getElementsByClassName("sidebar-elems")[0];
138 addClass(elems, "show-it");
140 var sidebar = document.getElementsByClassName("sidebar")[0];
142 addClass(sidebar, "mobile");
143 var filler = document.getElementById("sidebar-filler");
145 var div = document.createElement("div");
146 div.id = "sidebar-filler";
147 sidebar.appendChild(div);
152 function hideSidebar() {
153 var elems = document.getElementsByClassName("sidebar-elems")[0];
155 removeClass(elems, "show-it");
157 var sidebar = document.getElementsByClassName("sidebar")[0];
158 removeClass(sidebar, "mobile");
159 var filler = document.getElementById("sidebar-filler");
163 document.getElementsByTagName("body")[0].style.marginTop = "";
166 function showSearchResults(search) {
167 if (search === null || typeof search === 'undefined') {
168 search = getSearchElement();
170 addClass(main, "hidden");
171 removeClass(search, "hidden");
172 mouseMovedAfterSearch = false;
173 document.title = searchTitle;
176 function hideSearchResults(search) {
177 if (search === null || typeof search === 'undefined') {
178 search = getSearchElement();
180 addClass(search, "hidden");
181 removeClass(main, "hidden");
182 document.title = titleBeforeSearch;
185 // used for special search precedence
186 var TY_PRIMITIVE = itemTypes.indexOf("primitive");
187 var TY_KEYWORD = itemTypes.indexOf("keyword");
189 function getQueryStringParams() {
191 window.location.search.substring(1).split("&").
193 var pair = s.split("=");
194 params[decodeURIComponent(pair[0])] =
195 typeof pair[1] === "undefined" ? null : decodeURIComponent(pair[1]);
200 function browserSupportsHistoryApi() {
201 return window.history && typeof window.history.pushState === "function";
204 function isHidden(elem) {
205 return elem.offsetHeight === 0;
208 var main = document.getElementById("main");
211 function handleHashes(ev) {
213 var search = getSearchElement();
214 if (ev !== null && search && !hasClass(search, "hidden") && ev.newURL) {
215 // This block occurs when clicking on an element in the navbar while
217 hideSearchResults(search);
218 var hash = ev.newURL.slice(ev.newURL.indexOf("#") + 1);
219 if (browserSupportsHistoryApi()) {
220 history.replaceState(hash, "", "?search=#" + hash);
222 elem = document.getElementById(hash);
224 elem.scrollIntoView();
227 // This part is used in case an element is not visible.
228 if (savedHash !== window.location.hash) {
229 savedHash = window.location.hash;
230 if (savedHash.length === 0) {
233 elem = document.getElementById(savedHash.slice(1)); // we remove the '#'
234 if (!elem || !isHidden(elem)) {
237 var parent = elem.parentNode;
238 if (parent && hasClass(parent, "impl-items")) {
239 // In case this is a trait implementation item, we first need to toggle
240 // the "Show hidden undocumented items".
241 onEachLazy(parent.getElementsByClassName("collapsed"), function(e) {
242 if (e.parentNode === parent) {
243 // Only click on the toggle we're looking for.
248 if (isHidden(elem)) {
249 // The whole parent is collapsed. We need to click on its toggle as well!
250 if (hasClass(parent.lastElementChild, "collapse-toggle")) {
251 parent.lastElementChild.click();
258 function highlightSourceLines(match, ev) {
259 if (typeof match === "undefined") {
260 // If we're in mobile mode, we should hide the sidebar in any case.
262 match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
267 var from = parseInt(match[1], 10);
269 if (typeof match[2] !== "undefined") {
270 to = parseInt(match[2], 10);
277 var elem = document.getElementById(from);
282 var x = document.getElementById(from);
287 onEachLazy(document.getElementsByClassName("line-numbers"), function(e) {
288 onEachLazy(e.getElementsByTagName("span"), function(i_e) {
289 removeClass(i_e, "line-highlighted");
292 for (var i = from; i <= to; ++i) {
293 elem = document.getElementById(i);
297 addClass(elem, "line-highlighted");
301 function onHashChange(ev) {
302 // If we're in mobile mode, we should hide the sidebar in any case.
304 var match = window.location.hash.match(/^#?(\d+)(?:-(\d+))?$/);
306 return highlightSourceLines(match, ev);
311 function expandSection(id) {
312 var elem = document.getElementById(id);
313 if (elem && isHidden(elem)) {
314 var h3 = elem.parentNode.previousElementSibling;
315 if (h3 && h3.tagName !== "H3") {
316 h3 = h3.previousElementSibling; // skip div.docblock
320 var collapses = h3.getElementsByClassName("collapse-toggle");
321 if (collapses.length > 0) {
322 // The element is not visible, we need to make it appear!
323 collapseDocs(collapses[0], "show");
329 // Gets the human-readable string for the virtual-key code of the
330 // given KeyboardEvent, ev.
332 // This function is meant as a polyfill for KeyboardEvent#key,
333 // since it is not supported in Trident. We also test for
334 // KeyboardEvent#keyCode because the handleShortcut handler is
335 // also registered for the keydown event, because Blink doesn't fire
336 // keypress on hitting the Escape key.
338 // So I guess you could say things are getting pretty interoperable.
339 function getVirtualKey(ev) {
340 if ("key" in ev && typeof ev.key != "undefined") {
344 var c = ev.charCode || ev.keyCode;
348 return String.fromCharCode(c);
351 function getHelpElement() {
353 return document.getElementById("help");
356 function displayHelp(display, ev, help) {
357 help = help ? help : getHelpElement();
358 if (display === true) {
359 if (hasClass(help, "hidden")) {
361 removeClass(help, "hidden");
362 addClass(document.body, "blur");
364 } else if (hasClass(help, "hidden") === false) {
366 addClass(help, "hidden");
367 removeClass(document.body, "blur");
371 function handleEscape(ev) {
372 var help = getHelpElement();
373 var search = getSearchElement();
374 if (hasClass(help, "hidden") === false) {
375 displayHelp(false, ev, help);
376 } else if (hasClass(search, "hidden") === false) {
379 hideSearchResults(search);
382 hideThemeButtonState();
385 function handleShortcut(ev) {
386 // Don't interfere with browser shortcuts
387 if (ev.ctrlKey || ev.altKey || ev.metaKey || disableShortcuts === true) {
391 if (document.activeElement.tagName === "INPUT") {
392 switch (getVirtualKey(ev)) {
398 switch (getVirtualKey(ev)) {
405 displayHelp(false, ev);
417 displayHelp(true, ev);
421 var themePicker = getThemePickerElement();
422 if (themePicker.parentNode.contains(ev.target)) {
423 handleThemeKeyDown(ev);
429 function handleThemeKeyDown(ev) {
430 var active = document.activeElement;
431 var themes = getThemesElement();
432 switch (getVirtualKey(ev)) {
435 if (active.previousElementSibling && ev.target.id !== "theme-picker") {
436 active.previousElementSibling.focus();
438 showThemeButtonState();
439 themes.lastElementChild.focus();
444 if (active.nextElementSibling && ev.target.id !== "theme-picker") {
445 active.nextElementSibling.focus();
447 showThemeButtonState();
448 themes.firstElementChild.focus();
454 if (ev.target.id === "theme-picker" && themes.style.display === "none") {
456 showThemeButtonState();
457 themes.firstElementChild.focus();
462 themes.firstElementChild.focus();
466 themes.lastElementChild.focus();
468 // The escape key is handled in handleEscape, not here,
469 // so that pressing escape will close the menu even if it isn't focused
473 function findParentElement(elem, tagName) {
475 if (elem && elem.tagName === tagName) {
478 elem = elem.parentNode;
483 document.addEventListener("keypress", handleShortcut);
484 document.addEventListener("keydown", handleShortcut);
486 function resetMouseMoved(ev) {
487 mouseMovedAfterSearch = true;
490 document.addEventListener("mousemove", resetMouseMoved);
492 var handleSourceHighlight = (function() {
493 var prev_line_id = 0;
495 var set_fragment = function(name) {
496 var x = window.scrollX,
498 if (browserSupportsHistoryApi()) {
499 history.replaceState(null, null, "#" + name);
500 highlightSourceLines();
502 location.replace("#" + name);
504 // Prevent jumps when selecting one or many lines
505 window.scrollTo(x, y);
508 return function(ev) {
509 var cur_line_id = parseInt(ev.target.id, 10);
512 if (ev.shiftKey && prev_line_id) {
513 // Swap selection if needed
514 if (prev_line_id > cur_line_id) {
515 var tmp = prev_line_id;
516 prev_line_id = cur_line_id;
520 set_fragment(prev_line_id + "-" + cur_line_id);
522 prev_line_id = cur_line_id;
524 set_fragment(cur_line_id);
529 document.addEventListener("click", function(ev) {
530 if (hasClass(ev.target, "help-button")) {
531 displayHelp(true, ev);
532 } else if (hasClass(ev.target, "collapse-toggle")) {
533 collapseDocs(ev.target, "toggle");
534 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
535 collapseDocs(ev.target.parentNode, "toggle");
536 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
537 handleSourceHighlight(ev);
538 } else if (hasClass(getHelpElement(), "hidden") === false) {
539 var help = getHelpElement();
540 var is_inside_help_popup = ev.target !== help && help.contains(ev.target);
541 if (is_inside_help_popup === false) {
542 addClass(help, "hidden");
543 removeClass(document.body, "blur");
546 // Making a collapsed element visible on onhashchange seems
548 var a = findParentElement(ev.target, "A");
550 expandSection(a.hash.replace(/^#/, ""));
556 var x = document.getElementsByClassName("version-selector");
558 x[0].onchange = function() {
560 url = document.location.href,
562 len = rootPath.match(/\.\.\//g).length + 1;
564 for (i = 0; i < len; ++i) {
565 match = url.match(/\/[^\/]*$/);
567 stripped = match[0] + stripped;
569 url = url.substring(0, url.length - match[0].length);
572 var selectedVersion = document.getElementsByClassName("version-selector")[0].value;
573 url += "/" + selectedVersion + stripped;
575 document.location.href = url;
581 * A function to compute the Levenshtein distance between two strings
582 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
583 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
584 * This code is an unmodified version of the code written by Marco de Wit
585 * and was found at http://stackoverflow.com/a/18514751/745719
587 var levenshtein_row2 = [];
588 function levenshtein(s1, s2) {
592 var s1_len = s1.length, s2_len = s2.length;
593 if (s1_len && s2_len) {
594 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
595 while (i1 < s1_len) {
598 while (i2 < s2_len) {
599 c2 = s2.charCodeAt(i2);
603 for (i1 = 0; i1 < s1_len; ++i1) {
604 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
606 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
612 return s1_len + s2_len;
615 window.initSearch = function(rawSearchIndex) {
616 var MAX_LEV_DISTANCE = 3;
617 var MAX_RESULTS = 200;
618 var GENERICS_DATA = 1;
622 var NO_TYPE_FILTER = -1;
623 var currentResults, index, searchIndex;
625 var params = getQueryStringParams();
627 // Populate search bar with query string search term when provided,
628 // but only if the input bar is empty. This avoid the obnoxious issue
629 // where you start trying to do a search, and the index loads, and
630 // suddenly your search is gone!
631 if (search_input.value === "") {
632 search_input.value = params.search || "";
636 * Executes the query and builds an index of results
637 * @param {[Object]} query [The user query]
638 * @param {[type]} searchWords [The list of search words to query
640 * @param {[type]} filterCrates [Crate to search in if defined]
641 * @return {[type]} [A search index of results]
643 function execQuery(query, searchWords, filterCrates) {
644 function itemTypeFromName(typename) {
645 var length = itemTypes.length;
646 for (var i = 0; i < length; ++i) {
647 if (itemTypes[i] === typename) {
651 return NO_TYPE_FILTER;
654 var valLower = query.query.toLowerCase(),
656 typeFilter = itemTypeFromName(query.type),
657 results = {}, results_in_args = {}, results_returned = {},
658 split = valLower.split("::");
660 var length = split.length;
661 for (var z = 0; z < length; ++z) {
662 if (split[z] === "") {
668 function transformResults(results, isType) {
670 var length = results.length;
671 for (var i = 0; i < length; ++i) {
672 if (results[i].id > -1) {
673 var obj = searchIndex[results[i].id];
674 obj.lev = results[i].lev;
675 if (isType !== true || obj.type) {
676 var res = buildHrefAndPath(obj);
677 obj.displayPath = pathSplitter(res[0]);
678 obj.fullPath = obj.displayPath + obj.name;
679 // To be sure than it some items aren't considered as duplicate.
680 obj.fullPath += "|" + obj.ty;
683 if (out.length >= MAX_RESULTS) {
692 function sortResults(results, isType) {
694 for (var entry in results) {
695 if (hasOwnProperty(results, entry)) {
696 ar.push(results[entry]);
701 var nresults = results.length;
702 for (i = 0; i < nresults; ++i) {
703 results[i].word = searchWords[results[i].id];
704 results[i].item = searchIndex[results[i].id] || {};
706 // if there are no results then return to default and fail
707 if (results.length === 0) {
711 results.sort(function(aaa, bbb) {
714 // sort by exact match with regard to the last word (mismatch goes later)
715 a = (aaa.word !== val);
716 b = (bbb.word !== val);
717 if (a !== b) { return a - b; }
719 // Sort by non levenshtein results and then levenshtein results by the distance
720 // (less changes required to match means higher rankings)
723 if (a !== b) { return a - b; }
725 // sort by crate (non-current crate goes later)
726 a = (aaa.item.crate !== window.currentCrate);
727 b = (bbb.item.crate !== window.currentCrate);
728 if (a !== b) { return a - b; }
730 // sort by item name length (longer goes later)
733 if (a !== b) { return a - b; }
735 // sort by item name (lexicographically larger goes later)
738 if (a !== b) { return (a > b ? +1 : -1); }
740 // sort by index of keyword in item name (no literal occurrence goes later)
743 if (a !== b) { return a - b; }
744 // (later literal occurrence, if any, goes later)
747 if (a !== b) { return a - b; }
749 // special precedence for primitive and keyword pages
750 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
751 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
754 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
755 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
759 // sort by description (no description goes later)
760 a = (aaa.item.desc === "");
761 b = (bbb.item.desc === "");
762 if (a !== b) { return a - b; }
764 // sort by type (later occurrence in `itemTypes` goes later)
767 if (a !== b) { return a - b; }
769 // sort by path (lexicographically larger goes later)
772 if (a !== b) { return (a > b ? +1 : -1); }
778 var length = results.length;
779 for (i = 0; i < length; ++i) {
780 var result = results[i];
782 // this validation does not make sense when searching by types
783 if (result.dontValidate) {
786 var name = result.item.name.toLowerCase(),
787 path = result.item.path.toLowerCase(),
788 parent = result.item.parent;
790 if (isType !== true &&
791 validateResult(name, path, split, parent) === false)
796 return transformResults(results);
799 function extractGenerics(val) {
800 val = val.toLowerCase();
801 if (val.indexOf("<") !== -1) {
802 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
804 name: val.substring(0, val.indexOf("<")),
805 generics: values.split(/\s*,\s*/),
814 function getObjectFromId(id) {
815 if (typeof id === "number") {
816 return searchIndex[id];
821 function checkGenerics(obj, val) {
822 // The names match, but we need to be sure that all generics kinda
824 var lev_distance = MAX_LEV_DISTANCE + 1;
825 if (val.generics.length > 0) {
826 if (obj.length > GENERICS_DATA &&
827 obj[GENERICS_DATA].length >= val.generics.length) {
828 var elems = obj[GENERICS_DATA].slice(0);
831 // We need to find the type that matches the most to remove it in order
833 var vlength = val.generics.length;
834 for (var y = 0; y < vlength; ++y) {
835 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
836 var elength = elems.length;
837 var firstGeneric = getObjectFromId(val.generics[y]).name;
838 for (var x = 0; x < elength; ++x) {
839 var tmp_lev = levenshtein(getObjectFromId(elems[x]).name,
841 if (tmp_lev < lev.lev) {
846 if (lev.pos !== -1) {
847 elems.splice(lev.pos, 1);
848 lev_distance = Math.min(lev.lev, lev_distance);
852 return MAX_LEV_DISTANCE + 1;
855 return Math.ceil(total / done);
858 return MAX_LEV_DISTANCE + 1;
861 // Check for type name and type generics (if any).
862 function checkType(obj, val, literalSearch) {
863 var lev_distance = MAX_LEV_DISTANCE + 1;
865 if (obj[NAME] === val.name) {
866 if (literalSearch === true) {
867 if (val.generics && val.generics.length !== 0) {
868 if (obj.length > GENERICS_DATA &&
869 obj[GENERICS_DATA].length >= val.generics.length) {
870 var elems = obj[GENERICS_DATA].slice(0);
873 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
875 var firstGeneric = getObjectFromId(val.generics[y]).name;
876 for (x = 0; allFound === false && x < elems.length; ++x) {
877 allFound = getObjectFromId(elems[x]).name === firstGeneric;
879 if (allFound === true) {
880 elems.splice(x - 1, 1);
883 if (allFound === true) {
892 // If the type has generics but don't match, then it won't return at this point.
893 // Otherwise, `checkGenerics` will return 0 and it'll return.
894 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
895 var tmp_lev = checkGenerics(obj, val);
896 if (tmp_lev <= MAX_LEV_DISTANCE) {
903 // Names didn't match so let's check if one of the generic types could.
904 if (literalSearch === true) {
905 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
906 var length = obj[GENERICS_DATA].length;
907 for (x = 0; x < length; ++x) {
908 if (obj[GENERICS_DATA][x] === val.name) {
915 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
916 if (lev_distance <= MAX_LEV_DISTANCE) {
917 // The generics didn't match but the name kinda did so we give it
918 // a levenshtein distance value that isn't *this* good so it goes
919 // into the search results but not too high.
920 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
921 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
922 // We can check if the type we're looking for is inside the generics!
923 var olength = obj[GENERICS_DATA].length;
924 for (x = 0; x < olength; ++x) {
925 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
929 // Now whatever happens, the returned distance is "less good" so we should mark it
930 // as such, and so we add 1 to the distance to make it "less good".
931 return lev_distance + 1;
934 function findArg(obj, val, literalSearch, typeFilter) {
935 var lev_distance = MAX_LEV_DISTANCE + 1;
937 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
938 var length = obj.type[INPUTS_DATA].length;
939 for (var i = 0; i < length; i++) {
940 var tmp = obj.type[INPUTS_DATA][i];
941 if (typePassesFilter(typeFilter, tmp[1]) === false) {
944 tmp = checkType(tmp, val, literalSearch);
945 if (literalSearch === true) {
951 lev_distance = Math.min(tmp, lev_distance);
952 if (lev_distance === 0) {
957 return literalSearch === true ? false : lev_distance;
960 function checkReturned(obj, val, literalSearch, typeFilter) {
961 var lev_distance = MAX_LEV_DISTANCE + 1;
963 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
964 var ret = obj.type[OUTPUT_DATA];
965 if (typeof ret[0] === "string") {
968 for (var x = 0; x < ret.length; ++x) {
970 if (typePassesFilter(typeFilter, tmp[1]) === false) {
973 tmp = checkType(tmp, val, literalSearch);
974 if (literalSearch === true) {
980 lev_distance = Math.min(tmp, lev_distance);
981 if (lev_distance === 0) {
986 return literalSearch === true ? false : lev_distance;
989 function checkPath(contains, lastElem, ty) {
990 if (contains.length === 0) {
993 var ret_lev = MAX_LEV_DISTANCE + 1;
994 var path = ty.path.split("::");
996 if (ty.parent && ty.parent.name) {
997 path.push(ty.parent.name.toLowerCase());
1000 var length = path.length;
1001 var clength = contains.length;
1002 if (clength > length) {
1003 return MAX_LEV_DISTANCE + 1;
1005 for (var i = 0; i < length; ++i) {
1006 if (i + clength > length) {
1010 var aborted = false;
1011 for (var x = 0; x < clength; ++x) {
1012 var lev = levenshtein(path[i + x], contains[x]);
1013 if (lev > MAX_LEV_DISTANCE) {
1019 if (aborted === false) {
1020 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
1026 function typePassesFilter(filter, type) {
1028 if (filter <= NO_TYPE_FILTER) return true;
1031 if (filter === type) return true;
1033 // Match related items
1034 var name = itemTypes[type];
1035 switch (itemTypes[filter]) {
1037 return name === "associatedconstant";
1039 return name === "method" || name === "tymethod";
1041 return name === "primitive" || name === "associatedtype";
1043 return name === "traitalias";
1050 function generateId(ty) {
1051 if (ty.parent && ty.parent.name) {
1052 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
1054 return itemTypes[ty.ty] + ty.path + ty.name;
1057 function createAliasFromItem(item) {
1064 parent: item.parent,
1070 function handleAliases(ret, query, filterCrates) {
1071 // We separate aliases and crate aliases because we want to have current crate
1072 // aliases to be before the others in the displayed results.
1074 var crateAliases = [];
1076 if (filterCrates !== undefined) {
1077 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
1078 for (i = 0; i < ALIASES[filterCrates][query.search].length; ++i) {
1080 createAliasFromItem(
1081 searchIndex[ALIASES[filterCrates][query.search][i]]));
1085 Object.keys(ALIASES).forEach(function(crate) {
1086 if (ALIASES[crate][query.search]) {
1087 var pushTo = crate === window.currentCrate ? crateAliases : aliases;
1088 for (i = 0; i < ALIASES[crate][query.search].length; ++i) {
1090 createAliasFromItem(
1091 searchIndex[ALIASES[crate][query.search][i]]));
1097 var sortFunc = function(aaa, bbb) {
1098 if (aaa.path < bbb.path) {
1100 } else if (aaa.path === bbb.path) {
1105 crateAliases.sort(sortFunc);
1106 aliases.sort(sortFunc);
1108 var pushFunc = function(alias) {
1109 alias.alias = query.raw;
1110 var res = buildHrefAndPath(alias);
1111 alias.displayPath = pathSplitter(res[0]);
1112 alias.fullPath = alias.displayPath + alias.name;
1113 alias.href = res[1];
1115 ret.others.unshift(alias);
1116 if (ret.others.length > MAX_RESULTS) {
1120 onEach(aliases, pushFunc);
1121 onEach(crateAliases, pushFunc);
1124 // quoted values mean literal search
1125 var nSearchWords = searchWords.length;
1131 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
1132 val.charAt(val.length - 1) === val.charAt(0))
1134 val = extractGenerics(val.substr(1, val.length - 2));
1135 for (i = 0; i < nSearchWords; ++i) {
1136 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1139 in_args = findArg(searchIndex[i], val, true, typeFilter);
1140 returned = checkReturned(searchIndex[i], val, true, typeFilter);
1141 ty = searchIndex[i];
1142 fullId = generateId(ty);
1144 if (searchWords[i] === val.name
1145 && typePassesFilter(typeFilter, searchIndex[i].ty)
1146 && results[fullId] === undefined) {
1153 if (in_args === true && results_in_args[fullId] === undefined) {
1154 results_in_args[fullId] = {
1160 if (returned === true && results_returned[fullId] === undefined) {
1161 results_returned[fullId] = {
1168 query.inputs = [val];
1171 // searching by type
1172 } else if (val.search("->") > -1) {
1173 var trimmer = function(s) { return s.trim(); };
1174 var parts = val.split("->").map(trimmer);
1175 var input = parts[0];
1176 // sort inputs so that order does not matter
1177 var inputs = input.split(",").map(trimmer).sort();
1178 for (i = 0; i < inputs.length; ++i) {
1179 inputs[i] = extractGenerics(inputs[i]);
1181 var output = extractGenerics(parts[1]);
1183 for (i = 0; i < nSearchWords; ++i) {
1184 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1187 var type = searchIndex[i].type;
1188 ty = searchIndex[i];
1192 fullId = generateId(ty);
1194 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
1195 if (output.name === "*" || returned === true) {
1197 var is_module = false;
1199 if (input === "*") {
1202 var allFound = true;
1203 for (var it = 0; allFound === true && it < inputs.length; it++) {
1204 allFound = checkType(type, inputs[it], true);
1208 if (in_args === true) {
1209 results_in_args[fullId] = {
1215 if (returned === true) {
1216 results_returned[fullId] = {
1222 if (is_module === true) {
1231 query.inputs = inputs.map(function(input) {
1234 query.output = output.name;
1236 query.inputs = [val];
1239 // gather matching search results up to a certain maximum
1240 val = val.replace(/\_/g, "");
1242 var valGenerics = extractGenerics(val);
1244 var paths = valLower.split("::");
1246 for (j = 0; j < paths.length; ++j) {
1247 if (paths[j] === "") {
1252 val = paths[paths.length - 1];
1253 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
1256 for (j = 0; j < nSearchWords; ++j) {
1257 ty = searchIndex[j];
1258 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
1262 if (paths.length > 1) {
1263 lev = checkPath(contains, paths[paths.length - 1], ty);
1264 if (lev > MAX_LEV_DISTANCE) {
1266 } else if (lev > 0) {
1271 returned = MAX_LEV_DISTANCE + 1;
1272 in_args = MAX_LEV_DISTANCE + 1;
1274 // we want lev results to go lower than others
1275 lev = MAX_LEV_DISTANCE + 1;
1276 fullId = generateId(ty);
1278 if (searchWords[j].indexOf(split[i]) > -1 ||
1279 searchWords[j].indexOf(val) > -1 ||
1280 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1282 // filter type: ... queries
1283 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1284 index = searchWords[j].replace(/_/g, "").indexOf(val);
1287 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1288 if (typePassesFilter(typeFilter, ty.ty) === false) {
1289 lev = MAX_LEV_DISTANCE + 1;
1294 in_args = findArg(ty, valGenerics, false, typeFilter);
1295 returned = checkReturned(ty, valGenerics, false, typeFilter);
1298 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1299 if (val.length < 6) {
1305 if (in_args <= MAX_LEV_DISTANCE) {
1306 if (results_in_args[fullId] === undefined) {
1307 results_in_args[fullId] = {
1313 results_in_args[fullId].lev =
1314 Math.min(results_in_args[fullId].lev, in_args);
1316 if (returned <= MAX_LEV_DISTANCE) {
1317 if (results_returned[fullId] === undefined) {
1318 results_returned[fullId] = {
1324 results_returned[fullId].lev =
1325 Math.min(results_returned[fullId].lev, returned);
1327 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1328 if (index !== -1 && paths.length < 2) {
1331 if (results[fullId] === undefined) {
1338 results[fullId].lev = Math.min(results[fullId].lev, lev);
1344 "in_args": sortResults(results_in_args, true),
1345 "returned": sortResults(results_returned, true),
1346 "others": sortResults(results),
1348 handleAliases(ret, query, filterCrates);
1353 * Validate performs the following boolean logic. For example:
1354 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1355 * exists in (name || path || parent) OR => ("file" && "open") exists in
1358 * This could be written functionally, but I wanted to minimise
1359 * functions on stack.
1361 * @param {[string]} name [The name of the result]
1362 * @param {[string]} path [The path of the result]
1363 * @param {[string]} keys [The keys to be used (["file", "open"])]
1364 * @param {[object]} parent [The parent of the result]
1365 * @return {[boolean]} [Whether the result is valid or not]
1367 function validateResult(name, path, keys, parent) {
1368 for (var i = 0; i < keys.length; ++i) {
1369 // each check is for validation so we negate the conditions and invalidate
1371 // check for an exact name match
1372 name.indexOf(keys[i]) > -1 ||
1373 // then an exact path match
1374 path.indexOf(keys[i]) > -1 ||
1375 // next if there is a parent, check for exact parent match
1376 (parent !== undefined && parent.name !== undefined &&
1377 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1378 // lastly check to see if the name was a levenshtein match
1379 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1386 function getQuery(raw) {
1387 var matches, type, query;
1390 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1392 type = matches[1].replace(/^const$/, "constant");
1393 query = query.substring(matches[0].length);
1404 function initSearchNav() {
1407 var click_func = function(e) {
1409 // to retrieve the real "owner" of the event.
1410 while (el.tagName !== "TR") {
1413 var dst = e.target.getElementsByTagName("a");
1414 if (dst.length < 1) {
1418 if (window.location.pathname === dst.pathname) {
1419 hideSearchResults();
1420 document.location.href = dst.href;
1423 var mouseover_func = function(e) {
1424 if (mouseMovedAfterSearch) {
1426 // to retrieve the real "owner" of the event.
1427 while (el.tagName !== "TR") {
1430 clearTimeout(hoverTimeout);
1431 hoverTimeout = setTimeout(function() {
1432 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1433 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1434 removeClass(i_e, "highlighted");
1437 addClass(el, "highlighted");
1441 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1442 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1443 i_e.onclick = click_func;
1444 i_e.onmouseover = mouseover_func;
1448 search_input.onkeydown = function(e) {
1449 // "actives" references the currently highlighted item in each search tab.
1450 // Each array in "actives" represents a tab.
1451 var actives = [[], [], []];
1452 // "current" is used to know which tab we're looking into.
1454 onEachLazy(document.getElementById("results").childNodes, function(e) {
1455 onEachLazy(e.getElementsByClassName("highlighted"), function(h_e) {
1456 actives[current].push(h_e);
1461 if (e.which === 38) { // up
1462 if (!actives[currentTab].length ||
1463 !actives[currentTab][0].previousElementSibling) {
1467 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1468 removeClass(actives[currentTab][0], "highlighted");
1470 } else if (e.which === 40) { // down
1471 if (!actives[currentTab].length) {
1472 var results = document.getElementById("results").childNodes;
1473 if (results.length > 0) {
1474 var res = results[currentTab].getElementsByClassName("result");
1475 if (res.length > 0) {
1476 addClass(res[0], "highlighted");
1479 } else if (actives[currentTab][0].nextElementSibling) {
1480 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1481 removeClass(actives[currentTab][0], "highlighted");
1484 } else if (e.which === 13) { // return
1485 if (actives[currentTab].length) {
1486 document.location.href =
1487 actives[currentTab][0].getElementsByTagName("a")[0].href;
1489 } else if (e.which === 9) { // tab
1491 printTab(currentTab > 0 ? currentTab - 1 : 2);
1493 printTab(currentTab > 1 ? 0 : currentTab + 1);
1496 } else if (e.which === 16) { // shift
1497 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1498 } else if (actives[currentTab].length > 0) {
1499 removeClass(actives[currentTab][0], "highlighted");
1504 function buildHrefAndPath(item) {
1507 var type = itemTypes[item.ty];
1508 var name = item.name;
1509 var path = item.path;
1511 if (type === "mod") {
1512 displayPath = path + "::";
1513 href = rootPath + path.replace(/::/g, "/") + "/" +
1514 name + "/index.html";
1515 } else if (type === "primitive" || type === "keyword") {
1517 href = rootPath + path.replace(/::/g, "/") +
1518 "/" + type + "." + name + ".html";
1519 } else if (type === "externcrate") {
1521 href = rootPath + name + "/index.html";
1522 } else if (item.parent !== undefined) {
1523 var myparent = item.parent;
1524 var anchor = "#" + type + "." + name;
1525 var parentType = itemTypes[myparent.ty];
1526 var pageType = parentType;
1527 var pageName = myparent.name;
1529 if (parentType === "primitive") {
1530 displayPath = myparent.name + "::";
1531 } else if (type === "structfield" && parentType === "variant") {
1532 // Structfields belonging to variants are special: the
1533 // final path element is the enum name.
1534 var splitPath = item.path.split("::");
1535 var enumName = splitPath.pop();
1536 path = splitPath.join("::");
1537 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
1538 anchor = "#variant." + myparent.name + ".field." + name;
1540 pageName = enumName;
1542 displayPath = path + "::" + myparent.name + "::";
1544 href = rootPath + path.replace(/::/g, "/") +
1549 displayPath = item.path + "::";
1550 href = rootPath + item.path.replace(/::/g, "/") +
1551 "/" + type + "." + name + ".html";
1553 return [displayPath, href];
1556 function escape(content) {
1557 var h1 = document.createElement("h1");
1558 h1.textContent = content;
1559 return h1.innerHTML;
1562 function pathSplitter(path) {
1563 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1564 if (tmp.endsWith("<span>")) {
1565 return tmp.slice(0, tmp.length - 6);
1570 function addTab(array, query, display) {
1571 var extraStyle = "";
1572 if (display === false) {
1573 extraStyle = " style=\"display: none;\"";
1577 var duplicates = {};
1579 if (array.length > 0) {
1580 output = "<table class=\"search-results\"" + extraStyle + ">";
1582 array.forEach(function(item) {
1586 type = itemTypes[item.ty];
1588 if (item.is_alias !== true) {
1589 if (duplicates[item.fullPath]) {
1592 duplicates[item.fullPath] = true;
1596 output += "<tr class=\"" + type + " result\"><td>" +
1597 "<a href=\"" + item.href + "\">" +
1598 (item.is_alias === true ?
1599 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1600 "class=\"grey\"><i> - see </i></span>") : "") +
1601 item.displayPath + "<span class=\"" + type + "\">" +
1602 name + "</span></a></td><td>" +
1603 "<a href=\"" + item.href + "\">" +
1604 "<span class=\"desc\">" + escape(item.desc) +
1605 " </span></a></td></tr>";
1607 output += "</table>";
1609 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1610 "Try on <a href=\"https://duckduckgo.com/?q=" +
1611 encodeURIComponent("rust " + query.query) +
1612 "\">DuckDuckGo</a>?<br/><br/>" +
1613 "Or try looking in one of these:<ul><li>The <a " +
1614 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1615 " for technical details about the language.</li><li><a " +
1616 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1617 "Example</a> for expository code examples.</a></li><li>The <a " +
1618 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1619 "introductions to language features and the language itself.</li><li><a " +
1620 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1621 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1623 return [output, length];
1626 function makeTabHeader(tabNb, text, nbElems) {
1627 if (currentTab === tabNb) {
1628 return "<div class=\"selected\">" + text +
1629 " <div class=\"count\">(" + nbElems + ")</div></div>";
1631 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1634 function showResults(results) {
1635 var search = getSearchElement();
1636 if (results.others.length === 1
1637 && getSettingValue("go-to-only-result") === "true"
1638 // By default, the search DOM element is "empty" (meaning it has no children not
1639 // text content). Once a search has been run, it won't be empty, even if you press
1640 // ESC or empty the search input (which also "cancels" the search).
1641 && (!search.firstChild || search.firstChild.innerText !== getSearchLoadingText()))
1643 var elem = document.createElement("a");
1644 elem.href = results.others[0].href;
1645 elem.style.display = "none";
1646 // For firefox, we need the element to be in the DOM so it can be clicked.
1647 document.body.appendChild(elem);
1651 var query = getQuery(search_input.value);
1653 currentResults = query.id;
1655 var ret_others = addTab(results.others, query);
1656 var ret_in_args = addTab(results.in_args, query, false);
1657 var ret_returned = addTab(results.returned, query, false);
1659 var output = "<h1>Results for " + escape(query.query) +
1660 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1661 "<div id=\"titles\">" +
1662 makeTabHeader(0, "In Names", ret_others[1]) +
1663 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1664 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1665 "</div><div id=\"results\">" +
1666 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1668 search.innerHTML = output;
1669 showSearchResults(search);
1670 var tds = search.getElementsByTagName("td");
1672 if (tds.length > 0) {
1673 td_width = tds[0].offsetWidth;
1675 var width = search.offsetWidth - 40 - td_width;
1676 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1677 e.style.width = width + "px";
1680 var elems = document.getElementById("titles").childNodes;
1681 elems[0].onclick = function() { printTab(0); };
1682 elems[1].onclick = function() { printTab(1); };
1683 elems[2].onclick = function() { printTab(2); };
1684 printTab(currentTab);
1687 function execSearch(query, searchWords, filterCrates) {
1688 function getSmallest(arrays, positions, notDuplicates) {
1691 for (var it = 0; it < positions.length; ++it) {
1692 if (arrays[it].length > positions[it] &&
1693 (start === null || start > arrays[it][positions[it]].lev) &&
1694 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1695 start = arrays[it][positions[it]].lev;
1701 function mergeArrays(arrays) {
1704 var notDuplicates = {};
1706 for (var x = 0; x < arrays.length; ++x) {
1709 while (ret.length < MAX_RESULTS) {
1710 var smallest = getSmallest(arrays, positions, notDuplicates);
1712 if (smallest === null) {
1715 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1716 if (arrays[x].length > positions[x] &&
1717 arrays[x][positions[x]].lev === smallest &&
1718 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1719 ret.push(arrays[x][positions[x]]);
1720 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1728 var queries = query.raw.split(",");
1735 for (var i = 0; i < queries.length; ++i) {
1736 query = queries[i].trim();
1737 if (query.length !== 0) {
1738 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1740 results.in_args.push(tmp.in_args);
1741 results.returned.push(tmp.returned);
1742 results.others.push(tmp.others);
1745 if (queries.length > 1) {
1747 "in_args": mergeArrays(results.in_args),
1748 "returned": mergeArrays(results.returned),
1749 "others": mergeArrays(results.others),
1753 "in_args": results.in_args[0],
1754 "returned": results.returned[0],
1755 "others": results.others[0],
1759 function getFilterCrates() {
1760 var elem = document.getElementById("crate-search");
1762 if (elem && elem.value !== "All crates" && hasOwnProperty(rawSearchIndex, elem.value)) {
1768 function search(e, forced) {
1769 var params = getQueryStringParams();
1770 var query = getQuery(search_input.value.trim());
1776 if (query.query.length === 0) {
1779 if (forced !== true && query.id === currentResults) {
1780 if (query.query.length > 0) {
1781 putBackSearch(search_input);
1786 // Update document title to maintain a meaningful browser history
1787 searchTitle = "Results for " + query.query + " - Rust";
1789 // Because searching is incremental by character, only the most
1790 // recent search query is added to the browser history.
1791 if (browserSupportsHistoryApi()) {
1792 if (!history.state && !params.search) {
1793 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1795 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1799 var filterCrates = getFilterCrates();
1800 showResults(execSearch(query, index, filterCrates));
1803 function buildIndex(rawSearchIndex) {
1805 var searchWords = [];
1807 var currentIndex = 0;
1809 for (var crate in rawSearchIndex) {
1810 if (!hasOwnProperty(rawSearchIndex, crate)) { continue; }
1814 searchWords.push(crate);
1817 ty: 1, // == ExternCrate
1820 desc: rawSearchIndex[crate].doc,
1825 // an array of [(Number) item type,
1827 // (String) full path or empty string for previous path,
1828 // (String) description,
1829 // (Number | null) the parent path index to `paths`]
1830 // (Object | null) the type of the function (if any)
1831 var items = rawSearchIndex[crate].i;
1832 // an array of [(Number) item type,
1834 var paths = rawSearchIndex[crate].p;
1835 // a array of [(String) alias name
1836 // [Number] index to items]
1837 var aliases = rawSearchIndex[crate].a;
1839 // convert `rawPaths` entries into object form
1840 var len = paths.length;
1841 for (i = 0; i < len; ++i) {
1842 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1845 // convert `items` into an object form, and construct word indices.
1847 // before any analysis is performed lets gather the search terms to
1848 // search against apart from the rest of the data. This is a quick
1849 // operation that is cached for the life of the page state so that
1850 // all other search operations have access to this cached data for
1851 // faster analysis operations
1854 for (i = 0; i < len; ++i) {
1855 var rawRow = items[i];
1857 rawRow[2] = lastPath;
1865 parent: paths[rawRow[4]],
1868 searchIndex.push(row);
1869 if (typeof row.name === "string") {
1870 var word = row.name.toLowerCase();
1871 searchWords.push(word);
1873 searchWords.push("");
1875 lastPath = row.path;
1880 ALIASES[crate] = {};
1881 var j, local_aliases;
1882 for (var alias_name in aliases) {
1883 if (!aliases.hasOwnProperty(alias_name)) { continue; }
1885 if (!ALIASES[crate].hasOwnProperty(alias_name)) {
1886 ALIASES[crate][alias_name] = [];
1888 local_aliases = aliases[alias_name];
1889 for (j = 0; j < local_aliases.length; ++j) {
1890 ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1894 currentIndex += crateSize;
1899 function startSearch() {
1900 var callback = function() {
1901 clearInputTimeout();
1902 if (search_input.value.length === 0) {
1903 if (browserSupportsHistoryApi()) {
1904 history.replaceState("", window.currentCrate + " - Rust", "?search=");
1906 hideSearchResults();
1908 searchTimeout = setTimeout(search, 500);
1911 search_input.onkeyup = callback;
1912 search_input.oninput = callback;
1913 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1915 clearInputTimeout();
1918 search_input.onchange = function(e) {
1919 if (e.target !== document.activeElement) {
1920 // To prevent doing anything when it's from a blur event.
1923 // Do NOT e.preventDefault() here. It will prevent pasting.
1924 clearInputTimeout();
1925 // zero-timeout necessary here because at the time of event handler execution the
1926 // pasted content is not in the input field yet. Shouldn’t make any difference for
1928 setTimeout(search, 0);
1930 search_input.onpaste = search_input.onchange;
1932 var selectCrate = document.getElementById("crate-search");
1934 selectCrate.onchange = function() {
1935 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1936 search(undefined, true);
1940 // Push and pop states are used to add search results to the browser
1942 if (browserSupportsHistoryApi()) {
1943 // Store the previous <title> so we can revert back to it later.
1944 var previousTitle = document.title;
1946 window.addEventListener("popstate", function(e) {
1947 var params = getQueryStringParams();
1948 // Revert to the previous title manually since the History
1949 // API ignores the title parameter.
1950 document.title = previousTitle;
1951 // When browsing forward to search results the previous
1952 // search will be repeated, so the currentResults are
1953 // cleared to ensure the search is successful.
1954 currentResults = null;
1955 // Synchronize search bar with query string state and
1956 // perform the search. This will empty the bar if there's
1957 // nothing there, which lets you really go back to a
1958 // previous state with nothing in the bar.
1959 if (params.search && params.search.length > 0) {
1960 search_input.value = params.search;
1961 // Some browsers fire "onpopstate" for every page load
1962 // (Chrome), while others fire the event only when actually
1963 // popping a state (Firefox), which is why search() is
1964 // called both here and at the end of the startSearch()
1968 search_input.value = "";
1969 // When browsing back from search results the main page
1970 // visibility must be reset.
1971 hideSearchResults();
1978 index = buildIndex(rawSearchIndex);
1981 // Draw a convenient sidebar of known crates if we have a listing
1982 if (rootPath === "../" || rootPath === "./") {
1983 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1985 var div = document.createElement("div");
1986 div.className = "block crate";
1987 div.innerHTML = "<h3>Crates</h3>";
1988 var ul = document.createElement("ul");
1989 div.appendChild(ul);
1992 for (var crate in rawSearchIndex) {
1993 if (!hasOwnProperty(rawSearchIndex, crate)) {
1999 for (var i = 0; i < crates.length; ++i) {
2000 var klass = "crate";
2001 if (rootPath !== "./" && crates[i] === window.currentCrate) {
2002 klass += " current";
2004 var link = document.createElement("a");
2005 link.href = rootPath + crates[i] + "/index.html";
2006 link.title = rawSearchIndex[crates[i]].doc;
2007 link.className = klass;
2008 link.textContent = crates[i];
2010 var li = document.createElement("li");
2011 li.appendChild(link);
2014 sidebar.appendChild(div);
2020 // delayed sidebar rendering.
2021 window.initSidebarItems = function(items) {
2022 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
2023 var current = window.sidebarCurrent;
2025 function block(shortty, longty) {
2026 var filtered = items[shortty];
2031 var div = document.createElement("div");
2032 div.className = "block " + shortty;
2033 var h3 = document.createElement("h3");
2034 h3.textContent = longty;
2035 div.appendChild(h3);
2036 var ul = document.createElement("ul");
2038 var length = filtered.length;
2039 for (var i = 0; i < length; ++i) {
2040 var item = filtered[i];
2042 var desc = item[1]; // can be null
2044 var klass = shortty;
2045 if (name === current.name && shortty === current.ty) {
2046 klass += " current";
2049 if (shortty === "mod") {
2050 path = name + "/index.html";
2052 path = shortty + "." + name + ".html";
2054 var link = document.createElement("a");
2055 link.href = current.relpath + path;
2057 link.className = klass;
2058 link.textContent = name;
2059 var li = document.createElement("li");
2060 li.appendChild(link);
2063 div.appendChild(ul);
2065 sidebar.appendChild(div);
2069 block("primitive", "Primitive Types");
2070 block("mod", "Modules");
2071 block("macro", "Macros");
2072 block("struct", "Structs");
2073 block("enum", "Enums");
2074 block("union", "Unions");
2075 block("constant", "Constants");
2076 block("static", "Statics");
2077 block("trait", "Traits");
2078 block("fn", "Functions");
2079 block("type", "Type Definitions");
2080 block("foreigntype", "Foreign Types");
2081 block("keyword", "Keywords");
2082 block("traitalias", "Trait Aliases");
2085 window.register_implementors = function(imp) {
2086 var implementors = document.getElementById("implementors-list");
2087 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
2089 if (synthetic_implementors) {
2090 // This `inlined_types` variable is used to avoid having the same implementation
2091 // showing up twice. For example "String" in the "Sync" doc page.
2093 // By the way, this is only used by and useful for traits implemented automatically
2094 // (like "Send" and "Sync").
2095 var inlined_types = new Set();
2096 onEachLazy(synthetic_implementors.getElementsByClassName("impl"), function(el) {
2097 var aliases = el.getAttribute("aliases");
2101 aliases.split(",").forEach(function(alias) {
2102 inlined_types.add(alias);
2107 var libs = Object.getOwnPropertyNames(imp);
2108 var llength = libs.length;
2109 for (var i = 0; i < llength; ++i) {
2110 if (libs[i] === currentCrate) { continue; }
2111 var structs = imp[libs[i]];
2113 var slength = structs.length;
2115 for (var j = 0; j < slength; ++j) {
2116 var struct = structs[j];
2118 var list = struct.synthetic ? synthetic_implementors : implementors;
2120 if (struct.synthetic) {
2121 var stlength = struct.types.length;
2122 for (var k = 0; k < stlength; k++) {
2123 if (inlined_types.has(struct.types[k])) {
2124 continue struct_loop;
2126 inlined_types.add(struct.types[k]);
2130 var code = document.createElement("code");
2131 code.innerHTML = struct.text;
2133 var x = code.getElementsByTagName("a");
2134 var xlength = x.length;
2135 for (var it = 0; it < xlength; it++) {
2136 var href = x[it].getAttribute("href");
2137 if (href && href.indexOf("http") !== 0) {
2138 x[it].setAttribute("href", rootPath + href);
2141 var display = document.createElement("h3");
2142 addClass(display, "impl");
2143 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
2144 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
2145 "</tbody></table></span>";
2146 list.appendChild(display);
2150 if (window.pending_implementors) {
2151 window.register_implementors(window.pending_implementors);
2154 function labelForToggleButton(sectionIsCollapsed) {
2155 if (sectionIsCollapsed) {
2156 // button will expand the section
2159 // button will collapse the section
2160 // note that this text is also set in the HTML template in render.rs
2161 return "\u2212"; // "\u2212" is "−" minus sign
2164 function onEveryMatchingChild(elem, className, func) {
2165 if (elem && className && func) {
2166 var length = elem.childNodes.length;
2167 var nodes = elem.childNodes;
2168 for (var i = 0; i < length; ++i) {
2169 if (hasClass(nodes[i], className)) {
2172 onEveryMatchingChild(nodes[i], className, func);
2178 function toggleAllDocs(pageId, fromAutoCollapse) {
2179 var innerToggle = document.getElementById(toggleAllDocsId);
2183 if (hasClass(innerToggle, "will-expand")) {
2184 updateLocalStorage("rustdoc-collapse", "false");
2185 removeClass(innerToggle, "will-expand");
2186 onEveryMatchingChild(innerToggle, "inner", function(e) {
2187 e.innerHTML = labelForToggleButton(false);
2189 innerToggle.title = "collapse all docs";
2190 if (fromAutoCollapse !== true) {
2191 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2192 collapseDocs(e, "show");
2196 updateLocalStorage("rustdoc-collapse", "true");
2197 addClass(innerToggle, "will-expand");
2198 onEveryMatchingChild(innerToggle, "inner", function(e) {
2199 var parent = e.parentNode;
2200 var superParent = null;
2203 superParent = parent.parentNode;
2205 if (!parent || !superParent || superParent.id !== "main" ||
2206 hasClass(parent, "impl") === false) {
2207 e.innerHTML = labelForToggleButton(true);
2210 innerToggle.title = "expand all docs";
2211 if (fromAutoCollapse !== true) {
2212 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2213 var parent = e.parentNode;
2214 var superParent = null;
2217 superParent = parent.parentNode;
2219 if (!parent || !superParent || superParent.id !== "main" ||
2220 hasClass(parent, "impl") === false) {
2221 collapseDocs(e, "hide", pageId);
2228 function collapseDocs(toggle, mode, pageId) {
2229 if (!toggle || !toggle.parentNode) {
2233 function adjustToggle(arg) {
2234 return function(e) {
2235 if (hasClass(e, "toggle-label")) {
2237 e.style.display = "inline-block";
2239 e.style.display = "none";
2242 if (hasClass(e, "inner")) {
2243 e.innerHTML = labelForToggleButton(arg);
2248 function implHider(addOrRemove, fullHide) {
2249 return function(n) {
2250 var is_method = hasClass(n, "method") || fullHide;
2251 if (is_method || hasClass(n, "type")) {
2252 if (is_method === true) {
2254 addClass(n, "hidden-by-impl-hider");
2256 removeClass(n, "hidden-by-impl-hider");
2259 var ns = n.nextElementSibling;
2260 while (ns && (hasClass(ns, "docblock") || hasClass(ns, "stability"))) {
2262 addClass(ns, "hidden-by-impl-hider");
2264 removeClass(ns, "hidden-by-impl-hider");
2266 ns = ns.nextElementSibling;
2274 if (hasClass(toggle.parentNode, "impl") === false) {
2275 relatedDoc = toggle.parentNode.nextElementSibling;
2276 if (hasClass(relatedDoc, "stability")) {
2277 relatedDoc = relatedDoc.nextElementSibling;
2279 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
2280 if (mode === "toggle") {
2281 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
2287 if (action === "hide") {
2288 addClass(relatedDoc, "hidden-by-usual-hider");
2289 onEachLazy(toggle.childNodes, adjustToggle(true));
2290 addClass(toggle.parentNode, "collapsed");
2291 } else if (action === "show") {
2292 removeClass(relatedDoc, "hidden-by-usual-hider");
2293 removeClass(toggle.parentNode, "collapsed");
2294 onEachLazy(toggle.childNodes, adjustToggle(false));
2298 // we are collapsing the impl block(s).
2300 var parentElem = toggle.parentNode;
2301 relatedDoc = parentElem;
2302 var docblock = relatedDoc.nextElementSibling;
2304 while (hasClass(relatedDoc, "impl-items") === false) {
2305 relatedDoc = relatedDoc.nextElementSibling;
2308 if (!relatedDoc && hasClass(docblock, "docblock") === false) {
2312 // Hide all functions, but not associated types/consts.
2314 if (mode === "toggle") {
2315 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2316 hasClass(docblock, "hidden-by-impl-hider")) {
2323 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2324 if (action === "show") {
2325 removeClass(relatedDoc, "fns-now-collapsed");
2326 removeClass(docblock, "hidden-by-usual-hider");
2327 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2328 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2329 } else if (action === "hide") {
2330 addClass(relatedDoc, "fns-now-collapsed");
2331 addClass(docblock, "hidden-by-usual-hider");
2332 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2333 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2338 function collapser(pageId, e, collapse) {
2339 // inherent impl ids are like "impl" or impl-<number>'.
2340 // they will never be hidden by default.
2341 var n = e.parentElement;
2342 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2343 // Automatically minimize all non-inherent impls
2344 if (collapse || hasClass(n, "impl")) {
2345 collapseDocs(e, "hide", pageId);
2350 function autoCollapse(pageId, collapse) {
2352 toggleAllDocs(pageId, true);
2353 } else if (getSettingValue("auto-hide-trait-implementations") !== "false") {
2354 var impl_list = document.getElementById("trait-implementations-list");
2356 if (impl_list !== null) {
2357 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2358 collapser(pageId, e, collapse);
2362 var blanket_list = document.getElementById("blanket-implementations-list");
2364 if (blanket_list !== null) {
2365 onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) {
2366 collapser(pageId, e, collapse);
2372 function insertAfter(newNode, referenceNode) {
2373 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2376 function createSimpleToggle(sectionIsCollapsed) {
2377 var toggle = document.createElement("a");
2378 toggle.href = "javascript:void(0)";
2379 toggle.className = "collapse-toggle";
2380 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2385 function createToggle(toggle, otherMessage, fontSize, extraClass, show) {
2386 var span = document.createElement("span");
2387 span.className = "toggle-label";
2389 span.style.display = "none";
2391 if (!otherMessage) {
2392 span.innerHTML = " Expand description";
2394 span.innerHTML = otherMessage;
2398 span.style.fontSize = fontSize;
2401 var mainToggle = toggle.cloneNode(true);
2402 mainToggle.appendChild(span);
2404 var wrapper = document.createElement("div");
2405 wrapper.className = "toggle-wrapper";
2407 addClass(wrapper, "collapsed");
2408 var inner = mainToggle.getElementsByClassName("inner");
2409 if (inner && inner.length > 0) {
2410 inner[0].innerHTML = "+";
2414 addClass(wrapper, extraClass);
2416 wrapper.appendChild(mainToggle);
2421 var toggles = document.getElementById(toggleAllDocsId);
2423 toggles.onclick = toggleAllDocs;
2426 var toggle = createSimpleToggle(false);
2427 var hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
2428 var hideImplementors = getSettingValue("auto-collapse-implementors") !== "false";
2429 var pageId = getPageId();
2431 var func = function(e) {
2432 var next = e.nextElementSibling;
2436 if (hasClass(next, "docblock") === true ||
2437 (hasClass(next, "stability") === true &&
2438 hasClass(next.nextElementSibling, "docblock") === true)) {
2439 var newToggle = toggle.cloneNode(true);
2440 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2441 if (hideMethodDocs === true && hasClass(e, "method") === true) {
2442 collapseDocs(newToggle, "hide", pageId);
2447 var funcImpl = function(e) {
2448 var next = e.nextElementSibling;
2449 if (next && hasClass(next, "docblock")) {
2450 next = next.nextElementSibling;
2455 if (hasClass(e, "impl") &&
2456 (next.getElementsByClassName("method").length > 0 ||
2457 next.getElementsByClassName("associatedconstant").length > 0)) {
2458 var newToggle = toggle.cloneNode(true);
2459 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2460 // In case the option "auto-collapse implementors" is not set to false, we collapse
2461 // all implementors.
2462 if (hideImplementors === true && e.parentNode.id === "implementors-list") {
2463 collapseDocs(newToggle, "hide", pageId);
2468 onEachLazy(document.getElementsByClassName("method"), func);
2469 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2470 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2471 var impl_call = function() {};
2472 if (hideMethodDocs === true) {
2473 impl_call = function(e, newToggle) {
2474 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2475 // Automatically minimize all non-inherent impls
2476 if (hasClass(e, "impl") === true) {
2477 collapseDocs(newToggle, "hide", pageId);
2482 var newToggle = document.createElement("a");
2483 newToggle.href = "javascript:void(0)";
2484 newToggle.className = "collapse-toggle hidden-default collapsed";
2485 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2486 "</span>] Show hidden undocumented items";
2487 function toggleClicked() {
2488 if (hasClass(this, "collapsed")) {
2489 removeClass(this, "collapsed");
2490 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2491 if (hasClass(x, "content") === false) {
2492 removeClass(x, "hidden");
2496 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2497 "</span>] Hide undocumented items";
2499 addClass(this, "collapsed");
2500 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2501 if (hasClass(x, "content") === false) {
2502 addClass(x, "hidden");
2503 removeClass(x, "x");
2506 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2507 "</span>] Show hidden undocumented items";
2510 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2511 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2512 var hiddenElems = e.getElementsByClassName("hidden");
2513 var needToggle = false;
2515 var hlength = hiddenElems.length;
2516 for (var i = 0; i < hlength; ++i) {
2517 if (hasClass(hiddenElems[i], "content") === false &&
2518 hasClass(hiddenElems[i], "docblock") === false) {
2523 if (needToggle === true) {
2524 var inner_toggle = newToggle.cloneNode(true);
2525 inner_toggle.onclick = toggleClicked;
2526 e.insertBefore(inner_toggle, e.firstChild);
2527 impl_call(e.previousSibling, inner_toggle);
2531 var currentType = document.getElementsByClassName("type-decl")[0];
2532 var className = null;
2534 currentType = currentType.getElementsByClassName("rust")[0];
2536 currentType.classList.forEach(function(item) {
2537 if (item !== "main") {
2544 var showItemDeclarations = getSettingValue("auto-hide-" + className);
2545 if (showItemDeclarations === null) {
2546 if (className === "enum" || className === "macro") {
2547 showItemDeclarations = "false";
2548 } else if (className === "struct" || className === "union" || className === "trait") {
2549 showItemDeclarations = "true";
2551 // In case we found an unknown type, we just use the "parent" value.
2552 showItemDeclarations = getSettingValue("auto-hide-declarations");
2555 showItemDeclarations = showItemDeclarations === "false";
2556 function buildToggleWrapper(e) {
2557 if (hasClass(e, "autohide")) {
2558 var wrap = e.previousElementSibling;
2559 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2560 var inner_toggle = wrap.childNodes[0];
2561 var extra = e.childNodes[0].tagName === "H3";
2563 e.style.display = "none";
2564 addClass(wrap, "collapsed");
2565 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2566 e.innerHTML = labelForToggleButton(true);
2568 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2569 e.style.display = "inline-block";
2570 if (extra === true) {
2571 e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2576 if (e.parentNode.id === "main") {
2577 var otherMessage = "";
2581 if (hasClass(e, "type-decl")) {
2583 otherMessage = " Show declaration";
2584 if (showItemDeclarations === false) {
2585 extraClass = "collapsed";
2587 } else if (hasClass(e, "sub-variant")) {
2588 otherMessage = " Show fields";
2589 } else if (hasClass(e, "non-exhaustive")) {
2590 otherMessage = " This ";
2591 if (hasClass(e, "non-exhaustive-struct")) {
2592 otherMessage += "struct";
2593 } else if (hasClass(e, "non-exhaustive-enum")) {
2594 otherMessage += "enum";
2595 } else if (hasClass(e, "non-exhaustive-variant")) {
2596 otherMessage += "enum variant";
2597 } else if (hasClass(e, "non-exhaustive-type")) {
2598 otherMessage += "type";
2600 otherMessage += " is marked as non-exhaustive";
2601 } else if (hasClass(e.childNodes[0], "impl-items")) {
2602 extraClass = "marg-left";
2605 e.parentNode.insertBefore(
2611 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2613 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2614 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2616 if (hasClass(e, "non-exhaustive") === true) {
2617 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2622 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2623 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2624 var pageId = getPageId();
2626 autoCollapse(pageId, getSettingValue("collapse") === "true");
2628 if (pageId !== null) {
2629 expandSection(pageId);
2633 function createToggleWrapper(tog) {
2634 var span = document.createElement("span");
2635 span.className = "toggle-label";
2636 span.style.display = "none";
2637 span.innerHTML = " Expand attributes";
2638 tog.appendChild(span);
2640 var wrapper = document.createElement("div");
2641 wrapper.className = "toggle-wrapper toggle-attributes";
2642 wrapper.appendChild(tog);
2647 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2648 var itemAttributesFunc = function() {};
2649 if (getSettingValue("auto-hide-attributes") !== "false") {
2650 itemAttributesFunc = function(x) {
2651 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2654 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2655 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2656 var attr_tog = attributesToggle.cloneNode(true);
2657 if (hasClass(i_e, "top-attr") === true) {
2658 addClass(attr_tog, "top-attr");
2660 i_e.parentNode.insertBefore(attr_tog, i_e);
2661 itemAttributesFunc(i_e);
2666 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2667 var lineNumbersFunc = function() {};
2668 if (getSettingValue("line-numbers") === "true") {
2669 lineNumbersFunc = function(x) {
2670 var count = x.textContent.split("\n").length;
2672 for (var i = 0; i < count; ++i) {
2675 var node = document.createElement("pre");
2676 addClass(node, "line-number");
2677 node.innerHTML = elems.join("\n");
2678 x.parentNode.insertBefore(node, x);
2681 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2682 if (hasClass(e, "compile_fail")) {
2683 e.addEventListener("mouseover", function() {
2684 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2686 e.addEventListener("mouseout", function() {
2687 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2689 } else if (hasClass(e, "ignore")) {
2690 e.addEventListener("mouseover", function() {
2691 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2693 e.addEventListener("mouseout", function() {
2694 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2701 onEachLazy(document.getElementsByClassName("notable-traits"), function(e) {
2702 e.onclick = function() {
2703 this.getElementsByClassName('notable-traits-tooltiptext')[0]
2704 .classList.toggle("force-tooltip");
2708 // In the search display, allows to switch between tabs.
2709 function printTab(nb) {
2710 if (nb === 0 || nb === 1 || nb === 2) {
2714 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2715 if (nb_copy === 0) {
2716 addClass(elem, "selected");
2718 removeClass(elem, "selected");
2722 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2724 elem.style.display = "";
2726 elem.style.display = "none";
2732 function putBackSearch(search_input) {
2733 var search = getSearchElement();
2734 if (search_input.value !== "" && hasClass(search, "hidden")) {
2735 showSearchResults(search);
2736 if (browserSupportsHistoryApi()) {
2737 history.replaceState(search_input.value,
2739 "?search=" + encodeURIComponent(search_input.value));
2741 document.title = searchTitle;
2745 function getSearchLoadingText() {
2746 return "Loading search results...";
2750 search_input.onfocus = function() {
2751 putBackSearch(this);
2755 var params = getQueryStringParams();
2756 if (params && params.search) {
2757 var search = getSearchElement();
2758 search.innerHTML = "<h3 style=\"text-align: center;\">" + getSearchLoadingText() + "</h3>";
2759 showSearchResults(search);
2762 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2764 sidebar_menu.onclick = function() {
2765 var sidebar = document.getElementsByClassName("sidebar")[0];
2766 if (hasClass(sidebar, "mobile") === true) {
2775 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2778 onEachLazy(main.childNodes, function(e) {
2779 // Unhide the actual content once loading is complete. Headers get
2780 // flex treatment for their horizontal layout, divs get block treatment
2781 // for vertical layout (column-oriented flex layout for divs caused
2782 // errors in mobile browsers).
2783 if (e.tagName === "H2" || e.tagName === "H3") {
2784 var nextTagName = e.nextElementSibling.tagName;
2785 if (nextTagName == "H2" || nextTagName == "H3") {
2786 e.nextElementSibling.style.display = "flex";
2788 e.nextElementSibling.style.display = "block";
2794 function enableSearchInput() {
2796 search_input.removeAttribute('disabled');
2800 window.addSearchOptions = function(crates) {
2801 var elem = document.getElementById("crate-search");
2804 enableSearchInput();
2807 var crates_text = [];
2808 if (Object.keys(crates).length > 1) {
2809 for (var crate in crates) {
2810 if (hasOwnProperty(crates, crate)) {
2811 crates_text.push(crate);
2815 crates_text.sort(function(a, b) {
2816 var lower_a = a.toLowerCase();
2817 var lower_b = b.toLowerCase();
2819 if (lower_a < lower_b) {
2821 } else if (lower_a > lower_b) {
2826 var savedCrate = getSettingValue("saved-filter-crate");
2827 for (var i = 0; i < crates_text.length; ++i) {
2828 var option = document.createElement("option");
2829 option.value = crates_text[i];
2830 option.innerText = crates_text[i];
2831 elem.appendChild(option);
2832 // Set the crate filter from saved storage, if the current page has the saved crate
2835 // If not, ignore the crate filter -- we want to support filtering for crates on sites
2836 // like doc.rust-lang.org where the crates may differ from page to page while on the
2838 if (crates_text[i] === savedCrate) {
2839 elem.value = savedCrate;
2842 enableSearchInput();
2845 function buildHelperPopup() {
2846 var popup = document.createElement("aside");
2847 addClass(popup, "hidden");
2850 var book_info = document.createElement("span");
2851 book_info.innerHTML = "You can find more information in \
2852 <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
2854 var container = document.createElement("div");
2856 ["?", "Show this help dialog"],
2857 ["S", "Focus the search field"],
2858 ["↑", "Move up in search results"],
2859 ["↓", "Move down in search results"],
2860 ["↹", "Switch tab"],
2861 ["⏎", "Go to active search result"],
2862 ["+", "Expand all sections"],
2863 ["-", "Collapse all sections"],
2864 ].map(x => "<dt><kbd>" + x[0] + "</kbd></dt><dd>" + x[1] + "</dd>").join("");
2865 var div_shortcuts = document.createElement("div");
2866 addClass(div_shortcuts, "shortcuts");
2867 div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
2870 "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
2871 restrict the search to a given item kind.",
2872 "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
2873 <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
2874 and <code>const</code>.",
2875 "Search functions by type signature (e.g., <code>vec -> usize</code> or \
2876 <code>* -> vec</code>)",
2877 "Search multiple things at once by splitting your query with comma (e.g., \
2878 <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
2879 "You can look for items with an exact name by putting double quotes around \
2880 your request: <code>\"string\"</code>",
2881 "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
2882 ].map(x => "<p>" + x + "</p>").join("");
2883 var div_infos = document.createElement("div");
2884 addClass(div_infos, "infos");
2885 div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
2887 container.appendChild(book_info);
2888 container.appendChild(div_shortcuts);
2889 container.appendChild(div_infos);
2891 popup.appendChild(container);
2892 insertAfter(popup, getSearchElement());
2893 // So that it's only built once and then it'll do nothing when called!
2894 buildHelperPopup = function() {};
2898 window.onhashchange = onHashChange;
2901 // This is required in firefox. Explanations: when going back in the history, firefox doesn't re-run
2902 // the JS, therefore preventing rustdoc from setting a few things required to be able to reload the
2903 // previous search results (if you navigated to a search result with the keyboard, pressed enter on
2904 // it to navigate to that result, and then came back to this page).
2905 window.onunload = function(){};