PageRenderTime 36ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/_static/searchtools.js

https://bitbucket.org/ianb/silverlining/
JavaScript | 467 lines | 366 code | 47 blank | 54 comment | 77 complexity | c784e28784239905cb99ff23067fb72d MD5 | raw file
Possible License(s): GPL-2.0
  1. /**
  2. * helper function to return a node containing the
  3. * search summary for a given text. keywords is a list
  4. * of stemmed words, hlwords is the list of normal, unstemmed
  5. * words. the first one is used to find the occurance, the
  6. * latter for highlighting it.
  7. */
  8. jQuery.makeSearchSummary = function(text, keywords, hlwords) {
  9. var textLower = text.toLowerCase();
  10. var start = 0;
  11. $.each(keywords, function() {
  12. var i = textLower.indexOf(this.toLowerCase());
  13. if (i > -1)
  14. start = i;
  15. });
  16. start = Math.max(start - 120, 0);
  17. var excerpt = ((start > 0) ? '...' : '') +
  18. $.trim(text.substr(start, 240)) +
  19. ((start + 240 - text.length) ? '...' : '');
  20. var rv = $('<div class="context"></div>').text(excerpt);
  21. $.each(hlwords, function() {
  22. rv = rv.highlightText(this, 'highlight');
  23. });
  24. return rv;
  25. }
  26. /**
  27. * Porter Stemmer
  28. */
  29. var PorterStemmer = function() {
  30. var step2list = {
  31. ational: 'ate',
  32. tional: 'tion',
  33. enci: 'ence',
  34. anci: 'ance',
  35. izer: 'ize',
  36. bli: 'ble',
  37. alli: 'al',
  38. entli: 'ent',
  39. eli: 'e',
  40. ousli: 'ous',
  41. ization: 'ize',
  42. ation: 'ate',
  43. ator: 'ate',
  44. alism: 'al',
  45. iveness: 'ive',
  46. fulness: 'ful',
  47. ousness: 'ous',
  48. aliti: 'al',
  49. iviti: 'ive',
  50. biliti: 'ble',
  51. logi: 'log'
  52. };
  53. var step3list = {
  54. icate: 'ic',
  55. ative: '',
  56. alize: 'al',
  57. iciti: 'ic',
  58. ical: 'ic',
  59. ful: '',
  60. ness: ''
  61. };
  62. var c = "[^aeiou]"; // consonant
  63. var v = "[aeiouy]"; // vowel
  64. var C = c + "[^aeiouy]*"; // consonant sequence
  65. var V = v + "[aeiou]*"; // vowel sequence
  66. var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
  67. var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
  68. var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
  69. var s_v = "^(" + C + ")?" + v; // vowel in stem
  70. this.stemWord = function (w) {
  71. var stem;
  72. var suffix;
  73. var firstch;
  74. var origword = w;
  75. if (w.length < 3)
  76. return w;
  77. var re;
  78. var re2;
  79. var re3;
  80. var re4;
  81. firstch = w.substr(0,1);
  82. if (firstch == "y")
  83. w = firstch.toUpperCase() + w.substr(1);
  84. // Step 1a
  85. re = /^(.+?)(ss|i)es$/;
  86. re2 = /^(.+?)([^s])s$/;
  87. if (re.test(w))
  88. w = w.replace(re,"$1$2");
  89. else if (re2.test(w))
  90. w = w.replace(re2,"$1$2");
  91. // Step 1b
  92. re = /^(.+?)eed$/;
  93. re2 = /^(.+?)(ed|ing)$/;
  94. if (re.test(w)) {
  95. var fp = re.exec(w);
  96. re = new RegExp(mgr0);
  97. if (re.test(fp[1])) {
  98. re = /.$/;
  99. w = w.replace(re,"");
  100. }
  101. }
  102. else if (re2.test(w)) {
  103. var fp = re2.exec(w);
  104. stem = fp[1];
  105. re2 = new RegExp(s_v);
  106. if (re2.test(stem)) {
  107. w = stem;
  108. re2 = /(at|bl|iz)$/;
  109. re3 = new RegExp("([^aeiouylsz])\\1$");
  110. re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
  111. if (re2.test(w))
  112. w = w + "e";
  113. else if (re3.test(w)) {
  114. re = /.$/;
  115. w = w.replace(re,"");
  116. }
  117. else if (re4.test(w))
  118. w = w + "e";
  119. }
  120. }
  121. // Step 1c
  122. re = /^(.+?)y$/;
  123. if (re.test(w)) {
  124. var fp = re.exec(w);
  125. stem = fp[1];
  126. re = new RegExp(s_v);
  127. if (re.test(stem))
  128. w = stem + "i";
  129. }
  130. // Step 2
  131. re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
  132. if (re.test(w)) {
  133. var fp = re.exec(w);
  134. stem = fp[1];
  135. suffix = fp[2];
  136. re = new RegExp(mgr0);
  137. if (re.test(stem))
  138. w = stem + step2list[suffix];
  139. }
  140. // Step 3
  141. re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
  142. if (re.test(w)) {
  143. var fp = re.exec(w);
  144. stem = fp[1];
  145. suffix = fp[2];
  146. re = new RegExp(mgr0);
  147. if (re.test(stem))
  148. w = stem + step3list[suffix];
  149. }
  150. // Step 4
  151. re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
  152. re2 = /^(.+?)(s|t)(ion)$/;
  153. if (re.test(w)) {
  154. var fp = re.exec(w);
  155. stem = fp[1];
  156. re = new RegExp(mgr1);
  157. if (re.test(stem))
  158. w = stem;
  159. }
  160. else if (re2.test(w)) {
  161. var fp = re2.exec(w);
  162. stem = fp[1] + fp[2];
  163. re2 = new RegExp(mgr1);
  164. if (re2.test(stem))
  165. w = stem;
  166. }
  167. // Step 5
  168. re = /^(.+?)e$/;
  169. if (re.test(w)) {
  170. var fp = re.exec(w);
  171. stem = fp[1];
  172. re = new RegExp(mgr1);
  173. re2 = new RegExp(meq1);
  174. re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
  175. if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
  176. w = stem;
  177. }
  178. re = /ll$/;
  179. re2 = new RegExp(mgr1);
  180. if (re.test(w) && re2.test(w)) {
  181. re = /.$/;
  182. w = w.replace(re,"");
  183. }
  184. // and turn initial Y back to y
  185. if (firstch == "y")
  186. w = firstch.toLowerCase() + w.substr(1);
  187. return w;
  188. }
  189. }
  190. /**
  191. * Search Module
  192. */
  193. var Search = {
  194. _index : null,
  195. _queued_query : null,
  196. _pulse_status : -1,
  197. init : function() {
  198. var params = $.getQueryParameters();
  199. if (params.q) {
  200. var query = params.q[0];
  201. $('input[name="q"]')[0].value = query;
  202. this.performSearch(query);
  203. }
  204. },
  205. /**
  206. * Sets the index
  207. */
  208. setIndex : function(index) {
  209. var q;
  210. this._index = index;
  211. if ((q = this._queued_query) !== null) {
  212. this._queued_query = null;
  213. Search.query(q);
  214. }
  215. },
  216. hasIndex : function() {
  217. return this._index !== null;
  218. },
  219. deferQuery : function(query) {
  220. this._queued_query = query;
  221. },
  222. stopPulse : function() {
  223. this._pulse_status = 0;
  224. },
  225. startPulse : function() {
  226. if (this._pulse_status >= 0)
  227. return;
  228. function pulse() {
  229. Search._pulse_status = (Search._pulse_status + 1) % 4;
  230. var dotString = '';
  231. for (var i = 0; i < Search._pulse_status; i++)
  232. dotString += '.';
  233. Search.dots.text(dotString);
  234. if (Search._pulse_status > -1)
  235. window.setTimeout(pulse, 500);
  236. };
  237. pulse();
  238. },
  239. /**
  240. * perform a search for something
  241. */
  242. performSearch : function(query) {
  243. // create the required interface elements
  244. this.out = $('#search-results');
  245. this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
  246. this.dots = $('<span></span>').appendTo(this.title);
  247. this.status = $('<p style="display: none"></p>').appendTo(this.out);
  248. this.output = $('<ul class="search"/>').appendTo(this.out);
  249. $('#search-progress').text(_('Preparing search...'));
  250. this.startPulse();
  251. // index already loaded, the browser was quick!
  252. if (this.hasIndex())
  253. this.query(query);
  254. else
  255. this.deferQuery(query);
  256. },
  257. query : function(query) {
  258. // stem the searchterms and add them to the
  259. // correct list
  260. var stemmer = new PorterStemmer();
  261. var searchterms = [];
  262. var excluded = [];
  263. var hlterms = [];
  264. var tmp = query.split(/\s+/);
  265. var object = (tmp.length == 1) ? tmp[0].toLowerCase() : null;
  266. for (var i = 0; i < tmp.length; i++) {
  267. // stem the word
  268. var word = stemmer.stemWord(tmp[i]).toLowerCase();
  269. // select the correct list
  270. if (word[0] == '-') {
  271. var toAppend = excluded;
  272. word = word.substr(1);
  273. }
  274. else {
  275. var toAppend = searchterms;
  276. hlterms.push(tmp[i].toLowerCase());
  277. }
  278. // only add if not already in the list
  279. if (!$.contains(toAppend, word))
  280. toAppend.push(word);
  281. };
  282. var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
  283. console.debug('SEARCH: searching for:');
  284. console.info('required: ', searchterms);
  285. console.info('excluded: ', excluded);
  286. // prepare search
  287. var filenames = this._index.filenames;
  288. var titles = this._index.titles;
  289. var terms = this._index.terms;
  290. var descrefs = this._index.descrefs;
  291. var modules = this._index.modules;
  292. var desctypes = this._index.desctypes;
  293. var fileMap = {};
  294. var files = null;
  295. var objectResults = [];
  296. var regularResults = [];
  297. $('#search-progress').empty();
  298. // lookup as object
  299. if (object != null) {
  300. for (var module in modules) {
  301. if (module.indexOf(object) > -1) {
  302. fn = modules[module];
  303. descr = _('module, in ') + titles[fn];
  304. objectResults.push([filenames[fn], module, '#module-'+module, descr]);
  305. }
  306. }
  307. for (var prefix in descrefs) {
  308. for (var name in descrefs[prefix]) {
  309. var fullname = (prefix ? prefix + '.' : '') + name;
  310. if (fullname.toLowerCase().indexOf(object) > -1) {
  311. match = descrefs[prefix][name];
  312. descr = desctypes[match[1]] + _(', in ') + titles[match[0]];
  313. objectResults.push([filenames[match[0]], fullname, '#'+fullname, descr]);
  314. }
  315. }
  316. }
  317. }
  318. // sort results descending
  319. objectResults.sort(function(a, b) {
  320. return (a[1] > b[1]) ? -1 : ((a[1] < b[1]) ? 1 : 0);
  321. });
  322. // perform the search on the required terms
  323. for (var i = 0; i < searchterms.length; i++) {
  324. var word = searchterms[i];
  325. // no match but word was a required one
  326. if ((files = terms[word]) == null)
  327. break;
  328. if (files.length == undefined) {
  329. files = [files];
  330. }
  331. // create the mapping
  332. for (var j = 0; j < files.length; j++) {
  333. var file = files[j];
  334. if (file in fileMap)
  335. fileMap[file].push(word);
  336. else
  337. fileMap[file] = [word];
  338. }
  339. }
  340. // now check if the files don't contain excluded terms
  341. for (var file in fileMap) {
  342. var valid = true;
  343. // check if all requirements are matched
  344. if (fileMap[file].length != searchterms.length)
  345. continue;
  346. // ensure that none of the excluded terms is in the
  347. // search result.
  348. for (var i = 0; i < excluded.length; i++) {
  349. if (terms[excluded[i]] == file ||
  350. $.contains(terms[excluded[i]] || [], file)) {
  351. valid = false;
  352. break;
  353. }
  354. }
  355. // if we have still a valid result we can add it
  356. // to the result list
  357. if (valid)
  358. regularResults.push([filenames[file], titles[file], '', null]);
  359. }
  360. // delete unused variables in order to not waste
  361. // memory until list is retrieved completely
  362. delete filenames, titles, terms;
  363. // now sort the regular results descending by title
  364. regularResults.sort(function(a, b) {
  365. var left = a[1].toLowerCase();
  366. var right = b[1].toLowerCase();
  367. return (left > right) ? -1 : ((left < right) ? 1 : 0);
  368. });
  369. // combine both
  370. var results = regularResults.concat(objectResults);
  371. // print the results
  372. var resultCount = results.length;
  373. function displayNextItem() {
  374. // results left, load the summary and display it
  375. if (results.length) {
  376. var item = results.pop();
  377. var listItem = $('<li style="display:none"></li>');
  378. listItem.append($('<a/>').attr(
  379. 'href',
  380. item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
  381. highlightstring + item[2]).html(item[1]));
  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. $.get('_sources/' + item[0] + '.txt', function(data) {
  390. listItem.append($.makeSearchSummary(data, searchterms, hlterms));
  391. Search.output.append(listItem);
  392. listItem.slideDown(5, function() {
  393. displayNextItem();
  394. });
  395. });
  396. } else {
  397. // no source available, just display title
  398. Search.output.append(listItem);
  399. listItem.slideDown(5, function() {
  400. displayNextItem();
  401. });
  402. }
  403. }
  404. // search finished, update title and status message
  405. else {
  406. Search.stopPulse();
  407. Search.title.text(_('Search Results'));
  408. if (!resultCount)
  409. 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.'));
  410. else
  411. Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
  412. Search.status.fadeIn(500);
  413. }
  414. }
  415. displayNextItem();
  416. }
  417. }
  418. $(document).ready(function() {
  419. Search.init();
  420. });