searchtools.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /*
  2. * searchtools.js_t
  3. * ~~~~~~~~~~~~~~~~
  4. *
  5. * Sphinx JavaScript utilties for the full-text search.
  6. *
  7. * :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
  8. * :license: BSD, see LICENSE for details.
  9. *
  10. */
  11. /**
  12. * Porter Stemmer
  13. */
  14. var Stemmer = function() {
  15. var step2list = {
  16. ational: 'ate',
  17. tional: 'tion',
  18. enci: 'ence',
  19. anci: 'ance',
  20. izer: 'ize',
  21. bli: 'ble',
  22. alli: 'al',
  23. entli: 'ent',
  24. eli: 'e',
  25. ousli: 'ous',
  26. ization: 'ize',
  27. ation: 'ate',
  28. ator: 'ate',
  29. alism: 'al',
  30. iveness: 'ive',
  31. fulness: 'ful',
  32. ousness: 'ous',
  33. aliti: 'al',
  34. iviti: 'ive',
  35. biliti: 'ble',
  36. logi: 'log'
  37. };
  38. var step3list = {
  39. icate: 'ic',
  40. ative: '',
  41. alize: 'al',
  42. iciti: 'ic',
  43. ical: 'ic',
  44. ful: '',
  45. ness: ''
  46. };
  47. var c = "[^aeiou]"; // consonant
  48. var v = "[aeiouy]"; // vowel
  49. var C = c + "[^aeiouy]*"; // consonant sequence
  50. var V = v + "[aeiou]*"; // vowel sequence
  51. var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
  52. var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
  53. var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
  54. var s_v = "^(" + C + ")?" + v; // vowel in stem
  55. this.stemWord = function (w) {
  56. var stem;
  57. var suffix;
  58. var firstch;
  59. var origword = w;
  60. if (w.length < 3)
  61. return w;
  62. var re;
  63. var re2;
  64. var re3;
  65. var re4;
  66. firstch = w.substr(0,1);
  67. if (firstch == "y")
  68. w = firstch.toUpperCase() + w.substr(1);
  69. // Step 1a
  70. re = /^(.+?)(ss|i)es$/;
  71. re2 = /^(.+?)([^s])s$/;
  72. if (re.test(w))
  73. w = w.replace(re,"$1$2");
  74. else if (re2.test(w))
  75. w = w.replace(re2,"$1$2");
  76. // Step 1b
  77. re = /^(.+?)eed$/;
  78. re2 = /^(.+?)(ed|ing)$/;
  79. if (re.test(w)) {
  80. var fp = re.exec(w);
  81. re = new RegExp(mgr0);
  82. if (re.test(fp[1])) {
  83. re = /.$/;
  84. w = w.replace(re,"");
  85. }
  86. }
  87. else if (re2.test(w)) {
  88. var fp = re2.exec(w);
  89. stem = fp[1];
  90. re2 = new RegExp(s_v);
  91. if (re2.test(stem)) {
  92. w = stem;
  93. re2 = /(at|bl|iz)$/;
  94. re3 = new RegExp("([^aeiouylsz])\\1$");
  95. re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
  96. if (re2.test(w))
  97. w = w + "e";
  98. else if (re3.test(w)) {
  99. re = /.$/;
  100. w = w.replace(re,"");
  101. }
  102. else if (re4.test(w))
  103. w = w + "e";
  104. }
  105. }
  106. // Step 1c
  107. re = /^(.+?)y$/;
  108. if (re.test(w)) {
  109. var fp = re.exec(w);
  110. stem = fp[1];
  111. re = new RegExp(s_v);
  112. if (re.test(stem))
  113. w = stem + "i";
  114. }
  115. // Step 2
  116. re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
  117. if (re.test(w)) {
  118. var fp = re.exec(w);
  119. stem = fp[1];
  120. suffix = fp[2];
  121. re = new RegExp(mgr0);
  122. if (re.test(stem))
  123. w = stem + step2list[suffix];
  124. }
  125. // Step 3
  126. re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
  127. if (re.test(w)) {
  128. var fp = re.exec(w);
  129. stem = fp[1];
  130. suffix = fp[2];
  131. re = new RegExp(mgr0);
  132. if (re.test(stem))
  133. w = stem + step3list[suffix];
  134. }
  135. // Step 4
  136. re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
  137. re2 = /^(.+?)(s|t)(ion)$/;
  138. if (re.test(w)) {
  139. var fp = re.exec(w);
  140. stem = fp[1];
  141. re = new RegExp(mgr1);
  142. if (re.test(stem))
  143. w = stem;
  144. }
  145. else if (re2.test(w)) {
  146. var fp = re2.exec(w);
  147. stem = fp[1] + fp[2];
  148. re2 = new RegExp(mgr1);
  149. if (re2.test(stem))
  150. w = stem;
  151. }
  152. // Step 5
  153. re = /^(.+?)e$/;
  154. if (re.test(w)) {
  155. var fp = re.exec(w);
  156. stem = fp[1];
  157. re = new RegExp(mgr1);
  158. re2 = new RegExp(meq1);
  159. re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
  160. if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
  161. w = stem;
  162. }
  163. re = /ll$/;
  164. re2 = new RegExp(mgr1);
  165. if (re.test(w) && re2.test(w)) {
  166. re = /.$/;
  167. w = w.replace(re,"");
  168. }
  169. // and turn initial Y back to y
  170. if (firstch == "y")
  171. w = firstch.toLowerCase() + w.substr(1);
  172. return w;
  173. }
  174. }
  175. /**
  176. * Simple result scoring code.
  177. */
  178. var Scorer = {
  179. // Implement the following function to further tweak the score for each result
  180. // The function takes a result array [filename, title, anchor, descr, score]
  181. // and returns the new score.
  182. /*
  183. score: function(result) {
  184. return result[4];
  185. },
  186. */
  187. // query matches the full name of an object
  188. objNameMatch: 11,
  189. // or matches in the last dotted part of the object name
  190. objPartialMatch: 6,
  191. // Additive scores depending on the priority of the object
  192. objPrio: {0: 15, // used to be importantResults
  193. 1: 5, // used to be objectResults
  194. 2: -5}, // used to be unimportantResults
  195. // Used when the priority is not in the mapping.
  196. objPrioDefault: 0,
  197. // query found in title
  198. title: 15,
  199. // query found in terms
  200. term: 5
  201. };
  202. /**
  203. * Search Module
  204. */
  205. var Search = {
  206. _index : null,
  207. _queued_query : null,
  208. _pulse_status : -1,
  209. init : function() {
  210. var params = $.getQueryParameters();
  211. if (params.q) {
  212. var query = params.q[0];
  213. $('input[name="q"]')[0].value = query;
  214. this.performSearch(query);
  215. }
  216. },
  217. loadIndex : function(url) {
  218. $.ajax({type: "GET", url: url, data: null,
  219. dataType: "script", cache: true,
  220. complete: function(jqxhr, textstatus) {
  221. if (textstatus != "success") {
  222. document.getElementById("searchindexloader").src = url;
  223. }
  224. }});
  225. },
  226. setIndex : function(index) {
  227. var q;
  228. this._index = index;
  229. if ((q = this._queued_query) !== null) {
  230. this._queued_query = null;
  231. Search.query(q);
  232. }
  233. },
  234. hasIndex : function() {
  235. return this._index !== null;
  236. },
  237. deferQuery : function(query) {
  238. this._queued_query = query;
  239. },
  240. stopPulse : function() {
  241. this._pulse_status = 0;
  242. },
  243. startPulse : function() {
  244. if (this._pulse_status >= 0)
  245. return;
  246. function pulse() {
  247. var i;
  248. Search._pulse_status = (Search._pulse_status + 1) % 4;
  249. var dotString = '';
  250. for (i = 0; i < Search._pulse_status; i++)
  251. dotString += '.';
  252. Search.dots.text(dotString);
  253. if (Search._pulse_status > -1)
  254. window.setTimeout(pulse, 500);
  255. }
  256. pulse();
  257. },
  258. /**
  259. * perform a search for something (or wait until index is loaded)
  260. */
  261. performSearch : function(query) {
  262. // create the required interface elements
  263. this.out = $('#search-results');
  264. this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
  265. this.dots = $('<span></span>').appendTo(this.title);
  266. this.status = $('<p style="display: none"></p>').appendTo(this.out);
  267. this.output = $('<ul class="search"/>').appendTo(this.out);
  268. $('#search-progress').text(_('Preparing search...'));
  269. this.startPulse();
  270. // index already loaded, the browser was quick!
  271. if (this.hasIndex())
  272. this.query(query);
  273. else
  274. this.deferQuery(query);
  275. },
  276. /**
  277. * execute search (requires search index to be loaded)
  278. */
  279. query : function(query) {
  280. var i;
  281. var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];
  282. // stem the searchterms and add them to the correct list
  283. var stemmer = new Stemmer();
  284. var searchterms = [];
  285. var excluded = [];
  286. var hlterms = [];
  287. var tmp = query.split(/\s+/);
  288. var objectterms = [];
  289. for (i = 0; i < tmp.length; i++) {
  290. if (tmp[i] !== "") {
  291. objectterms.push(tmp[i].toLowerCase());
  292. }
  293. if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
  294. tmp[i] === "") {
  295. // skip this "word"
  296. continue;
  297. }
  298. // stem the word
  299. var word = stemmer.stemWord(tmp[i].toLowerCase());
  300. var toAppend;
  301. // select the correct list
  302. if (word[0] == '-') {
  303. toAppend = excluded;
  304. word = word.substr(1);
  305. }
  306. else {
  307. toAppend = searchterms;
  308. hlterms.push(tmp[i].toLowerCase());
  309. }
  310. // only add if not already in the list
  311. if (!$u.contains(toAppend, word))
  312. toAppend.push(word);
  313. }
  314. var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
  315. // console.debug('SEARCH: searching for:');
  316. // console.info('required: ', searchterms);
  317. // console.info('excluded: ', excluded);
  318. // prepare search
  319. var terms = this._index.terms;
  320. var titleterms = this._index.titleterms;
  321. // array of [filename, title, anchor, descr, score]
  322. var results = [];
  323. $('#search-progress').empty();
  324. // lookup as object
  325. for (i = 0; i < objectterms.length; i++) {
  326. var others = [].concat(objectterms.slice(0, i),
  327. objectterms.slice(i+1, objectterms.length));
  328. results = results.concat(this.performObjectSearch(objectterms[i], others));
  329. }
  330. // lookup as search terms in fulltext
  331. results = results.concat(this.performTermsSearch(searchterms, excluded, terms, Scorer.term))
  332. .concat(this.performTermsSearch(searchterms, excluded, titleterms, Scorer.title));
  333. // let the scorer override scores with a custom scoring function
  334. if (Scorer.score) {
  335. for (i = 0; i < results.length; i++)
  336. results[i][4] = Scorer.score(results[i]);
  337. }
  338. // now sort the results by score (in opposite order of appearance, since the
  339. // display function below uses pop() to retrieve items) and then
  340. // alphabetically
  341. results.sort(function(a, b) {
  342. var left = a[4];
  343. var right = b[4];
  344. if (left > right) {
  345. return 1;
  346. } else if (left < right) {
  347. return -1;
  348. } else {
  349. // same score: sort alphabetically
  350. left = a[1].toLowerCase();
  351. right = b[1].toLowerCase();
  352. return (left > right) ? -1 : ((left < right) ? 1 : 0);
  353. }
  354. });
  355. // for debugging
  356. //Search.lastresults = results.slice(); // a copy
  357. //console.info('search results:', Search.lastresults);
  358. // print the results
  359. var resultCount = results.length;
  360. function displayNextItem() {
  361. // results left, load the summary and display it
  362. if (results.length) {
  363. var item = results.pop();
  364. var listItem = $('<li style="display:none"></li>');
  365. if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
  366. // dirhtml builder
  367. var dirname = item[0] + '/';
  368. if (dirname.match(/\/index\/$/)) {
  369. dirname = dirname.substring(0, dirname.length-6);
  370. } else if (dirname == 'index/') {
  371. dirname = '';
  372. }
  373. listItem.append($('<a/>').attr('href',
  374. DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
  375. highlightstring + item[2]).html(item[1]));
  376. } else {
  377. // normal html builders
  378. listItem.append($('<a/>').attr('href',
  379. item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
  380. highlightstring + item[2]).html(item[1]));
  381. }
  382. if (item[3]) {
  383. listItem.append($('<span> (' + item[3] + ')</span>'));
  384. Search.output.append(listItem);
  385. listItem.slideDown(5, function() {
  386. displayNextItem();
  387. });
  388. } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
  389. $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[0] + '.txt',
  390. dataType: "text",
  391. complete: function(jqxhr, textstatus) {
  392. var data = jqxhr.responseText;
  393. if (data !== '' && data !== undefined) {
  394. listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
  395. }
  396. Search.output.append(listItem);
  397. listItem.slideDown(5, function() {
  398. displayNextItem();
  399. });
  400. }});
  401. } else {
  402. // no source available, just display title
  403. Search.output.append(listItem);
  404. listItem.slideDown(5, function() {
  405. displayNextItem();
  406. });
  407. }
  408. }
  409. // search finished, update title and status message
  410. else {
  411. Search.stopPulse();
  412. Search.title.text(_('Search Results'));
  413. if (!resultCount)
  414. 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.'));
  415. else
  416. Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
  417. Search.status.fadeIn(500);
  418. }
  419. }
  420. displayNextItem();
  421. },
  422. /**
  423. * search for object names
  424. */
  425. performObjectSearch : function(object, otherterms) {
  426. var filenames = this._index.filenames;
  427. var objects = this._index.objects;
  428. var objnames = this._index.objnames;
  429. var titles = this._index.titles;
  430. var i;
  431. var results = [];
  432. for (var prefix in objects) {
  433. for (var name in objects[prefix]) {
  434. var fullname = (prefix ? prefix + '.' : '') + name;
  435. if (fullname.toLowerCase().indexOf(object) > -1) {
  436. var score = 0;
  437. var parts = fullname.split('.');
  438. // check for different match types: exact matches of full name or
  439. // "last name" (i.e. last dotted part)
  440. if (fullname == object || parts[parts.length - 1] == object) {
  441. score += Scorer.objNameMatch;
  442. // matches in last name
  443. } else if (parts[parts.length - 1].indexOf(object) > -1) {
  444. score += Scorer.objPartialMatch;
  445. }
  446. var match = objects[prefix][name];
  447. var objname = objnames[match[1]][2];
  448. var title = titles[match[0]];
  449. // If more than one term searched for, we require other words to be
  450. // found in the name/title/description
  451. if (otherterms.length > 0) {
  452. var haystack = (prefix + ' ' + name + ' ' +
  453. objname + ' ' + title).toLowerCase();
  454. var allfound = true;
  455. for (i = 0; i < otherterms.length; i++) {
  456. if (haystack.indexOf(otherterms[i]) == -1) {
  457. allfound = false;
  458. break;
  459. }
  460. }
  461. if (!allfound) {
  462. continue;
  463. }
  464. }
  465. var descr = objname + _(', in ') + title;
  466. var anchor = match[3];
  467. if (anchor === '')
  468. anchor = fullname;
  469. else if (anchor == '-')
  470. anchor = objnames[match[1]][1] + '-' + fullname;
  471. // add custom score for some objects according to scorer
  472. if (Scorer.objPrio.hasOwnProperty(match[2])) {
  473. score += Scorer.objPrio[match[2]];
  474. } else {
  475. score += Scorer.objPrioDefault;
  476. }
  477. results.push([filenames[match[0]], fullname, '#'+anchor, descr, score]);
  478. }
  479. }
  480. }
  481. return results;
  482. },
  483. /**
  484. * search for full-text terms in the index
  485. */
  486. performTermsSearch : function(searchterms, excluded, terms, score) {
  487. var filenames = this._index.filenames;
  488. var titles = this._index.titles;
  489. var i, j, file, files;
  490. var fileMap = {};
  491. var results = [];
  492. // perform the search on the required terms
  493. for (i = 0; i < searchterms.length; i++) {
  494. var word = searchterms[i];
  495. // no match but word was a required one
  496. if ((files = terms[word]) === undefined)
  497. break;
  498. if (files.length === undefined) {
  499. files = [files];
  500. }
  501. // create the mapping
  502. for (j = 0; j < files.length; j++) {
  503. file = files[j];
  504. if (file in fileMap)
  505. fileMap[file].push(word);
  506. else
  507. fileMap[file] = [word];
  508. }
  509. }
  510. // now check if the files don't contain excluded terms
  511. for (file in fileMap) {
  512. var valid = true;
  513. // check if all requirements are matched
  514. if (fileMap[file].length != searchterms.length)
  515. continue;
  516. // ensure that none of the excluded terms is in the search result
  517. for (i = 0; i < excluded.length; i++) {
  518. if (terms[excluded[i]] == file ||
  519. $u.contains(terms[excluded[i]] || [], file)) {
  520. valid = false;
  521. break;
  522. }
  523. }
  524. // if we have still a valid result we can add it to the result list
  525. if (valid) {
  526. results.push([filenames[file], titles[file], '', null, score]);
  527. }
  528. }
  529. return results;
  530. },
  531. /**
  532. * helper function to return a node containing the
  533. * search summary for a given text. keywords is a list
  534. * of stemmed words, hlwords is the list of normal, unstemmed
  535. * words. the first one is used to find the occurance, the
  536. * latter for highlighting it.
  537. */
  538. makeSearchSummary : function(text, keywords, hlwords) {
  539. var textLower = text.toLowerCase();
  540. var start = 0;
  541. $.each(keywords, function() {
  542. var i = textLower.indexOf(this.toLowerCase());
  543. if (i > -1)
  544. start = i;
  545. });
  546. start = Math.max(start - 120, 0);
  547. var excerpt = ((start > 0) ? '...' : '') +
  548. $.trim(text.substr(start, 240)) +
  549. ((start + 240 - text.length) ? '...' : '');
  550. var rv = $('<div class="context"></div>').text(excerpt);
  551. $.each(hlwords, function() {
  552. rv = rv.highlightText(this, 'highlighted');
  553. });
  554. return rv;
  555. }
  556. };
  557. $(document).ready(function() {
  558. Search.init();
  559. });