5 * Sphinx JavaScript utilities for the full-text search.
7 * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
8 * :license: BSD, see LICENSE for details.
14 * Simple result scoring code.
17 // Implement the following function to further tweak the score for each result
18 // The function takes a result array [filename, title, anchor, descr, score]
19 // and returns the new score.
21 score: function(result) {
26 // query matches the full name of an object
28 // or matches in the last dotted part of the object name
30 // Additive scores depending on the priority of the object
31 objPrio: {0: 15, // used to be importantResults
32 1: 5, // used to be objectResults
33 2: -5}, // used to be unimportantResults
34 // Used when the priority is not in the mapping.
37 // query found in title
40 // query found in terms
47 function splitQuery(query) {
48 return query.split(/\s+/);
61 htmlToText : function(htmlString) {
62 var virtualDocument = document.implementation.createHTMLDocument('virtual');
63 var htmlElement = $(htmlString, virtualDocument);
64 htmlElement.find('.headerlink').remove();
65 docContent = htmlElement.find('[role=main]')[0];
66 if(docContent === undefined) {
67 console.warn("Content block not found. Sphinx search tries to obtain it " +
68 "via '[role=main]'. Could you check your theme or template.");
71 return docContent.textContent || docContent.innerText;
75 var params = $.getQueryParameters();
77 var query = params.q[0];
78 $('input[name="q"]')[0].value = query;
79 this.performSearch(query);
83 loadIndex : function(url) {
84 $.ajax({type: "GET", url: url, data: null,
85 dataType: "script", cache: true,
86 complete: function(jqxhr, textstatus) {
87 if (textstatus != "success") {
88 document.getElementById("searchindexloader").src = url;
93 setIndex : function(index) {
96 if ((q = this._queued_query) !== null) {
97 this._queued_query = null;
102 hasIndex : function() {
103 return this._index !== null;
106 deferQuery : function(query) {
107 this._queued_query = query;
110 stopPulse : function() {
111 this._pulse_status = 0;
114 startPulse : function() {
115 if (this._pulse_status >= 0)
119 Search._pulse_status = (Search._pulse_status + 1) % 4;
121 for (i = 0; i < Search._pulse_status; i++)
123 Search.dots.text(dotString);
124 if (Search._pulse_status > -1)
125 window.setTimeout(pulse, 500);
131 * perform a search for something (or wait until index is loaded)
133 performSearch : function(query) {
134 // create the required interface elements
135 this.out = $('#search-results');
136 this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
137 this.dots = $('<span></span>').appendTo(this.title);
138 this.status = $('<p class="search-summary"> </p>').appendTo(this.out);
139 this.output = $('<ul class="search"/>').appendTo(this.out);
141 $('#search-progress').text(_('Preparing search...'));
144 // index already loaded, the browser was quick!
148 this.deferQuery(query);
152 * execute search (requires search index to be loaded)
154 query : function(query) {
157 // stem the searchterms and add them to the correct list
158 var stemmer = new Stemmer();
159 var searchterms = [];
162 var tmp = splitQuery(query);
163 var objectterms = [];
164 for (i = 0; i < tmp.length; i++) {
166 objectterms.push(tmp[i].toLowerCase());
169 if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i] === "") {
174 var word = stemmer.stemWord(tmp[i].toLowerCase());
175 // prevent stemmer from cutting word smaller than two chars
176 if(word.length < 3 && tmp[i].length >= 3) {
180 // select the correct list
181 if (word[0] == '-') {
183 word = word.substr(1);
186 toAppend = searchterms;
187 hlterms.push(tmp[i].toLowerCase());
189 // only add if not already in the list
190 if (!$u.contains(toAppend, word))
193 var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
195 // console.debug('SEARCH: searching for:');
196 // console.info('required: ', searchterms);
197 // console.info('excluded: ', excluded);
200 var terms = this._index.terms;
201 var titleterms = this._index.titleterms;
203 // array of [filename, title, anchor, descr, score]
205 $('#search-progress').empty();
208 for (i = 0; i < objectterms.length; i++) {
209 var others = [].concat(objectterms.slice(0, i),
210 objectterms.slice(i+1, objectterms.length));
211 results = results.concat(this.performObjectSearch(objectterms[i], others));
214 // lookup as search terms in fulltext
215 results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
217 // let the scorer override scores with a custom scoring function
219 for (i = 0; i < results.length; i++)
220 results[i][4] = Scorer.score(results[i]);
223 // now sort the results by score (in opposite order of appearance, since the
224 // display function below uses pop() to retrieve items) and then
226 results.sort(function(a, b) {
231 } else if (left < right) {
234 // same score: sort alphabetically
235 left = a[1].toLowerCase();
236 right = b[1].toLowerCase();
237 return (left > right) ? -1 : ((left < right) ? 1 : 0);
242 //Search.lastresults = results.slice(); // a copy
243 //console.info('search results:', Search.lastresults);
246 var resultCount = results.length;
247 function displayNextItem() {
248 // results left, load the summary and display it
249 if (results.length) {
250 var item = results.pop();
251 var listItem = $('<li></li>');
254 if (DOCUMENTATION_OPTIONS.BUILDER === 'dirhtml') {
256 var dirname = item[0] + '/';
257 if (dirname.match(/\/index\/$/)) {
258 dirname = dirname.substring(0, dirname.length-6);
259 } else if (dirname == 'index/') {
262 requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + dirname;
263 linkUrl = requestUrl;
266 // normal html builders
267 requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX;
268 linkUrl = item[0] + DOCUMENTATION_OPTIONS.LINK_SUFFIX;
270 listItem.append($('<a/>').attr('href',
272 highlightstring + item[2]).html(item[1]));
274 listItem.append($('<span> (' + item[3] + ')</span>'));
275 Search.output.append(listItem);
276 setTimeout(function() {
279 } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
280 $.ajax({url: requestUrl,
282 complete: function(jqxhr, textstatus) {
283 var data = jqxhr.responseText;
284 if (data !== '' && data !== undefined) {
285 var summary = Search.makeSearchSummary(data, searchterms, hlterms);
287 listItem.append(summary);
290 Search.output.append(listItem);
291 setTimeout(function() {
296 // no source available, just display title
297 Search.output.append(listItem);
298 setTimeout(function() {
303 // search finished, update title and status message
306 Search.title.text(_('Search Results'));
308 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.'));
310 Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
311 Search.status.fadeIn(500);
318 * search for object names
320 performObjectSearch : function(object, otherterms) {
321 var filenames = this._index.filenames;
322 var docnames = this._index.docnames;
323 var objects = this._index.objects;
324 var objnames = this._index.objnames;
325 var titles = this._index.titles;
330 for (var prefix in objects) {
331 for (var iMatch = 0; iMatch != objects[prefix].length; ++iMatch) {
332 var match = objects[prefix][iMatch];
334 var fullname = (prefix ? prefix + '.' : '') + name;
335 var fullnameLower = fullname.toLowerCase()
336 if (fullnameLower.indexOf(object) > -1) {
338 var parts = fullnameLower.split('.');
339 // check for different match types: exact matches of full name or
340 // "last name" (i.e. last dotted part)
341 if (fullnameLower == object || parts[parts.length - 1] == object) {
342 score += Scorer.objNameMatch;
343 // matches in last name
344 } else if (parts[parts.length - 1].indexOf(object) > -1) {
345 score += Scorer.objPartialMatch;
347 var objname = objnames[match[1]][2];
348 var title = titles[match[0]];
349 // If more than one term searched for, we require other words to be
350 // found in the name/title/description
351 if (otherterms.length > 0) {
352 var haystack = (prefix + ' ' + name + ' ' +
353 objname + ' ' + title).toLowerCase();
355 for (i = 0; i < otherterms.length; i++) {
356 if (haystack.indexOf(otherterms[i]) == -1) {
365 var descr = objname + _(', in ') + title;
367 var anchor = match[3];
370 else if (anchor == '-')
371 anchor = objnames[match[1]][1] + '-' + fullname;
372 // add custom score for some objects according to scorer
373 if (Scorer.objPrio.hasOwnProperty(match[2])) {
374 score += Scorer.objPrio[match[2]];
376 score += Scorer.objPrioDefault;
378 results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
387 * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
389 escapeRegExp : function(string) {
390 return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
394 * search for full-text terms in the index
396 performTermsSearch : function(searchterms, excluded, terms, titleterms) {
397 var docnames = this._index.docnames;
398 var filenames = this._index.filenames;
399 var titles = this._index.titles;
406 // perform the search on the required terms
407 for (i = 0; i < searchterms.length; i++) {
408 var word = searchterms[i];
411 {files: terms[word], score: Scorer.term},
412 {files: titleterms[word], score: Scorer.title}
414 // add support for partial matches
415 if (word.length > 2) {
416 var word_regex = this.escapeRegExp(word);
417 for (var w in terms) {
418 if (w.match(word_regex) && !terms[word]) {
419 _o.push({files: terms[w], score: Scorer.partialTerm})
422 for (var w in titleterms) {
423 if (w.match(word_regex) && !titleterms[word]) {
424 _o.push({files: titleterms[w], score: Scorer.partialTitle})
429 // no match but word was a required one
430 if ($u.every(_o, function(o){return o.files === undefined;})) {
433 // found search word in contents
434 $u.each(_o, function(o) {
435 var _files = o.files;
436 if (_files === undefined)
439 if (_files.length === undefined)
441 files = files.concat(_files);
443 // set score for the word in each file to Scorer.term
444 for (j = 0; j < _files.length; j++) {
446 if (!(file in scoreMap))
448 scoreMap[file][word] = o.score;
452 // create the mapping
453 for (j = 0; j < files.length; j++) {
455 if (file in fileMap && fileMap[file].indexOf(word) === -1)
456 fileMap[file].push(word);
458 fileMap[file] = [word];
462 // now check if the files don't contain excluded terms
463 for (file in fileMap) {
466 // check if all requirements are matched
467 var filteredTermCount = // as search terms with length < 3 are discarded: ignore
468 searchterms.filter(function(term){return term.length > 2}).length
470 fileMap[file].length != searchterms.length &&
471 fileMap[file].length != filteredTermCount
474 // ensure that none of the excluded terms is in the search result
475 for (i = 0; i < excluded.length; i++) {
476 if (terms[excluded[i]] == file ||
477 titleterms[excluded[i]] == file ||
478 $u.contains(terms[excluded[i]] || [], file) ||
479 $u.contains(titleterms[excluded[i]] || [], file)) {
485 // if we have still a valid result we can add it to the result list
487 // select one (max) score for the file.
488 // for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
489 var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
490 results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
497 * helper function to return a node containing the
498 * search summary for a given text. keywords is a list
499 * of stemmed words, hlwords is the list of normal, unstemmed
500 * words. the first one is used to find the occurrence, the
501 * latter for highlighting it.
503 makeSearchSummary : function(htmlText, keywords, hlwords) {
504 var text = Search.htmlToText(htmlText);
508 var textLower = text.toLowerCase();
510 $.each(keywords, function() {
511 var i = textLower.indexOf(this.toLowerCase());
515 start = Math.max(start - 120, 0);
516 var excerpt = ((start > 0) ? '...' : '') +
517 $.trim(text.substr(start, 240)) +
518 ((start + 240 - text.length) ? '...' : '');
519 var rv = $('<p class="context"></p>').text(excerpt);
520 $.each(hlwords, function() {
521 rv = rv.highlightText(this, 'highlighted');
527 $(document).ready(function() {