Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

searchtools.js 16 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
  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. if (DOCUMENTATION_OPTIONS.BUILDER === 'dirhtml') {
  226. // dirhtml builder
  227. var dirname = item[0] + '/';
  228. if (dirname.match(/\/index\/$/)) {
  229. dirname = dirname.substring(0, dirname.length-6);
  230. } else if (dirname == 'index/') {
  231. dirname = '';
  232. }
  233. requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + dirname;
  234. } else {
  235. // normal html builders
  236. requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX;
  237. }
  238. listItem.append($('<a/>').attr('href',
  239. requestUrl +
  240. highlightstring + item[2]).html(item[1]));
  241. if (item[3]) {
  242. listItem.append($('<span> (' + item[3] + ')</span>'));
  243. Search.output.append(listItem);
  244. listItem.slideDown(5, function() {
  245. displayNextItem();
  246. });
  247. } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
  248. $.ajax({url: requestUrl,
  249. dataType: "text",
  250. complete: function(jqxhr, textstatus) {
  251. var data = jqxhr.responseText;
  252. if (data !== '' && data !== undefined) {
  253. listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
  254. }
  255. Search.output.append(listItem);
  256. listItem.slideDown(5, function() {
  257. displayNextItem();
  258. });
  259. }});
  260. } else {
  261. // no source available, just display title
  262. Search.output.append(listItem);
  263. listItem.slideDown(5, function() {
  264. displayNextItem();
  265. });
  266. }
  267. }
  268. // search finished, update title and status message
  269. else {
  270. Search.stopPulse();
  271. Search.title.text(_('Search Results'));
  272. if (!resultCount)
  273. 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.'));
  274. else
  275. Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
  276. Search.status.fadeIn(500);
  277. }
  278. }
  279. displayNextItem();
  280. },
  281. /**
  282. * search for object names
  283. */
  284. performObjectSearch : function(object, otherterms) {
  285. var filenames = this._index.filenames;
  286. var docnames = this._index.docnames;
  287. var objects = this._index.objects;
  288. var objnames = this._index.objnames;
  289. var titles = this._index.titles;
  290. var i;
  291. var results = [];
  292. for (var prefix in objects) {
  293. for (var name in objects[prefix]) {
  294. var fullname = (prefix ? prefix + '.' : '') + name;
  295. var fullnameLower = fullname.toLowerCase()
  296. if (fullnameLower.indexOf(object) > -1) {
  297. var score = 0;
  298. var parts = fullnameLower.split('.');
  299. // check for different match types: exact matches of full name or
  300. // "last name" (i.e. last dotted part)
  301. if (fullnameLower == object || parts[parts.length - 1] == object) {
  302. score += Scorer.objNameMatch;
  303. // matches in last name
  304. } else if (parts[parts.length - 1].indexOf(object) > -1) {
  305. score += Scorer.objPartialMatch;
  306. }
  307. var match = objects[prefix][name];
  308. var objname = objnames[match[1]][2];
  309. var title = titles[match[0]];
  310. // If more than one term searched for, we require other words to be
  311. // found in the name/title/description
  312. if (otherterms.length > 0) {
  313. var haystack = (prefix + ' ' + name + ' ' +
  314. objname + ' ' + title).toLowerCase();
  315. var allfound = true;
  316. for (i = 0; i < otherterms.length; i++) {
  317. if (haystack.indexOf(otherterms[i]) == -1) {
  318. allfound = false;
  319. break;
  320. }
  321. }
  322. if (!allfound) {
  323. continue;
  324. }
  325. }
  326. var descr = objname + _(', in ') + title;
  327. var anchor = match[3];
  328. if (anchor === '')
  329. anchor = fullname;
  330. else if (anchor == '-')
  331. anchor = objnames[match[1]][1] + '-' + fullname;
  332. // add custom score for some objects according to scorer
  333. if (Scorer.objPrio.hasOwnProperty(match[2])) {
  334. score += Scorer.objPrio[match[2]];
  335. } else {
  336. score += Scorer.objPrioDefault;
  337. }
  338. results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
  339. }
  340. }
  341. }
  342. return results;
  343. },
  344. /**
  345. * search for full-text terms in the index
  346. */
  347. performTermsSearch : function(searchterms, excluded, terms, titleterms) {
  348. var docnames = this._index.docnames;
  349. var filenames = this._index.filenames;
  350. var titles = this._index.titles;
  351. var i, j, file;
  352. var fileMap = {};
  353. var scoreMap = {};
  354. var results = [];
  355. // perform the search on the required terms
  356. for (i = 0; i < searchterms.length; i++) {
  357. var word = searchterms[i];
  358. var files = [];
  359. var _o = [
  360. {files: terms[word], score: Scorer.term},
  361. {files: titleterms[word], score: Scorer.title}
  362. ];
  363. // add support for partial matches
  364. if (word.length > 2) {
  365. for (var w in terms) {
  366. if (w.match(word) && !terms[word]) {
  367. _o.push({files: terms[w], score: Scorer.partialTerm})
  368. }
  369. }
  370. for (var w in titleterms) {
  371. if (w.match(word) && !titleterms[word]) {
  372. _o.push({files: titleterms[w], score: Scorer.partialTitle})
  373. }
  374. }
  375. }
  376. // no match but word was a required one
  377. if ($u.every(_o, function(o){return o.files === undefined;})) {
  378. break;
  379. }
  380. // found search word in contents
  381. $u.each(_o, function(o) {
  382. var _files = o.files;
  383. if (_files === undefined)
  384. return
  385. if (_files.length === undefined)
  386. _files = [_files];
  387. files = files.concat(_files);
  388. // set score for the word in each file to Scorer.term
  389. for (j = 0; j < _files.length; j++) {
  390. file = _files[j];
  391. if (!(file in scoreMap))
  392. scoreMap[file] = {};
  393. scoreMap[file][word] = o.score;
  394. }
  395. });
  396. // create the mapping
  397. for (j = 0; j < files.length; j++) {
  398. file = files[j];
  399. if (file in fileMap && fileMap[file].indexOf(word) === -1)
  400. fileMap[file].push(word);
  401. else
  402. fileMap[file] = [word];
  403. }
  404. }
  405. // now check if the files don't contain excluded terms
  406. for (file in fileMap) {
  407. var valid = true;
  408. // check if all requirements are matched
  409. var filteredTermCount = // as search terms with length < 3 are discarded: ignore
  410. searchterms.filter(function(term){return term.length > 2}).length
  411. if (
  412. fileMap[file].length != searchterms.length &&
  413. fileMap[file].length != filteredTermCount
  414. ) continue;
  415. // ensure that none of the excluded terms is in the search result
  416. for (i = 0; i < excluded.length; i++) {
  417. if (terms[excluded[i]] == file ||
  418. titleterms[excluded[i]] == file ||
  419. $u.contains(terms[excluded[i]] || [], file) ||
  420. $u.contains(titleterms[excluded[i]] || [], file)) {
  421. valid = false;
  422. break;
  423. }
  424. }
  425. // if we have still a valid result we can add it to the result list
  426. if (valid) {
  427. // select one (max) score for the file.
  428. // for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
  429. var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
  430. results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
  431. }
  432. }
  433. return results;
  434. },
  435. /**
  436. * helper function to return a node containing the
  437. * search summary for a given text. keywords is a list
  438. * of stemmed words, hlwords is the list of normal, unstemmed
  439. * words. the first one is used to find the occurrence, the
  440. * latter for highlighting it.
  441. */
  442. makeSearchSummary : function(htmlText, keywords, hlwords) {
  443. var text = Search.htmlToText(htmlText);
  444. var textLower = text.toLowerCase();
  445. var start = 0;
  446. $.each(keywords, function() {
  447. var i = textLower.indexOf(this.toLowerCase());
  448. if (i > -1)
  449. start = i;
  450. });
  451. start = Math.max(start - 120, 0);
  452. var excerpt = ((start > 0) ? '...' : '') +
  453. $.trim(text.substr(start, 240)) +
  454. ((start + 240 - text.length) ? '...' : '');
  455. var rv = $('<div class="context"></div>').text(excerpt);
  456. $.each(hlwords, function() {
  457. rv = rv.highlightText(this, 'highlighted');
  458. });
  459. return rv;
  460. }
  461. };
  462. $(document).ready(function() {
  463. Search.init();
  464. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...