searchtools.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*
  2. * searchtools.js
  3. * ~~~~~~~~~~~~~~~~
  4. *
  5. * Sphinx JavaScript utilities for the full-text search.
  6. *
  7. * :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS.
  8. * :license: BSD, see LICENSE for details.
  9. *
  10. */
  11. if (!Scorer) {
  12. /**
  13. * Simple result scoring code.
  14. */
  15. var Scorer = {
  16. // Implement the following function to further tweak the score for each result
  17. // The function takes a result array [filename, title, anchor, descr, score]
  18. // and returns the new score.
  19. /*
  20. score: function(result) {
  21. return result[4];
  22. },
  23. */
  24. // query matches the full name of an object
  25. objNameMatch: 11,
  26. // or matches in the last dotted part of the object name
  27. objPartialMatch: 6,
  28. // Additive scores depending on the priority of the object
  29. objPrio: {0: 15, // used to be importantResults
  30. 1: 5, // used to be objectResults
  31. 2: -5}, // used to be unimportantResults
  32. // Used when the priority is not in the mapping.
  33. objPrioDefault: 0,
  34. // query found in title
  35. title: 15,
  36. partialTitle: 7,
  37. // query found in terms
  38. term: 5,
  39. partialTerm: 2
  40. };
  41. }
  42. if (!splitQuery) {
  43. function splitQuery(query) {
  44. return query.split(/\s+/);
  45. }
  46. }
  47. /**
  48. * Search Module
  49. */
  50. var Search = {
  51. _index : null,
  52. _queued_query : null,
  53. _pulse_status : -1,
  54. htmlToText : function(htmlString) {
  55. var htmlElement = document.createElement('span');
  56. htmlElement.innerHTML = htmlString;
  57. $(htmlElement).find('.headerlink').remove();
  58. docContent = $(htmlElement).find('[role=main]')[0];
  59. if(docContent === undefined) {
  60. console.warn("Content block not found. Sphinx search tries to obtain it " +
  61. "via '[role=main]'. Could you check your theme or template.");
  62. return "";
  63. }
  64. return docContent.textContent || docContent.innerText;
  65. },
  66. init : function() {
  67. var params = $.getQueryParameters();
  68. if (params.q) {
  69. var query = params.q[0];
  70. $('input[name="q"]')[0].value = query;
  71. this.performSearch(query);
  72. }
  73. },
  74. loadIndex : function(url) {
  75. $.ajax({type: "GET", url: url, data: null,
  76. dataType: "script", cache: true,
  77. complete: function(jqxhr, textstatus) {
  78. if (textstatus != "success") {
  79. document.getElementById("searchindexloader").src = url;
  80. }
  81. }});
  82. },
  83. setIndex : function(index) {
  84. var q;
  85. this._index = index;
  86. if ((q = this._queued_query) !== null) {
  87. this._queued_query = null;
  88. Search.query(q);
  89. }
  90. },
  91. hasIndex : function() {
  92. return this._index !== null;
  93. },
  94. deferQuery : function(query) {
  95. this._queued_query = query;
  96. },
  97. stopPulse : function() {
  98. this._pulse_status = 0;
  99. },
  100. startPulse : function() {
  101. if (this._pulse_status >= 0)
  102. return;
  103. function pulse() {
  104. var i;
  105. Search._pulse_status = (Search._pulse_status + 1) % 4;
  106. var dotString = '';
  107. for (i = 0; i < Search._pulse_status; i++)
  108. dotString += '.';
  109. Search.dots.text(dotString);
  110. if (Search._pulse_status > -1)
  111. window.setTimeout(pulse, 500);
  112. }
  113. pulse();
  114. },
  115. /**
  116. * perform a search for something (or wait until index is loaded)
  117. */
  118. performSearch : function(query) {
  119. // create the required interface elements
  120. this.out = $('#search-results');
  121. this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
  122. this.dots = $('<span></span>').appendTo(this.title);
  123. this.status = $('<p class="search-summary">&nbsp;</p>').appendTo(this.out);
  124. this.output = $('<ul class="search"/>').appendTo(this.out);
  125. $('#search-progress').text(_('Preparing search...'));
  126. this.startPulse();
  127. // index already loaded, the browser was quick!
  128. if (this.hasIndex())
  129. this.query(query);
  130. else
  131. this.deferQuery(query);
  132. },
  133. /**
  134. * execute search (requires search index to be loaded)
  135. */
  136. query : function(query) {
  137. var i;
  138. // stem the searchterms and add them to the correct list
  139. var stemmer = new Stemmer();
  140. var searchterms = [];
  141. var excluded = [];
  142. var hlterms = [];
  143. var tmp = splitQuery(query);
  144. var objectterms = [];
  145. for (i = 0; i < tmp.length; i++) {
  146. if (tmp[i] !== "") {
  147. objectterms.push(tmp[i].toLowerCase());
  148. }
  149. if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
  150. tmp[i] === "") {
  151. // skip this "word"
  152. continue;
  153. }
  154. // stem the word
  155. var word = stemmer.stemWord(tmp[i].toLowerCase());
  156. // prevent stemmer from cutting word smaller than two chars
  157. if(word.length < 3 && tmp[i].length >= 3) {
  158. word = tmp[i];
  159. }
  160. var toAppend;
  161. // select the correct list
  162. if (word[0] == '-') {
  163. toAppend = excluded;
  164. word = word.substr(1);
  165. }
  166. else {
  167. toAppend = searchterms;
  168. hlterms.push(tmp[i].toLowerCase());
  169. }
  170. // only add if not already in the list
  171. if (!$u.contains(toAppend, word))
  172. toAppend.push(word);
  173. }
  174. var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
  175. // console.debug('SEARCH: searching for:');
  176. // console.info('required: ', searchterms);
  177. // console.info('excluded: ', excluded);
  178. // prepare search
  179. var terms = this._index.terms;
  180. var titleterms = this._index.titleterms;
  181. // array of [filename, title, anchor, descr, score]
  182. var results = [];
  183. $('#search-progress').empty();
  184. // lookup as object
  185. for (i = 0; i < objectterms.length; i++) {
  186. var others = [].concat(objectterms.slice(0, i),
  187. objectterms.slice(i+1, objectterms.length));
  188. results = results.concat(this.performObjectSearch(objectterms[i], others));
  189. }
  190. // lookup as search terms in fulltext
  191. results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
  192. // let the scorer override scores with a custom scoring function
  193. if (Scorer.score) {
  194. for (i = 0; i < results.length; i++)
  195. results[i][4] = Scorer.score(results[i]);
  196. }
  197. // now sort the results by score (in opposite order of appearance, since the
  198. // display function below uses pop() to retrieve items) and then
  199. // alphabetically
  200. results.sort(function(a, b) {
  201. var left = a[4];
  202. var right = b[4];
  203. if (left > right) {
  204. return 1;
  205. } else if (left < right) {
  206. return -1;
  207. } else {
  208. // same score: sort alphabetically
  209. left = a[1].toLowerCase();
  210. right = b[1].toLowerCase();
  211. return (left > right) ? -1 : ((left < right) ? 1 : 0);
  212. }
  213. });
  214. // for debugging
  215. //Search.lastresults = results.slice(); // a copy
  216. //console.info('search results:', Search.lastresults);
  217. // print the results
  218. var resultCount = results.length;
  219. function displayNextItem() {
  220. // results left, load the summary and display it
  221. if (results.length) {
  222. var item = results.pop();
  223. var listItem = $('<li style="display:none"></li>');
  224. var requestUrl = "";
  225. var linkUrl = "";
  226. if (DOCUMENTATION_OPTIONS.BUILDER === 'dirhtml') {
  227. // dirhtml builder
  228. var dirname = item[0] + '/';
  229. if (dirname.match(/\/index\/$/)) {
  230. dirname = dirname.substring(0, dirname.length-6);
  231. } else if (dirname == 'index/') {
  232. dirname = '';
  233. }
  234. requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + dirname;
  235. linkUrl = requestUrl;
  236. } else {
  237. // normal html builders
  238. requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX;
  239. linkUrl = item[0] + DOCUMENTATION_OPTIONS.LINK_SUFFIX;
  240. }
  241. listItem.append($('<a/>').attr('href',
  242. linkUrl +
  243. highlightstring + item[2]).html(item[1]));
  244. if (item[3]) {
  245. listItem.append($('<span> (' + item[3] + ')</span>'));
  246. Search.output.append(listItem);
  247. listItem.slideDown(5, function() {
  248. displayNextItem();
  249. });
  250. } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
  251. $.ajax({url: requestUrl,
  252. dataType: "text",
  253. complete: function(jqxhr, textstatus) {
  254. var data = jqxhr.responseText;
  255. if (data !== '' && data !== undefined) {
  256. listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
  257. }
  258. Search.output.append(listItem);
  259. listItem.slideDown(5, function() {
  260. displayNextItem();
  261. });
  262. }});
  263. } else {
  264. // no source available, just display title
  265. Search.output.append(listItem);
  266. listItem.slideDown(5, function() {
  267. displayNextItem();
  268. });
  269. }
  270. }
  271. // search finished, update title and status message
  272. else {
  273. Search.stopPulse();
  274. Search.title.text(_('Search Results'));
  275. if (!resultCount)
  276. Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
  277. else
  278. Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
  279. Search.status.fadeIn(500);
  280. }
  281. }
  282. displayNextItem();
  283. },
  284. /**
  285. * search for object names
  286. */
  287. performObjectSearch : function(object, otherterms) {
  288. var filenames = this._index.filenames;
  289. var docnames = this._index.docnames;
  290. var objects = this._index.objects;
  291. var objnames = this._index.objnames;
  292. var titles = this._index.titles;
  293. var i;
  294. var results = [];
  295. for (var prefix in objects) {
  296. for (var name in objects[prefix]) {
  297. var fullname = (prefix ? prefix + '.' : '') + name;
  298. var fullnameLower = fullname.toLowerCase()
  299. if (fullnameLower.indexOf(object) > -1) {
  300. var score = 0;
  301. var parts = fullnameLower.split('.');
  302. // check for different match types: exact matches of full name or
  303. // "last name" (i.e. last dotted part)
  304. if (fullnameLower == object || parts[parts.length - 1] == object) {
  305. score += Scorer.objNameMatch;
  306. // matches in last name
  307. } else if (parts[parts.length - 1].indexOf(object) > -1) {
  308. score += Scorer.objPartialMatch;
  309. }
  310. var match = objects[prefix][name];
  311. var objname = objnames[match[1]][2];
  312. var title = titles[match[0]];
  313. // If more than one term searched for, we require other words to be
  314. // found in the name/title/description
  315. if (otherterms.length > 0) {
  316. var haystack = (prefix + ' ' + name + ' ' +
  317. objname + ' ' + title).toLowerCase();
  318. var allfound = true;
  319. for (i = 0; i < otherterms.length; i++) {
  320. if (haystack.indexOf(otherterms[i]) == -1) {
  321. allfound = false;
  322. break;
  323. }
  324. }
  325. if (!allfound) {
  326. continue;
  327. }
  328. }
  329. var descr = objname + _(', in ') + title;
  330. var anchor = match[3];
  331. if (anchor === '')
  332. anchor = fullname;
  333. else if (anchor == '-')
  334. anchor = objnames[match[1]][1] + '-' + fullname;
  335. // add custom score for some objects according to scorer
  336. if (Scorer.objPrio.hasOwnProperty(match[2])) {
  337. score += Scorer.objPrio[match[2]];
  338. } else {
  339. score += Scorer.objPrioDefault;
  340. }
  341. results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
  342. }
  343. }
  344. }
  345. return results;
  346. },
  347. /**
  348. * search for full-text terms in the index
  349. */
  350. performTermsSearch : function(searchterms, excluded, terms, titleterms) {
  351. var docnames = this._index.docnames;
  352. var filenames = this._index.filenames;
  353. var titles = this._index.titles;
  354. var i, j, file;
  355. var fileMap = {};
  356. var scoreMap = {};
  357. var results = [];
  358. // perform the search on the required terms
  359. for (i = 0; i < searchterms.length; i++) {
  360. var word = searchterms[i];
  361. var files = [];
  362. var _o = [
  363. {files: terms[word], score: Scorer.term},
  364. {files: titleterms[word], score: Scorer.title}
  365. ];
  366. // add support for partial matches
  367. if (word.length > 2) {
  368. for (var w in terms) {
  369. if (w.match(word) && !terms[word]) {
  370. _o.push({files: terms[w], score: Scorer.partialTerm})
  371. }
  372. }
  373. for (var w in titleterms) {
  374. if (w.match(word) && !titleterms[word]) {
  375. _o.push({files: titleterms[w], score: Scorer.partialTitle})
  376. }
  377. }
  378. }
  379. // no match but word was a required one
  380. if ($u.every(_o, function(o){return o.files === undefined;})) {
  381. break;
  382. }
  383. // found search word in contents
  384. $u.each(_o, function(o) {
  385. var _files = o.files;
  386. if (_files === undefined)
  387. return
  388. if (_files.length === undefined)
  389. _files = [_files];
  390. files = files.concat(_files);
  391. // set score for the word in each file to Scorer.term
  392. for (j = 0; j < _files.length; j++) {
  393. file = _files[j];
  394. if (!(file in scoreMap))
  395. scoreMap[file] = {};
  396. scoreMap[file][word] = o.score;
  397. }
  398. });
  399. // create the mapping
  400. for (j = 0; j < files.length; j++) {
  401. file = files[j];
  402. if (file in fileMap && fileMap[file].indexOf(word) === -1)
  403. fileMap[file].push(word);
  404. else
  405. fileMap[file] = [word];
  406. }
  407. }
  408. // now check if the files don't contain excluded terms
  409. for (file in fileMap) {
  410. var valid = true;
  411. // check if all requirements are matched
  412. var filteredTermCount = // as search terms with length < 3 are discarded: ignore
  413. searchterms.filter(function(term){return term.length > 2}).length
  414. if (
  415. fileMap[file].length != searchterms.length &&
  416. fileMap[file].length != filteredTermCount
  417. ) continue;
  418. // ensure that none of the excluded terms is in the search result
  419. for (i = 0; i < excluded.length; i++) {
  420. if (terms[excluded[i]] == file ||
  421. titleterms[excluded[i]] == file ||
  422. $u.contains(terms[excluded[i]] || [], file) ||
  423. $u.contains(titleterms[excluded[i]] || [], file)) {
  424. valid = false;
  425. break;
  426. }
  427. }
  428. // if we have still a valid result we can add it to the result list
  429. if (valid) {
  430. // select one (max) score for the file.
  431. // for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
  432. var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
  433. results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
  434. }
  435. }
  436. return results;
  437. },
  438. /**
  439. * helper function to return a node containing the
  440. * search summary for a given text. keywords is a list
  441. * of stemmed words, hlwords is the list of normal, unstemmed
  442. * words. the first one is used to find the occurrence, the
  443. * latter for highlighting it.
  444. */
  445. makeSearchSummary : function(htmlText, keywords, hlwords) {
  446. var text = Search.htmlToText(htmlText);
  447. var textLower = text.toLowerCase();
  448. var start = 0;
  449. $.each(keywords, function() {
  450. var i = textLower.indexOf(this.toLowerCase());
  451. if (i > -1)
  452. start = i;
  453. });
  454. start = Math.max(start - 120, 0);
  455. var excerpt = ((start > 0) ? '...' : '') +
  456. $.trim(text.substr(start, 240)) +
  457. ((start + 240 - text.length) ? '...' : '');
  458. var rv = $('<div class="context"></div>').text(excerpt);
  459. $.each(hlwords, function() {
  460. rv = rv.highlightText(this, 'highlighted');
  461. });
  462. return rv;
  463. }
  464. };
  465. $(document).ready(function() {
  466. Search.init();
  467. });