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);
422 displayHelp(false, ev);
424 var themePicker = getThemePickerElement();
430 var themePicker = getThemePickerElement();
431 if (themePicker.parentNode.contains(ev.target)) {
432 handleThemeKeyDown(ev);
438 function handleThemeKeyDown(ev) {
439 var active = document.activeElement;
440 var themes = getThemesElement();
441 switch (getVirtualKey(ev)) {
444 if (active.previousElementSibling && ev.target.id !== "theme-picker") {
445 active.previousElementSibling.focus();
447 showThemeButtonState();
448 themes.lastElementChild.focus();
453 if (active.nextElementSibling && ev.target.id !== "theme-picker") {
454 active.nextElementSibling.focus();
456 showThemeButtonState();
457 themes.firstElementChild.focus();
463 if (ev.target.id === "theme-picker" && themes.style.display === "none") {
465 showThemeButtonState();
466 themes.firstElementChild.focus();
471 themes.firstElementChild.focus();
475 themes.lastElementChild.focus();
477 // The escape key is handled in handleEscape, not here,
478 // so that pressing escape will close the menu even if it isn't focused
482 function findParentElement(elem, tagName) {
484 if (elem && elem.tagName === tagName) {
487 elem = elem.parentNode;
492 document.addEventListener("keypress", handleShortcut);
493 document.addEventListener("keydown", handleShortcut);
495 function resetMouseMoved(ev) {
496 mouseMovedAfterSearch = true;
499 document.addEventListener("mousemove", resetMouseMoved);
501 var handleSourceHighlight = (function() {
502 var prev_line_id = 0;
504 var set_fragment = function(name) {
505 var x = window.scrollX,
507 if (browserSupportsHistoryApi()) {
508 history.replaceState(null, null, "#" + name);
509 highlightSourceLines();
511 location.replace("#" + name);
513 // Prevent jumps when selecting one or many lines
514 window.scrollTo(x, y);
517 return function(ev) {
518 var cur_line_id = parseInt(ev.target.id, 10);
521 if (ev.shiftKey && prev_line_id) {
522 // Swap selection if needed
523 if (prev_line_id > cur_line_id) {
524 var tmp = prev_line_id;
525 prev_line_id = cur_line_id;
529 set_fragment(prev_line_id + "-" + cur_line_id);
531 prev_line_id = cur_line_id;
533 set_fragment(cur_line_id);
538 document.addEventListener("click", function(ev) {
539 if (hasClass(ev.target, "help-button")) {
540 displayHelp(true, ev);
541 } else if (hasClass(ev.target, "collapse-toggle")) {
542 collapseDocs(ev.target, "toggle");
543 } else if (hasClass(ev.target.parentNode, "collapse-toggle")) {
544 collapseDocs(ev.target.parentNode, "toggle");
545 } else if (ev.target.tagName === "SPAN" && hasClass(ev.target.parentNode, "line-numbers")) {
546 handleSourceHighlight(ev);
547 } else if (hasClass(getHelpElement(), "hidden") === false) {
548 var help = getHelpElement();
549 var is_inside_help_popup = ev.target !== help && help.contains(ev.target);
550 if (is_inside_help_popup === false) {
551 addClass(help, "hidden");
552 removeClass(document.body, "blur");
555 // Making a collapsed element visible on onhashchange seems
557 var a = findParentElement(ev.target, "A");
559 expandSection(a.hash.replace(/^#/, ""));
565 var x = document.getElementsByClassName("version-selector");
567 x[0].onchange = function() {
569 url = document.location.href,
571 len = rootPath.match(/\.\.\//g).length + 1;
573 for (i = 0; i < len; ++i) {
574 match = url.match(/\/[^\/]*$/);
576 stripped = match[0] + stripped;
578 url = url.substring(0, url.length - match[0].length);
581 var selectedVersion = document.getElementsByClassName("version-selector")[0].value;
582 url += "/" + selectedVersion + stripped;
584 document.location.href = url;
590 * A function to compute the Levenshtein distance between two strings
591 * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
592 * Full License can be found at http://creativecommons.org/licenses/by-sa/3.0/legalcode
593 * This code is an unmodified version of the code written by Marco de Wit
594 * and was found at http://stackoverflow.com/a/18514751/745719
596 var levenshtein_row2 = [];
597 function levenshtein(s1, s2) {
601 var s1_len = s1.length, s2_len = s2.length;
602 if (s1_len && s2_len) {
603 var i1 = 0, i2 = 0, a, b, c, c2, row = levenshtein_row2;
604 while (i1 < s1_len) {
607 while (i2 < s2_len) {
608 c2 = s2.charCodeAt(i2);
612 for (i1 = 0; i1 < s1_len; ++i1) {
613 c = a + (s1.charCodeAt(i1) !== c2 ? 1 : 0);
615 b = b < a ? (b < c ? b + 1 : c) : (a < c ? a + 1 : c);
621 return s1_len + s2_len;
624 window.initSearch = function(rawSearchIndex) {
625 var MAX_LEV_DISTANCE = 3;
626 var MAX_RESULTS = 200;
627 var GENERICS_DATA = 1;
631 var NO_TYPE_FILTER = -1;
632 var currentResults, index, searchIndex;
634 var params = getQueryStringParams();
636 // Populate search bar with query string search term when provided,
637 // but only if the input bar is empty. This avoid the obnoxious issue
638 // where you start trying to do a search, and the index loads, and
639 // suddenly your search is gone!
640 if (search_input.value === "") {
641 search_input.value = params.search || "";
645 * Executes the query and builds an index of results
646 * @param {[Object]} query [The user query]
647 * @param {[type]} searchWords [The list of search words to query
649 * @param {[type]} filterCrates [Crate to search in if defined]
650 * @return {[type]} [A search index of results]
652 function execQuery(query, searchWords, filterCrates) {
653 function itemTypeFromName(typename) {
654 var length = itemTypes.length;
655 for (var i = 0; i < length; ++i) {
656 if (itemTypes[i] === typename) {
660 return NO_TYPE_FILTER;
663 var valLower = query.query.toLowerCase(),
665 typeFilter = itemTypeFromName(query.type),
666 results = {}, results_in_args = {}, results_returned = {},
667 split = valLower.split("::");
669 var length = split.length;
670 for (var z = 0; z < length; ++z) {
671 if (split[z] === "") {
677 function transformResults(results, isType) {
679 var length = results.length;
680 for (var i = 0; i < length; ++i) {
681 if (results[i].id > -1) {
682 var obj = searchIndex[results[i].id];
683 obj.lev = results[i].lev;
684 if (isType !== true || obj.type) {
685 var res = buildHrefAndPath(obj);
686 obj.displayPath = pathSplitter(res[0]);
687 obj.fullPath = obj.displayPath + obj.name;
688 // To be sure than it some items aren't considered as duplicate.
689 obj.fullPath += "|" + obj.ty;
692 if (out.length >= MAX_RESULTS) {
701 function sortResults(results, isType) {
703 for (var entry in results) {
704 if (hasOwnProperty(results, entry)) {
705 ar.push(results[entry]);
710 var nresults = results.length;
711 for (i = 0; i < nresults; ++i) {
712 results[i].word = searchWords[results[i].id];
713 results[i].item = searchIndex[results[i].id] || {};
715 // if there are no results then return to default and fail
716 if (results.length === 0) {
720 results.sort(function(aaa, bbb) {
723 // sort by exact match with regard to the last word (mismatch goes later)
724 a = (aaa.word !== val);
725 b = (bbb.word !== val);
726 if (a !== b) { return a - b; }
728 // Sort by non levenshtein results and then levenshtein results by the distance
729 // (less changes required to match means higher rankings)
732 if (a !== b) { return a - b; }
734 // sort by crate (non-current crate goes later)
735 a = (aaa.item.crate !== window.currentCrate);
736 b = (bbb.item.crate !== window.currentCrate);
737 if (a !== b) { return a - b; }
739 // sort by item name length (longer goes later)
742 if (a !== b) { return a - b; }
744 // sort by item name (lexicographically larger goes later)
747 if (a !== b) { return (a > b ? +1 : -1); }
749 // sort by index of keyword in item name (no literal occurrence goes later)
752 if (a !== b) { return a - b; }
753 // (later literal occurrence, if any, goes later)
756 if (a !== b) { return a - b; }
758 // special precedence for primitive and keyword pages
759 if ((aaa.item.ty === TY_PRIMITIVE && bbb.item.ty !== TY_KEYWORD) ||
760 (aaa.item.ty === TY_KEYWORD && bbb.item.ty !== TY_PRIMITIVE)) {
763 if ((bbb.item.ty === TY_PRIMITIVE && aaa.item.ty !== TY_PRIMITIVE) ||
764 (bbb.item.ty === TY_KEYWORD && aaa.item.ty !== TY_KEYWORD)) {
768 // sort by description (no description goes later)
769 a = (aaa.item.desc === "");
770 b = (bbb.item.desc === "");
771 if (a !== b) { return a - b; }
773 // sort by type (later occurrence in `itemTypes` goes later)
776 if (a !== b) { return a - b; }
778 // sort by path (lexicographically larger goes later)
781 if (a !== b) { return (a > b ? +1 : -1); }
787 var length = results.length;
788 for (i = 0; i < length; ++i) {
789 var result = results[i];
791 // this validation does not make sense when searching by types
792 if (result.dontValidate) {
795 var name = result.item.name.toLowerCase(),
796 path = result.item.path.toLowerCase(),
797 parent = result.item.parent;
799 if (isType !== true &&
800 validateResult(name, path, split, parent) === false)
805 return transformResults(results);
808 function extractGenerics(val) {
809 val = val.toLowerCase();
810 if (val.indexOf("<") !== -1) {
811 var values = val.substring(val.indexOf("<") + 1, val.lastIndexOf(">"));
813 name: val.substring(0, val.indexOf("<")),
814 generics: values.split(/\s*,\s*/),
823 function getObjectFromId(id) {
824 if (typeof id === "number") {
825 return searchIndex[id];
830 function checkGenerics(obj, val) {
831 // The names match, but we need to be sure that all generics kinda
833 var lev_distance = MAX_LEV_DISTANCE + 1;
834 if (val.generics.length > 0) {
835 if (obj.length > GENERICS_DATA &&
836 obj[GENERICS_DATA].length >= val.generics.length) {
837 var elems = obj[GENERICS_DATA].slice(0);
840 // We need to find the type that matches the most to remove it in order
842 var vlength = val.generics.length;
843 for (var y = 0; y < vlength; ++y) {
844 var lev = { pos: -1, lev: MAX_LEV_DISTANCE + 1};
845 var elength = elems.length;
846 var firstGeneric = getObjectFromId(val.generics[y]).name;
847 for (var x = 0; x < elength; ++x) {
848 var tmp_lev = levenshtein(getObjectFromId(elems[x]).name,
850 if (tmp_lev < lev.lev) {
855 if (lev.pos !== -1) {
856 elems.splice(lev.pos, 1);
857 lev_distance = Math.min(lev.lev, lev_distance);
861 return MAX_LEV_DISTANCE + 1;
864 return Math.ceil(total / done);
867 return MAX_LEV_DISTANCE + 1;
870 // Check for type name and type generics (if any).
871 function checkType(obj, val, literalSearch) {
872 var lev_distance = MAX_LEV_DISTANCE + 1;
874 if (obj[NAME] === val.name) {
875 if (literalSearch === true) {
876 if (val.generics && val.generics.length !== 0) {
877 if (obj.length > GENERICS_DATA &&
878 obj[GENERICS_DATA].length >= val.generics.length) {
879 var elems = obj[GENERICS_DATA].slice(0);
882 for (var y = 0; allFound === true && y < val.generics.length; ++y) {
884 var firstGeneric = getObjectFromId(val.generics[y]).name;
885 for (x = 0; allFound === false && x < elems.length; ++x) {
886 allFound = getObjectFromId(elems[x]).name === firstGeneric;
888 if (allFound === true) {
889 elems.splice(x - 1, 1);
892 if (allFound === true) {
901 // If the type has generics but don't match, then it won't return at this point.
902 // Otherwise, `checkGenerics` will return 0 and it'll return.
903 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length !== 0) {
904 var tmp_lev = checkGenerics(obj, val);
905 if (tmp_lev <= MAX_LEV_DISTANCE) {
912 // Names didn't match so let's check if one of the generic types could.
913 if (literalSearch === true) {
914 if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
915 var length = obj[GENERICS_DATA].length;
916 for (x = 0; x < length; ++x) {
917 if (obj[GENERICS_DATA][x] === val.name) {
924 lev_distance = Math.min(levenshtein(obj[NAME], val.name), lev_distance);
925 if (lev_distance <= MAX_LEV_DISTANCE) {
926 // The generics didn't match but the name kinda did so we give it
927 // a levenshtein distance value that isn't *this* good so it goes
928 // into the search results but not too high.
929 lev_distance = Math.ceil((checkGenerics(obj, val) + lev_distance) / 2);
930 } else if (obj.length > GENERICS_DATA && obj[GENERICS_DATA].length > 0) {
931 // We can check if the type we're looking for is inside the generics!
932 var olength = obj[GENERICS_DATA].length;
933 for (x = 0; x < olength; ++x) {
934 lev_distance = Math.min(levenshtein(obj[GENERICS_DATA][x], val.name),
938 // Now whatever happens, the returned distance is "less good" so we should mark it
939 // as such, and so we add 1 to the distance to make it "less good".
940 return lev_distance + 1;
943 function findArg(obj, val, literalSearch, typeFilter) {
944 var lev_distance = MAX_LEV_DISTANCE + 1;
946 if (obj && obj.type && obj.type[INPUTS_DATA] && obj.type[INPUTS_DATA].length > 0) {
947 var length = obj.type[INPUTS_DATA].length;
948 for (var i = 0; i < length; i++) {
949 var tmp = obj.type[INPUTS_DATA][i];
950 if (typePassesFilter(typeFilter, tmp[1]) === false) {
953 tmp = checkType(tmp, val, literalSearch);
954 if (literalSearch === true) {
960 lev_distance = Math.min(tmp, lev_distance);
961 if (lev_distance === 0) {
966 return literalSearch === true ? false : lev_distance;
969 function checkReturned(obj, val, literalSearch, typeFilter) {
970 var lev_distance = MAX_LEV_DISTANCE + 1;
972 if (obj && obj.type && obj.type.length > OUTPUT_DATA) {
973 var ret = obj.type[OUTPUT_DATA];
974 if (typeof ret[0] === "string") {
977 for (var x = 0; x < ret.length; ++x) {
979 if (typePassesFilter(typeFilter, tmp[1]) === false) {
982 tmp = checkType(tmp, val, literalSearch);
983 if (literalSearch === true) {
989 lev_distance = Math.min(tmp, lev_distance);
990 if (lev_distance === 0) {
995 return literalSearch === true ? false : lev_distance;
998 function checkPath(contains, lastElem, ty) {
999 if (contains.length === 0) {
1002 var ret_lev = MAX_LEV_DISTANCE + 1;
1003 var path = ty.path.split("::");
1005 if (ty.parent && ty.parent.name) {
1006 path.push(ty.parent.name.toLowerCase());
1009 var length = path.length;
1010 var clength = contains.length;
1011 if (clength > length) {
1012 return MAX_LEV_DISTANCE + 1;
1014 for (var i = 0; i < length; ++i) {
1015 if (i + clength > length) {
1019 var aborted = false;
1020 for (var x = 0; x < clength; ++x) {
1021 var lev = levenshtein(path[i + x], contains[x]);
1022 if (lev > MAX_LEV_DISTANCE) {
1028 if (aborted === false) {
1029 ret_lev = Math.min(ret_lev, Math.round(lev_total / clength));
1035 function typePassesFilter(filter, type) {
1037 if (filter <= NO_TYPE_FILTER) return true;
1040 if (filter === type) return true;
1042 // Match related items
1043 var name = itemTypes[type];
1044 switch (itemTypes[filter]) {
1046 return name === "associatedconstant";
1048 return name === "method" || name === "tymethod";
1050 return name === "primitive" || name === "associatedtype";
1052 return name === "traitalias";
1059 function generateId(ty) {
1060 if (ty.parent && ty.parent.name) {
1061 return itemTypes[ty.ty] + ty.path + ty.parent.name + ty.name;
1063 return itemTypes[ty.ty] + ty.path + ty.name;
1066 function createAliasFromItem(item) {
1073 parent: item.parent,
1079 function handleAliases(ret, query, filterCrates) {
1080 // We separate aliases and crate aliases because we want to have current crate
1081 // aliases to be before the others in the displayed results.
1083 var crateAliases = [];
1085 if (filterCrates !== undefined) {
1086 if (ALIASES[filterCrates] && ALIASES[filterCrates][query.search]) {
1087 for (i = 0; i < ALIASES[filterCrates][query.search].length; ++i) {
1089 createAliasFromItem(
1090 searchIndex[ALIASES[filterCrates][query.search][i]]));
1094 Object.keys(ALIASES).forEach(function(crate) {
1095 if (ALIASES[crate][query.search]) {
1096 var pushTo = crate === window.currentCrate ? crateAliases : aliases;
1097 for (i = 0; i < ALIASES[crate][query.search].length; ++i) {
1099 createAliasFromItem(
1100 searchIndex[ALIASES[crate][query.search][i]]));
1106 var sortFunc = function(aaa, bbb) {
1107 if (aaa.path < bbb.path) {
1109 } else if (aaa.path === bbb.path) {
1114 crateAliases.sort(sortFunc);
1115 aliases.sort(sortFunc);
1117 var pushFunc = function(alias) {
1118 alias.alias = query.raw;
1119 var res = buildHrefAndPath(alias);
1120 alias.displayPath = pathSplitter(res[0]);
1121 alias.fullPath = alias.displayPath + alias.name;
1122 alias.href = res[1];
1124 ret.others.unshift(alias);
1125 if (ret.others.length > MAX_RESULTS) {
1129 onEach(aliases, pushFunc);
1130 onEach(crateAliases, pushFunc);
1133 // quoted values mean literal search
1134 var nSearchWords = searchWords.length;
1140 if ((val.charAt(0) === "\"" || val.charAt(0) === "'") &&
1141 val.charAt(val.length - 1) === val.charAt(0))
1143 val = extractGenerics(val.substr(1, val.length - 2));
1144 for (i = 0; i < nSearchWords; ++i) {
1145 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1148 in_args = findArg(searchIndex[i], val, true, typeFilter);
1149 returned = checkReturned(searchIndex[i], val, true, typeFilter);
1150 ty = searchIndex[i];
1151 fullId = generateId(ty);
1153 if (searchWords[i] === val.name
1154 && typePassesFilter(typeFilter, searchIndex[i].ty)
1155 && results[fullId] === undefined) {
1162 if (in_args === true && results_in_args[fullId] === undefined) {
1163 results_in_args[fullId] = {
1169 if (returned === true && results_returned[fullId] === undefined) {
1170 results_returned[fullId] = {
1177 query.inputs = [val];
1180 // searching by type
1181 } else if (val.search("->") > -1) {
1182 var trimmer = function(s) { return s.trim(); };
1183 var parts = val.split("->").map(trimmer);
1184 var input = parts[0];
1185 // sort inputs so that order does not matter
1186 var inputs = input.split(",").map(trimmer).sort();
1187 for (i = 0; i < inputs.length; ++i) {
1188 inputs[i] = extractGenerics(inputs[i]);
1190 var output = extractGenerics(parts[1]);
1192 for (i = 0; i < nSearchWords; ++i) {
1193 if (filterCrates !== undefined && searchIndex[i].crate !== filterCrates) {
1196 var type = searchIndex[i].type;
1197 ty = searchIndex[i];
1201 fullId = generateId(ty);
1203 returned = checkReturned(ty, output, true, NO_TYPE_FILTER);
1204 if (output.name === "*" || returned === true) {
1206 var is_module = false;
1208 if (input === "*") {
1211 var allFound = true;
1212 for (var it = 0; allFound === true && it < inputs.length; it++) {
1213 allFound = checkType(type, inputs[it], true);
1217 if (in_args === true) {
1218 results_in_args[fullId] = {
1224 if (returned === true) {
1225 results_returned[fullId] = {
1231 if (is_module === true) {
1240 query.inputs = inputs.map(function(input) {
1243 query.output = output.name;
1245 query.inputs = [val];
1248 // gather matching search results up to a certain maximum
1249 val = val.replace(/\_/g, "");
1251 var valGenerics = extractGenerics(val);
1253 var paths = valLower.split("::");
1255 for (j = 0; j < paths.length; ++j) {
1256 if (paths[j] === "") {
1261 val = paths[paths.length - 1];
1262 var contains = paths.slice(0, paths.length > 1 ? paths.length - 1 : 1);
1265 for (j = 0; j < nSearchWords; ++j) {
1266 ty = searchIndex[j];
1267 if (!ty || (filterCrates !== undefined && ty.crate !== filterCrates)) {
1271 if (paths.length > 1) {
1272 lev = checkPath(contains, paths[paths.length - 1], ty);
1273 if (lev > MAX_LEV_DISTANCE) {
1275 } else if (lev > 0) {
1280 returned = MAX_LEV_DISTANCE + 1;
1281 in_args = MAX_LEV_DISTANCE + 1;
1283 // we want lev results to go lower than others
1284 lev = MAX_LEV_DISTANCE + 1;
1285 fullId = generateId(ty);
1287 if (searchWords[j].indexOf(split[i]) > -1 ||
1288 searchWords[j].indexOf(val) > -1 ||
1289 searchWords[j].replace(/_/g, "").indexOf(val) > -1)
1291 // filter type: ... queries
1292 if (typePassesFilter(typeFilter, ty.ty) && results[fullId] === undefined) {
1293 index = searchWords[j].replace(/_/g, "").indexOf(val);
1296 if ((lev = levenshtein(searchWords[j], val)) <= MAX_LEV_DISTANCE) {
1297 if (typePassesFilter(typeFilter, ty.ty) === false) {
1298 lev = MAX_LEV_DISTANCE + 1;
1303 in_args = findArg(ty, valGenerics, false, typeFilter);
1304 returned = checkReturned(ty, valGenerics, false, typeFilter);
1307 if (lev > 0 && val.length > 3 && searchWords[j].indexOf(val) > -1) {
1308 if (val.length < 6) {
1314 if (in_args <= MAX_LEV_DISTANCE) {
1315 if (results_in_args[fullId] === undefined) {
1316 results_in_args[fullId] = {
1322 results_in_args[fullId].lev =
1323 Math.min(results_in_args[fullId].lev, in_args);
1325 if (returned <= MAX_LEV_DISTANCE) {
1326 if (results_returned[fullId] === undefined) {
1327 results_returned[fullId] = {
1333 results_returned[fullId].lev =
1334 Math.min(results_returned[fullId].lev, returned);
1336 if (index !== -1 || lev <= MAX_LEV_DISTANCE) {
1337 if (index !== -1 && paths.length < 2) {
1340 if (results[fullId] === undefined) {
1347 results[fullId].lev = Math.min(results[fullId].lev, lev);
1353 "in_args": sortResults(results_in_args, true),
1354 "returned": sortResults(results_returned, true),
1355 "others": sortResults(results),
1357 handleAliases(ret, query, filterCrates);
1362 * Validate performs the following boolean logic. For example:
1363 * "File::open" will give IF A PARENT EXISTS => ("file" && "open")
1364 * exists in (name || path || parent) OR => ("file" && "open") exists in
1367 * This could be written functionally, but I wanted to minimise
1368 * functions on stack.
1370 * @param {[string]} name [The name of the result]
1371 * @param {[string]} path [The path of the result]
1372 * @param {[string]} keys [The keys to be used (["file", "open"])]
1373 * @param {[object]} parent [The parent of the result]
1374 * @return {[boolean]} [Whether the result is valid or not]
1376 function validateResult(name, path, keys, parent) {
1377 for (var i = 0; i < keys.length; ++i) {
1378 // each check is for validation so we negate the conditions and invalidate
1380 // check for an exact name match
1381 name.indexOf(keys[i]) > -1 ||
1382 // then an exact path match
1383 path.indexOf(keys[i]) > -1 ||
1384 // next if there is a parent, check for exact parent match
1385 (parent !== undefined && parent.name !== undefined &&
1386 parent.name.toLowerCase().indexOf(keys[i]) > -1) ||
1387 // lastly check to see if the name was a levenshtein match
1388 levenshtein(name, keys[i]) <= MAX_LEV_DISTANCE)) {
1395 function getQuery(raw) {
1396 var matches, type, query;
1399 matches = query.match(/^(fn|mod|struct|enum|trait|type|const|macro)\s*:\s*/i);
1401 type = matches[1].replace(/^const$/, "constant");
1402 query = query.substring(matches[0].length);
1413 function initSearchNav() {
1416 var click_func = function(e) {
1418 // to retrieve the real "owner" of the event.
1419 while (el.tagName !== "TR") {
1422 var dst = e.target.getElementsByTagName("a");
1423 if (dst.length < 1) {
1427 if (window.location.pathname === dst.pathname) {
1428 hideSearchResults();
1429 document.location.href = dst.href;
1432 var mouseover_func = function(e) {
1433 if (mouseMovedAfterSearch) {
1435 // to retrieve the real "owner" of the event.
1436 while (el.tagName !== "TR") {
1439 clearTimeout(hoverTimeout);
1440 hoverTimeout = setTimeout(function() {
1441 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1442 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1443 removeClass(i_e, "highlighted");
1446 addClass(el, "highlighted");
1450 onEachLazy(document.getElementsByClassName("search-results"), function(e) {
1451 onEachLazy(e.getElementsByClassName("result"), function(i_e) {
1452 i_e.onclick = click_func;
1453 i_e.onmouseover = mouseover_func;
1457 search_input.onkeydown = function(e) {
1458 // "actives" references the currently highlighted item in each search tab.
1459 // Each array in "actives" represents a tab.
1460 var actives = [[], [], []];
1461 // "current" is used to know which tab we're looking into.
1463 onEachLazy(document.getElementById("results").childNodes, function(e) {
1464 onEachLazy(e.getElementsByClassName("highlighted"), function(h_e) {
1465 actives[current].push(h_e);
1470 if (e.which === 38) { // up
1471 if (!actives[currentTab].length ||
1472 !actives[currentTab][0].previousElementSibling) {
1476 addClass(actives[currentTab][0].previousElementSibling, "highlighted");
1477 removeClass(actives[currentTab][0], "highlighted");
1479 } else if (e.which === 40) { // down
1480 if (!actives[currentTab].length) {
1481 var results = document.getElementById("results").childNodes;
1482 if (results.length > 0) {
1483 var res = results[currentTab].getElementsByClassName("result");
1484 if (res.length > 0) {
1485 addClass(res[0], "highlighted");
1488 } else if (actives[currentTab][0].nextElementSibling) {
1489 addClass(actives[currentTab][0].nextElementSibling, "highlighted");
1490 removeClass(actives[currentTab][0], "highlighted");
1493 } else if (e.which === 13) { // return
1494 if (actives[currentTab].length) {
1495 document.location.href =
1496 actives[currentTab][0].getElementsByTagName("a")[0].href;
1498 } else if (e.which === 9) { // tab
1500 printTab(currentTab > 0 ? currentTab - 1 : 2);
1502 printTab(currentTab > 1 ? 0 : currentTab + 1);
1505 } else if (e.which === 16) { // shift
1506 // Does nothing, it's just to avoid losing "focus" on the highlighted element.
1507 } else if (actives[currentTab].length > 0) {
1508 removeClass(actives[currentTab][0], "highlighted");
1513 function buildHrefAndPath(item) {
1516 var type = itemTypes[item.ty];
1517 var name = item.name;
1518 var path = item.path;
1520 if (type === "mod") {
1521 displayPath = path + "::";
1522 href = rootPath + path.replace(/::/g, "/") + "/" +
1523 name + "/index.html";
1524 } else if (type === "primitive" || type === "keyword") {
1526 href = rootPath + path.replace(/::/g, "/") +
1527 "/" + type + "." + name + ".html";
1528 } else if (type === "externcrate") {
1530 href = rootPath + name + "/index.html";
1531 } else if (item.parent !== undefined) {
1532 var myparent = item.parent;
1533 var anchor = "#" + type + "." + name;
1534 var parentType = itemTypes[myparent.ty];
1535 var pageType = parentType;
1536 var pageName = myparent.name;
1538 if (parentType === "primitive") {
1539 displayPath = myparent.name + "::";
1540 } else if (type === "structfield" && parentType === "variant") {
1541 // Structfields belonging to variants are special: the
1542 // final path element is the enum name.
1543 var splitPath = item.path.split("::");
1544 var enumName = splitPath.pop();
1545 path = splitPath.join("::");
1546 displayPath = path + "::" + enumName + "::" + myparent.name + "::";
1547 anchor = "#variant." + myparent.name + ".field." + name;
1549 pageName = enumName;
1551 displayPath = path + "::" + myparent.name + "::";
1553 href = rootPath + path.replace(/::/g, "/") +
1558 displayPath = item.path + "::";
1559 href = rootPath + item.path.replace(/::/g, "/") +
1560 "/" + type + "." + name + ".html";
1562 return [displayPath, href];
1565 function escape(content) {
1566 var h1 = document.createElement("h1");
1567 h1.textContent = content;
1568 return h1.innerHTML;
1571 function pathSplitter(path) {
1572 var tmp = "<span>" + path.replace(/::/g, "::</span><span>");
1573 if (tmp.endsWith("<span>")) {
1574 return tmp.slice(0, tmp.length - 6);
1579 function addTab(array, query, display) {
1580 var extraStyle = "";
1581 if (display === false) {
1582 extraStyle = " style=\"display: none;\"";
1586 var duplicates = {};
1588 if (array.length > 0) {
1589 output = "<table class=\"search-results\"" + extraStyle + ">";
1591 array.forEach(function(item) {
1595 type = itemTypes[item.ty];
1597 if (item.is_alias !== true) {
1598 if (duplicates[item.fullPath]) {
1601 duplicates[item.fullPath] = true;
1605 output += "<tr class=\"" + type + " result\"><td>" +
1606 "<a href=\"" + item.href + "\">" +
1607 (item.is_alias === true ?
1608 ("<span class=\"alias\"><b>" + item.alias + " </b></span><span " +
1609 "class=\"grey\"><i> - see </i></span>") : "") +
1610 item.displayPath + "<span class=\"" + type + "\">" +
1611 name + "</span></a></td><td>" +
1612 "<a href=\"" + item.href + "\">" +
1613 "<span class=\"desc\">" + escape(item.desc) +
1614 " </span></a></td></tr>";
1616 output += "</table>";
1618 output = "<div class=\"search-failed\"" + extraStyle + ">No results :(<br/>" +
1619 "Try on <a href=\"https://duckduckgo.com/?q=" +
1620 encodeURIComponent("rust " + query.query) +
1621 "\">DuckDuckGo</a>?<br/><br/>" +
1622 "Or try looking in one of these:<ul><li>The <a " +
1623 "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " +
1624 " for technical details about the language.</li><li><a " +
1625 "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " +
1626 "Example</a> for expository code examples.</a></li><li>The <a " +
1627 "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " +
1628 "introductions to language features and the language itself.</li><li><a " +
1629 "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" +
1630 " <a href=\"https://crates.io/\">crates.io</a>.</li></ul></div>";
1632 return [output, length];
1635 function makeTabHeader(tabNb, text, nbElems) {
1636 if (currentTab === tabNb) {
1637 return "<div class=\"selected\">" + text +
1638 " <div class=\"count\">(" + nbElems + ")</div></div>";
1640 return "<div>" + text + " <div class=\"count\">(" + nbElems + ")</div></div>";
1643 function showResults(results) {
1644 var search = getSearchElement();
1645 if (results.others.length === 1
1646 && getSettingValue("go-to-only-result") === "true"
1647 // By default, the search DOM element is "empty" (meaning it has no children not
1648 // text content). Once a search has been run, it won't be empty, even if you press
1649 // ESC or empty the search input (which also "cancels" the search).
1650 && (!search.firstChild || search.firstChild.innerText !== getSearchLoadingText()))
1652 var elem = document.createElement("a");
1653 elem.href = results.others[0].href;
1654 elem.style.display = "none";
1655 // For firefox, we need the element to be in the DOM so it can be clicked.
1656 document.body.appendChild(elem);
1660 var query = getQuery(search_input.value);
1662 currentResults = query.id;
1664 var ret_others = addTab(results.others, query);
1665 var ret_in_args = addTab(results.in_args, query, false);
1666 var ret_returned = addTab(results.returned, query, false);
1668 var output = "<h1>Results for " + escape(query.query) +
1669 (query.type ? " (type: " + escape(query.type) + ")" : "") + "</h1>" +
1670 "<div id=\"titles\">" +
1671 makeTabHeader(0, "In Names", ret_others[1]) +
1672 makeTabHeader(1, "In Parameters", ret_in_args[1]) +
1673 makeTabHeader(2, "In Return Types", ret_returned[1]) +
1674 "</div><div id=\"results\">" +
1675 ret_others[0] + ret_in_args[0] + ret_returned[0] + "</div>";
1677 search.innerHTML = output;
1678 showSearchResults(search);
1679 var tds = search.getElementsByTagName("td");
1681 if (tds.length > 0) {
1682 td_width = tds[0].offsetWidth;
1684 var width = search.offsetWidth - 40 - td_width;
1685 onEachLazy(search.getElementsByClassName("desc"), function(e) {
1686 e.style.width = width + "px";
1689 var elems = document.getElementById("titles").childNodes;
1690 elems[0].onclick = function() { printTab(0); };
1691 elems[1].onclick = function() { printTab(1); };
1692 elems[2].onclick = function() { printTab(2); };
1693 printTab(currentTab);
1696 function execSearch(query, searchWords, filterCrates) {
1697 function getSmallest(arrays, positions, notDuplicates) {
1700 for (var it = 0; it < positions.length; ++it) {
1701 if (arrays[it].length > positions[it] &&
1702 (start === null || start > arrays[it][positions[it]].lev) &&
1703 !notDuplicates[arrays[it][positions[it]].fullPath]) {
1704 start = arrays[it][positions[it]].lev;
1710 function mergeArrays(arrays) {
1713 var notDuplicates = {};
1715 for (var x = 0; x < arrays.length; ++x) {
1718 while (ret.length < MAX_RESULTS) {
1719 var smallest = getSmallest(arrays, positions, notDuplicates);
1721 if (smallest === null) {
1724 for (x = 0; x < arrays.length && ret.length < MAX_RESULTS; ++x) {
1725 if (arrays[x].length > positions[x] &&
1726 arrays[x][positions[x]].lev === smallest &&
1727 !notDuplicates[arrays[x][positions[x]].fullPath]) {
1728 ret.push(arrays[x][positions[x]]);
1729 notDuplicates[arrays[x][positions[x]].fullPath] = true;
1737 var queries = query.raw.split(",");
1744 for (var i = 0; i < queries.length; ++i) {
1745 query = queries[i].trim();
1746 if (query.length !== 0) {
1747 var tmp = execQuery(getQuery(query), searchWords, filterCrates);
1749 results.in_args.push(tmp.in_args);
1750 results.returned.push(tmp.returned);
1751 results.others.push(tmp.others);
1754 if (queries.length > 1) {
1756 "in_args": mergeArrays(results.in_args),
1757 "returned": mergeArrays(results.returned),
1758 "others": mergeArrays(results.others),
1762 "in_args": results.in_args[0],
1763 "returned": results.returned[0],
1764 "others": results.others[0],
1768 function getFilterCrates() {
1769 var elem = document.getElementById("crate-search");
1771 if (elem && elem.value !== "All crates" && hasOwnProperty(rawSearchIndex, elem.value)) {
1777 function search(e, forced) {
1778 var params = getQueryStringParams();
1779 var query = getQuery(search_input.value.trim());
1785 if (query.query.length === 0) {
1788 if (forced !== true && query.id === currentResults) {
1789 if (query.query.length > 0) {
1790 putBackSearch(search_input);
1795 // Update document title to maintain a meaningful browser history
1796 searchTitle = "Results for " + query.query + " - Rust";
1798 // Because searching is incremental by character, only the most
1799 // recent search query is added to the browser history.
1800 if (browserSupportsHistoryApi()) {
1801 if (!history.state && !params.search) {
1802 history.pushState(query, "", "?search=" + encodeURIComponent(query.raw));
1804 history.replaceState(query, "", "?search=" + encodeURIComponent(query.raw));
1808 var filterCrates = getFilterCrates();
1809 showResults(execSearch(query, index, filterCrates));
1812 function buildIndex(rawSearchIndex) {
1814 var searchWords = [];
1816 var currentIndex = 0;
1818 for (var crate in rawSearchIndex) {
1819 if (!hasOwnProperty(rawSearchIndex, crate)) { continue; }
1823 searchWords.push(crate);
1826 ty: 1, // == ExternCrate
1829 desc: rawSearchIndex[crate].doc,
1834 // an array of [(Number) item type,
1836 // (String) full path or empty string for previous path,
1837 // (String) description,
1838 // (Number | null) the parent path index to `paths`]
1839 // (Object | null) the type of the function (if any)
1840 var items = rawSearchIndex[crate].i;
1841 // an array of [(Number) item type,
1843 var paths = rawSearchIndex[crate].p;
1844 // a array of [(String) alias name
1845 // [Number] index to items]
1846 var aliases = rawSearchIndex[crate].a;
1848 // convert `rawPaths` entries into object form
1849 var len = paths.length;
1850 for (i = 0; i < len; ++i) {
1851 paths[i] = {ty: paths[i][0], name: paths[i][1]};
1854 // convert `items` into an object form, and construct word indices.
1856 // before any analysis is performed lets gather the search terms to
1857 // search against apart from the rest of the data. This is a quick
1858 // operation that is cached for the life of the page state so that
1859 // all other search operations have access to this cached data for
1860 // faster analysis operations
1863 for (i = 0; i < len; ++i) {
1864 var rawRow = items[i];
1866 rawRow[2] = lastPath;
1874 parent: paths[rawRow[4]],
1877 searchIndex.push(row);
1878 if (typeof row.name === "string") {
1879 var word = row.name.toLowerCase();
1880 searchWords.push(word);
1882 searchWords.push("");
1884 lastPath = row.path;
1889 ALIASES[crate] = {};
1890 var j, local_aliases;
1891 for (var alias_name in aliases) {
1892 if (!aliases.hasOwnProperty(alias_name)) { continue; }
1894 if (!ALIASES[crate].hasOwnProperty(alias_name)) {
1895 ALIASES[crate][alias_name] = [];
1897 local_aliases = aliases[alias_name];
1898 for (j = 0; j < local_aliases.length; ++j) {
1899 ALIASES[crate][alias_name].push(local_aliases[j] + currentIndex);
1903 currentIndex += crateSize;
1908 function startSearch() {
1909 var callback = function() {
1910 clearInputTimeout();
1911 if (search_input.value.length === 0) {
1912 if (browserSupportsHistoryApi()) {
1913 history.replaceState("", window.currentCrate + " - Rust", "?search=");
1915 hideSearchResults();
1917 searchTimeout = setTimeout(search, 500);
1920 search_input.onkeyup = callback;
1921 search_input.oninput = callback;
1922 document.getElementsByClassName("search-form")[0].onsubmit = function(e) {
1924 clearInputTimeout();
1927 search_input.onchange = function(e) {
1928 if (e.target !== document.activeElement) {
1929 // To prevent doing anything when it's from a blur event.
1932 // Do NOT e.preventDefault() here. It will prevent pasting.
1933 clearInputTimeout();
1934 // zero-timeout necessary here because at the time of event handler execution the
1935 // pasted content is not in the input field yet. Shouldn’t make any difference for
1937 setTimeout(search, 0);
1939 search_input.onpaste = search_input.onchange;
1941 var selectCrate = document.getElementById("crate-search");
1943 selectCrate.onchange = function() {
1944 updateLocalStorage("rustdoc-saved-filter-crate", selectCrate.value);
1945 search(undefined, true);
1949 // Push and pop states are used to add search results to the browser
1951 if (browserSupportsHistoryApi()) {
1952 // Store the previous <title> so we can revert back to it later.
1953 var previousTitle = document.title;
1955 window.addEventListener("popstate", function(e) {
1956 var params = getQueryStringParams();
1957 // Revert to the previous title manually since the History
1958 // API ignores the title parameter.
1959 document.title = previousTitle;
1960 // When browsing forward to search results the previous
1961 // search will be repeated, so the currentResults are
1962 // cleared to ensure the search is successful.
1963 currentResults = null;
1964 // Synchronize search bar with query string state and
1965 // perform the search. This will empty the bar if there's
1966 // nothing there, which lets you really go back to a
1967 // previous state with nothing in the bar.
1968 if (params.search && params.search.length > 0) {
1969 search_input.value = params.search;
1970 // Some browsers fire "onpopstate" for every page load
1971 // (Chrome), while others fire the event only when actually
1972 // popping a state (Firefox), which is why search() is
1973 // called both here and at the end of the startSearch()
1977 search_input.value = "";
1978 // When browsing back from search results the main page
1979 // visibility must be reset.
1980 hideSearchResults();
1987 index = buildIndex(rawSearchIndex);
1990 // Draw a convenient sidebar of known crates if we have a listing
1991 if (rootPath === "../" || rootPath === "./") {
1992 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
1994 var div = document.createElement("div");
1995 div.className = "block crate";
1996 div.innerHTML = "<h3>Crates</h3>";
1997 var ul = document.createElement("ul");
1998 div.appendChild(ul);
2001 for (var crate in rawSearchIndex) {
2002 if (!hasOwnProperty(rawSearchIndex, crate)) {
2008 for (var i = 0; i < crates.length; ++i) {
2009 var klass = "crate";
2010 if (rootPath !== "./" && crates[i] === window.currentCrate) {
2011 klass += " current";
2013 var link = document.createElement("a");
2014 link.href = rootPath + crates[i] + "/index.html";
2015 link.title = rawSearchIndex[crates[i]].doc;
2016 link.className = klass;
2017 link.textContent = crates[i];
2019 var li = document.createElement("li");
2020 li.appendChild(link);
2023 sidebar.appendChild(div);
2029 // delayed sidebar rendering.
2030 window.initSidebarItems = function(items) {
2031 var sidebar = document.getElementsByClassName("sidebar-elems")[0];
2032 var current = window.sidebarCurrent;
2034 function block(shortty, longty) {
2035 var filtered = items[shortty];
2040 var div = document.createElement("div");
2041 div.className = "block " + shortty;
2042 var h3 = document.createElement("h3");
2043 h3.textContent = longty;
2044 div.appendChild(h3);
2045 var ul = document.createElement("ul");
2047 var length = filtered.length;
2048 for (var i = 0; i < length; ++i) {
2049 var item = filtered[i];
2051 var desc = item[1]; // can be null
2053 var klass = shortty;
2054 if (name === current.name && shortty === current.ty) {
2055 klass += " current";
2058 if (shortty === "mod") {
2059 path = name + "/index.html";
2061 path = shortty + "." + name + ".html";
2063 var link = document.createElement("a");
2064 link.href = current.relpath + path;
2066 link.className = klass;
2067 link.textContent = name;
2068 var li = document.createElement("li");
2069 li.appendChild(link);
2072 div.appendChild(ul);
2074 sidebar.appendChild(div);
2078 block("primitive", "Primitive Types");
2079 block("mod", "Modules");
2080 block("macro", "Macros");
2081 block("struct", "Structs");
2082 block("enum", "Enums");
2083 block("union", "Unions");
2084 block("constant", "Constants");
2085 block("static", "Statics");
2086 block("trait", "Traits");
2087 block("fn", "Functions");
2088 block("type", "Type Definitions");
2089 block("foreigntype", "Foreign Types");
2090 block("keyword", "Keywords");
2091 block("traitalias", "Trait Aliases");
2094 window.register_implementors = function(imp) {
2095 var implementors = document.getElementById("implementors-list");
2096 var synthetic_implementors = document.getElementById("synthetic-implementors-list");
2098 if (synthetic_implementors) {
2099 // This `inlined_types` variable is used to avoid having the same implementation
2100 // showing up twice. For example "String" in the "Sync" doc page.
2102 // By the way, this is only used by and useful for traits implemented automatically
2103 // (like "Send" and "Sync").
2104 var inlined_types = new Set();
2105 onEachLazy(synthetic_implementors.getElementsByClassName("impl"), function(el) {
2106 var aliases = el.getAttribute("aliases");
2110 aliases.split(",").forEach(function(alias) {
2111 inlined_types.add(alias);
2116 var libs = Object.getOwnPropertyNames(imp);
2117 var llength = libs.length;
2118 for (var i = 0; i < llength; ++i) {
2119 if (libs[i] === currentCrate) { continue; }
2120 var structs = imp[libs[i]];
2122 var slength = structs.length;
2124 for (var j = 0; j < slength; ++j) {
2125 var struct = structs[j];
2127 var list = struct.synthetic ? synthetic_implementors : implementors;
2129 if (struct.synthetic) {
2130 var stlength = struct.types.length;
2131 for (var k = 0; k < stlength; k++) {
2132 if (inlined_types.has(struct.types[k])) {
2133 continue struct_loop;
2135 inlined_types.add(struct.types[k]);
2139 var code = document.createElement("code");
2140 code.innerHTML = struct.text;
2142 var x = code.getElementsByTagName("a");
2143 var xlength = x.length;
2144 for (var it = 0; it < xlength; it++) {
2145 var href = x[it].getAttribute("href");
2146 if (href && href.indexOf("http") !== 0) {
2147 x[it].setAttribute("href", rootPath + href);
2150 var display = document.createElement("h3");
2151 addClass(display, "impl");
2152 display.innerHTML = "<span class=\"in-band\"><table class=\"table-display\">" +
2153 "<tbody><tr><td><code>" + code.outerHTML + "</code></td><td></td></tr>" +
2154 "</tbody></table></span>";
2155 list.appendChild(display);
2159 if (window.pending_implementors) {
2160 window.register_implementors(window.pending_implementors);
2163 function labelForToggleButton(sectionIsCollapsed) {
2164 if (sectionIsCollapsed) {
2165 // button will expand the section
2168 // button will collapse the section
2169 // note that this text is also set in the HTML template in render.rs
2170 return "\u2212"; // "\u2212" is "−" minus sign
2173 function onEveryMatchingChild(elem, className, func) {
2174 if (elem && className && func) {
2175 var length = elem.childNodes.length;
2176 var nodes = elem.childNodes;
2177 for (var i = 0; i < length; ++i) {
2178 if (hasClass(nodes[i], className)) {
2181 onEveryMatchingChild(nodes[i], className, func);
2187 function toggleAllDocs(pageId, fromAutoCollapse) {
2188 var innerToggle = document.getElementById(toggleAllDocsId);
2192 if (hasClass(innerToggle, "will-expand")) {
2193 updateLocalStorage("rustdoc-collapse", "false");
2194 removeClass(innerToggle, "will-expand");
2195 onEveryMatchingChild(innerToggle, "inner", function(e) {
2196 e.innerHTML = labelForToggleButton(false);
2198 innerToggle.title = "collapse all docs";
2199 if (fromAutoCollapse !== true) {
2200 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2201 collapseDocs(e, "show");
2205 updateLocalStorage("rustdoc-collapse", "true");
2206 addClass(innerToggle, "will-expand");
2207 onEveryMatchingChild(innerToggle, "inner", function(e) {
2208 var parent = e.parentNode;
2209 var superParent = null;
2212 superParent = parent.parentNode;
2214 if (!parent || !superParent || superParent.id !== "main" ||
2215 hasClass(parent, "impl") === false) {
2216 e.innerHTML = labelForToggleButton(true);
2219 innerToggle.title = "expand all docs";
2220 if (fromAutoCollapse !== true) {
2221 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
2222 var parent = e.parentNode;
2223 var superParent = null;
2226 superParent = parent.parentNode;
2228 if (!parent || !superParent || superParent.id !== "main" ||
2229 hasClass(parent, "impl") === false) {
2230 collapseDocs(e, "hide", pageId);
2237 function collapseDocs(toggle, mode, pageId) {
2238 if (!toggle || !toggle.parentNode) {
2242 function adjustToggle(arg) {
2243 return function(e) {
2244 if (hasClass(e, "toggle-label")) {
2246 e.style.display = "inline-block";
2248 e.style.display = "none";
2251 if (hasClass(e, "inner")) {
2252 e.innerHTML = labelForToggleButton(arg);
2257 function implHider(addOrRemove, fullHide) {
2258 return function(n) {
2259 var is_method = hasClass(n, "method") || fullHide;
2260 if (is_method || hasClass(n, "type")) {
2261 if (is_method === true) {
2263 addClass(n, "hidden-by-impl-hider");
2265 removeClass(n, "hidden-by-impl-hider");
2268 var ns = n.nextElementSibling;
2269 while (ns && (hasClass(ns, "docblock") || hasClass(ns, "stability"))) {
2271 addClass(ns, "hidden-by-impl-hider");
2273 removeClass(ns, "hidden-by-impl-hider");
2275 ns = ns.nextElementSibling;
2283 if (hasClass(toggle.parentNode, "impl") === false) {
2284 relatedDoc = toggle.parentNode.nextElementSibling;
2285 if (hasClass(relatedDoc, "stability")) {
2286 relatedDoc = relatedDoc.nextElementSibling;
2288 if (hasClass(relatedDoc, "docblock") || hasClass(relatedDoc, "sub-variant")) {
2289 if (mode === "toggle") {
2290 if (hasClass(relatedDoc, "hidden-by-usual-hider")) {
2296 if (action === "hide") {
2297 addClass(relatedDoc, "hidden-by-usual-hider");
2298 onEachLazy(toggle.childNodes, adjustToggle(true));
2299 addClass(toggle.parentNode, "collapsed");
2300 } else if (action === "show") {
2301 removeClass(relatedDoc, "hidden-by-usual-hider");
2302 removeClass(toggle.parentNode, "collapsed");
2303 onEachLazy(toggle.childNodes, adjustToggle(false));
2307 // we are collapsing the impl block(s).
2309 var parentElem = toggle.parentNode;
2310 relatedDoc = parentElem;
2311 var docblock = relatedDoc.nextElementSibling;
2313 while (hasClass(relatedDoc, "impl-items") === false) {
2314 relatedDoc = relatedDoc.nextElementSibling;
2317 if (!relatedDoc && hasClass(docblock, "docblock") === false) {
2321 // Hide all functions, but not associated types/consts.
2323 if (mode === "toggle") {
2324 if (hasClass(relatedDoc, "fns-now-collapsed") ||
2325 hasClass(docblock, "hidden-by-impl-hider")) {
2332 var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
2333 if (action === "show") {
2334 removeClass(relatedDoc, "fns-now-collapsed");
2335 // Stability information is never hidden.
2336 if (hasClass(docblock, "stability") === false) {
2337 removeClass(docblock, "hidden-by-usual-hider");
2339 onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
2340 onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
2341 } else if (action === "hide") {
2342 addClass(relatedDoc, "fns-now-collapsed");
2343 // Stability information should be shown even when detailed info is hidden.
2344 if (hasClass(docblock, "stability") === false) {
2345 addClass(docblock, "hidden-by-usual-hider");
2347 onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
2348 onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
2353 function collapser(pageId, e, collapse) {
2354 // inherent impl ids are like "impl" or impl-<number>'.
2355 // they will never be hidden by default.
2356 var n = e.parentElement;
2357 if (n.id.match(/^impl(?:-\d+)?$/) === null) {
2358 // Automatically minimize all non-inherent impls
2359 if (collapse || hasClass(n, "impl")) {
2360 collapseDocs(e, "hide", pageId);
2365 function autoCollapse(pageId, collapse) {
2367 toggleAllDocs(pageId, true);
2368 } else if (getSettingValue("auto-hide-trait-implementations") !== "false") {
2369 var impl_list = document.getElementById("trait-implementations-list");
2371 if (impl_list !== null) {
2372 onEachLazy(impl_list.getElementsByClassName("collapse-toggle"), function(e) {
2373 collapser(pageId, e, collapse);
2377 var blanket_list = document.getElementById("blanket-implementations-list");
2379 if (blanket_list !== null) {
2380 onEachLazy(blanket_list.getElementsByClassName("collapse-toggle"), function(e) {
2381 collapser(pageId, e, collapse);
2387 function insertAfter(newNode, referenceNode) {
2388 referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
2391 function createSimpleToggle(sectionIsCollapsed) {
2392 var toggle = document.createElement("a");
2393 toggle.href = "javascript:void(0)";
2394 toggle.className = "collapse-toggle";
2395 toggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(sectionIsCollapsed) +
2400 function createToggle(toggle, otherMessage, fontSize, extraClass, show) {
2401 var span = document.createElement("span");
2402 span.className = "toggle-label";
2404 span.style.display = "none";
2406 if (!otherMessage) {
2407 span.innerHTML = " Expand description";
2409 span.innerHTML = otherMessage;
2413 span.style.fontSize = fontSize;
2416 var mainToggle = toggle.cloneNode(true);
2417 mainToggle.appendChild(span);
2419 var wrapper = document.createElement("div");
2420 wrapper.className = "toggle-wrapper";
2422 addClass(wrapper, "collapsed");
2423 var inner = mainToggle.getElementsByClassName("inner");
2424 if (inner && inner.length > 0) {
2425 inner[0].innerHTML = "+";
2429 addClass(wrapper, extraClass);
2431 wrapper.appendChild(mainToggle);
2436 var toggles = document.getElementById(toggleAllDocsId);
2438 toggles.onclick = toggleAllDocs;
2441 var toggle = createSimpleToggle(false);
2442 var hideMethodDocs = getSettingValue("auto-hide-method-docs") === "true";
2443 var hideImplementors = getSettingValue("auto-collapse-implementors") !== "false";
2444 var pageId = getPageId();
2446 var func = function(e) {
2447 var next = e.nextElementSibling;
2448 if (next && hasClass(next, "stability")) {
2449 next = next.nextElementSibling;
2454 if (hasClass(next, "docblock")) {
2455 var newToggle = toggle.cloneNode(true);
2456 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2457 if (hideMethodDocs === true && hasClass(e, "method") === true) {
2458 collapseDocs(newToggle, "hide", pageId);
2463 var funcImpl = function(e) {
2464 var next = e.nextElementSibling;
2465 if (next && hasClass(next, "stability")) {
2466 next = next.nextElementSibling;
2468 if (next && hasClass(next, "docblock")) {
2469 next = next.nextElementSibling;
2474 if (hasClass(e, "impl") &&
2475 (next.getElementsByClassName("method").length > 0 ||
2476 next.getElementsByClassName("associatedconstant").length > 0)) {
2477 var newToggle = toggle.cloneNode(true);
2478 insertAfter(newToggle, e.childNodes[e.childNodes.length - 1]);
2479 // In case the option "auto-collapse implementors" is not set to false, we collapse
2480 // all implementors.
2481 if (hideImplementors === true && e.parentNode.id === "implementors-list") {
2482 collapseDocs(newToggle, "hide", pageId);
2487 onEachLazy(document.getElementsByClassName("method"), func);
2488 onEachLazy(document.getElementsByClassName("associatedconstant"), func);
2489 onEachLazy(document.getElementsByClassName("impl"), funcImpl);
2490 var impl_call = function() {};
2491 if (hideMethodDocs === true) {
2492 impl_call = function(e, newToggle) {
2493 if (e.id.match(/^impl(?:-\d+)?$/) === null) {
2494 // Automatically minimize all non-inherent impls
2495 if (hasClass(e, "impl") === true) {
2496 collapseDocs(newToggle, "hide", pageId);
2501 var newToggle = document.createElement("a");
2502 newToggle.href = "javascript:void(0)";
2503 newToggle.className = "collapse-toggle hidden-default collapsed";
2504 newToggle.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2505 "</span>] Show hidden undocumented items";
2506 function toggleClicked() {
2507 if (hasClass(this, "collapsed")) {
2508 removeClass(this, "collapsed");
2509 onEachLazy(this.parentNode.getElementsByClassName("hidden"), function(x) {
2510 if (hasClass(x, "content") === false) {
2511 removeClass(x, "hidden");
2515 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(false) +
2516 "</span>] Hide undocumented items";
2518 addClass(this, "collapsed");
2519 onEachLazy(this.parentNode.getElementsByClassName("x"), function(x) {
2520 if (hasClass(x, "content") === false) {
2521 addClass(x, "hidden");
2522 removeClass(x, "x");
2525 this.innerHTML = "[<span class=\"inner\">" + labelForToggleButton(true) +
2526 "</span>] Show hidden undocumented items";
2529 onEachLazy(document.getElementsByClassName("impl-items"), function(e) {
2530 onEachLazy(e.getElementsByClassName("associatedconstant"), func);
2531 var hiddenElems = e.getElementsByClassName("hidden");
2532 var needToggle = false;
2534 var hlength = hiddenElems.length;
2535 for (var i = 0; i < hlength; ++i) {
2536 if (hasClass(hiddenElems[i], "content") === false &&
2537 hasClass(hiddenElems[i], "docblock") === false) {
2542 if (needToggle === true) {
2543 var inner_toggle = newToggle.cloneNode(true);
2544 inner_toggle.onclick = toggleClicked;
2545 e.insertBefore(inner_toggle, e.firstChild);
2546 impl_call(e.previousSibling, inner_toggle);
2550 var currentType = document.getElementsByClassName("type-decl")[0];
2551 var className = null;
2553 currentType = currentType.getElementsByClassName("rust")[0];
2555 currentType.classList.forEach(function(item) {
2556 if (item !== "main") {
2563 var showItemDeclarations = getSettingValue("auto-hide-" + className);
2564 if (showItemDeclarations === null) {
2565 if (className === "enum" || className === "macro") {
2566 showItemDeclarations = "false";
2567 } else if (className === "struct" || className === "union" || className === "trait") {
2568 showItemDeclarations = "true";
2570 // In case we found an unknown type, we just use the "parent" value.
2571 showItemDeclarations = getSettingValue("auto-hide-declarations");
2574 showItemDeclarations = showItemDeclarations === "false";
2575 function buildToggleWrapper(e) {
2576 if (hasClass(e, "autohide")) {
2577 var wrap = e.previousElementSibling;
2578 if (wrap && hasClass(wrap, "toggle-wrapper")) {
2579 var inner_toggle = wrap.childNodes[0];
2580 var extra = e.childNodes[0].tagName === "H3";
2582 e.style.display = "none";
2583 addClass(wrap, "collapsed");
2584 onEachLazy(inner_toggle.getElementsByClassName("inner"), function(e) {
2585 e.innerHTML = labelForToggleButton(true);
2587 onEachLazy(inner_toggle.getElementsByClassName("toggle-label"), function(e) {
2588 e.style.display = "inline-block";
2589 if (extra === true) {
2590 e.innerHTML = " Show " + e.childNodes[0].innerHTML;
2595 if (e.parentNode.id === "main") {
2596 var otherMessage = "";
2600 if (hasClass(e, "type-decl")) {
2602 otherMessage = " Show declaration";
2603 if (showItemDeclarations === false) {
2604 extraClass = "collapsed";
2606 } else if (hasClass(e, "sub-variant")) {
2607 otherMessage = " Show fields";
2608 } else if (hasClass(e, "non-exhaustive")) {
2609 otherMessage = " This ";
2610 if (hasClass(e, "non-exhaustive-struct")) {
2611 otherMessage += "struct";
2612 } else if (hasClass(e, "non-exhaustive-enum")) {
2613 otherMessage += "enum";
2614 } else if (hasClass(e, "non-exhaustive-variant")) {
2615 otherMessage += "enum variant";
2616 } else if (hasClass(e, "non-exhaustive-type")) {
2617 otherMessage += "type";
2619 otherMessage += " is marked as non-exhaustive";
2620 } else if (hasClass(e.childNodes[0], "impl-items")) {
2621 extraClass = "marg-left";
2624 e.parentNode.insertBefore(
2630 hasClass(e, "type-decl") === false || showItemDeclarations === true),
2632 if (hasClass(e, "type-decl") === true && showItemDeclarations === true) {
2633 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2635 if (hasClass(e, "non-exhaustive") === true) {
2636 collapseDocs(e.previousSibling.childNodes[0], "toggle");
2641 onEachLazy(document.getElementsByClassName("docblock"), buildToggleWrapper);
2642 onEachLazy(document.getElementsByClassName("sub-variant"), buildToggleWrapper);
2643 var pageId = getPageId();
2645 autoCollapse(pageId, getSettingValue("collapse") === "true");
2647 if (pageId !== null) {
2648 expandSection(pageId);
2652 function createToggleWrapper(tog) {
2653 var span = document.createElement("span");
2654 span.className = "toggle-label";
2655 span.style.display = "none";
2656 span.innerHTML = " Expand attributes";
2657 tog.appendChild(span);
2659 var wrapper = document.createElement("div");
2660 wrapper.className = "toggle-wrapper toggle-attributes";
2661 wrapper.appendChild(tog);
2666 // To avoid checking on "rustdoc-item-attributes" value on every loop...
2667 var itemAttributesFunc = function() {};
2668 if (getSettingValue("auto-hide-attributes") !== "false") {
2669 itemAttributesFunc = function(x) {
2670 collapseDocs(x.previousSibling.childNodes[0], "toggle");
2673 var attributesToggle = createToggleWrapper(createSimpleToggle(false));
2674 onEachLazy(main.getElementsByClassName("attributes"), function(i_e) {
2675 var attr_tog = attributesToggle.cloneNode(true);
2676 if (hasClass(i_e, "top-attr") === true) {
2677 addClass(attr_tog, "top-attr");
2679 i_e.parentNode.insertBefore(attr_tog, i_e);
2680 itemAttributesFunc(i_e);
2685 // To avoid checking on "rustdoc-line-numbers" value on every loop...
2686 var lineNumbersFunc = function() {};
2687 if (getSettingValue("line-numbers") === "true") {
2688 lineNumbersFunc = function(x) {
2689 var count = x.textContent.split("\n").length;
2691 for (var i = 0; i < count; ++i) {
2694 var node = document.createElement("pre");
2695 addClass(node, "line-number");
2696 node.innerHTML = elems.join("\n");
2697 x.parentNode.insertBefore(node, x);
2700 onEachLazy(document.getElementsByClassName("rust-example-rendered"), function(e) {
2701 if (hasClass(e, "compile_fail")) {
2702 e.addEventListener("mouseover", function() {
2703 this.parentElement.previousElementSibling.childNodes[0].style.color = "#f00";
2705 e.addEventListener("mouseout", function() {
2706 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2708 } else if (hasClass(e, "ignore")) {
2709 e.addEventListener("mouseover", function() {
2710 this.parentElement.previousElementSibling.childNodes[0].style.color = "#ff9200";
2712 e.addEventListener("mouseout", function() {
2713 this.parentElement.previousElementSibling.childNodes[0].style.color = "";
2720 onEachLazy(document.getElementsByClassName("notable-traits"), function(e) {
2721 e.onclick = function() {
2722 this.getElementsByClassName('notable-traits-tooltiptext')[0]
2723 .classList.toggle("force-tooltip");
2727 // In the search display, allows to switch between tabs.
2728 function printTab(nb) {
2729 if (nb === 0 || nb === 1 || nb === 2) {
2733 onEachLazy(document.getElementById("titles").childNodes, function(elem) {
2734 if (nb_copy === 0) {
2735 addClass(elem, "selected");
2737 removeClass(elem, "selected");
2741 onEachLazy(document.getElementById("results").childNodes, function(elem) {
2743 elem.style.display = "";
2745 elem.style.display = "none";
2751 function putBackSearch(search_input) {
2752 var search = getSearchElement();
2753 if (search_input.value !== "" && hasClass(search, "hidden")) {
2754 showSearchResults(search);
2755 if (browserSupportsHistoryApi()) {
2756 history.replaceState(search_input.value,
2758 "?search=" + encodeURIComponent(search_input.value));
2760 document.title = searchTitle;
2764 function getSearchLoadingText() {
2765 return "Loading search results...";
2769 search_input.onfocus = function() {
2770 putBackSearch(this);
2774 var params = getQueryStringParams();
2775 if (params && params.search) {
2776 var search = getSearchElement();
2777 search.innerHTML = "<h3 style=\"text-align: center;\">" + getSearchLoadingText() + "</h3>";
2778 showSearchResults(search);
2781 var sidebar_menu = document.getElementsByClassName("sidebar-menu")[0];
2783 sidebar_menu.onclick = function() {
2784 var sidebar = document.getElementsByClassName("sidebar")[0];
2785 if (hasClass(sidebar, "mobile") === true) {
2794 onEachLazy(main.getElementsByClassName("loading-content"), function(e) {
2797 onEachLazy(main.childNodes, function(e) {
2798 // Unhide the actual content once loading is complete. Headers get
2799 // flex treatment for their horizontal layout, divs get block treatment
2800 // for vertical layout (column-oriented flex layout for divs caused
2801 // errors in mobile browsers).
2802 if (e.tagName === "H2" || e.tagName === "H3") {
2803 var nextTagName = e.nextElementSibling.tagName;
2804 if (nextTagName == "H2" || nextTagName == "H3") {
2805 e.nextElementSibling.style.display = "flex";
2807 e.nextElementSibling.style.display = "block";
2813 function enableSearchInput() {
2815 search_input.removeAttribute('disabled');
2819 window.addSearchOptions = function(crates) {
2820 var elem = document.getElementById("crate-search");
2823 enableSearchInput();
2826 var crates_text = [];
2827 if (Object.keys(crates).length > 1) {
2828 for (var crate in crates) {
2829 if (hasOwnProperty(crates, crate)) {
2830 crates_text.push(crate);
2834 crates_text.sort(function(a, b) {
2835 var lower_a = a.toLowerCase();
2836 var lower_b = b.toLowerCase();
2838 if (lower_a < lower_b) {
2840 } else if (lower_a > lower_b) {
2845 var savedCrate = getSettingValue("saved-filter-crate");
2846 for (var i = 0; i < crates_text.length; ++i) {
2847 var option = document.createElement("option");
2848 option.value = crates_text[i];
2849 option.innerText = crates_text[i];
2850 elem.appendChild(option);
2851 // Set the crate filter from saved storage, if the current page has the saved crate
2854 // If not, ignore the crate filter -- we want to support filtering for crates on sites
2855 // like doc.rust-lang.org where the crates may differ from page to page while on the
2857 if (crates_text[i] === savedCrate) {
2858 elem.value = savedCrate;
2861 enableSearchInput();
2864 function buildHelperPopup() {
2865 var popup = document.createElement("aside");
2866 addClass(popup, "hidden");
2869 var book_info = document.createElement("span");
2870 book_info.innerHTML = "You can find more information in \
2871 <a href=\"https://doc.rust-lang.org/rustdoc/\">the rustdoc book</a>.";
2873 var container = document.createElement("div");
2875 ["?", "Show this help dialog"],
2876 ["S", "Focus the search field"],
2877 ["T", "Focus the theme picker menu"],
2878 ["↑", "Move up in search results"],
2879 ["↓", "Move down in search results"],
2880 ["↹", "Switch tab"],
2881 ["⏎", "Go to active search result"],
2882 ["+", "Expand all sections"],
2883 ["-", "Collapse all sections"],
2884 ].map(x => "<dt><kbd>" + x[0] + "</kbd></dt><dd>" + x[1] + "</dd>").join("");
2885 var div_shortcuts = document.createElement("div");
2886 addClass(div_shortcuts, "shortcuts");
2887 div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>";
2890 "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \
2891 restrict the search to a given item kind.",
2892 "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \
2893 <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, \
2894 and <code>const</code>.",
2895 "Search functions by type signature (e.g., <code>vec -> usize</code> or \
2896 <code>* -> vec</code>)",
2897 "Search multiple things at once by splitting your query with comma (e.g., \
2898 <code>str,u8</code> or <code>String,struct:Vec,test</code>)",
2899 "You can look for items with an exact name by putting double quotes around \
2900 your request: <code>\"string\"</code>",
2901 "Look for items inside another one by searching for a path: <code>vec::Vec</code>",
2902 ].map(x => "<p>" + x + "</p>").join("");
2903 var div_infos = document.createElement("div");
2904 addClass(div_infos, "infos");
2905 div_infos.innerHTML = "<h2>Search Tricks</h2>" + infos;
2907 container.appendChild(book_info);
2908 container.appendChild(div_shortcuts);
2909 container.appendChild(div_infos);
2911 popup.appendChild(container);
2912 insertAfter(popup, getSearchElement());
2913 // So that it's only built once and then it'll do nothing when called!
2914 buildHelperPopup = function() {};
2918 window.onhashchange = onHashChange;
2921 // This is required in firefox. Explanations: when going back in the history, firefox doesn't re-run
2922 // the JS, therefore preventing rustdoc from setting a few things required to be able to reload the
2923 // previous search results (if you navigated to a search result with the keyboard, pressed enter on
2924 // it to navigate to that result, and then came back to this page).
2925 window.onunload = function(){};