5 * Sphinx JavaScript utilities for the full-text search.
7 * :copyright: Copyright 2007-2019 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
39 // query found in terms
45 function splitQuery(query) {
46 return query.split(/\s+/);
60 var params = $.getQueryParameters();
62 var query = params.q[0];
63 $('input[name="q"]')[0].value = query;
64 this.performSearch(query);
68 loadIndex : function(url) {
69 $.ajax({type: "GET", url: url, data: null,
70 dataType: "script", cache: true,
71 complete: function(jqxhr, textstatus) {
72 if (textstatus != "success") {
73 document.getElementById("searchindexloader").src = url;
78 setIndex : function(index) {
81 if ((q = this._queued_query) !== null) {
82 this._queued_query = null;
87 hasIndex : function() {
88 return this._index !== null;
91 deferQuery : function(query) {
92 this._queued_query = query;
95 stopPulse : function() {
96 this._pulse_status = 0;
99 startPulse : function() {
100 if (this._pulse_status >= 0)
104 Search._pulse_status = (Search._pulse_status + 1) % 4;
106 for (i = 0; i < Search._pulse_status; i++)
108 Search.dots.text(dotString);
109 if (Search._pulse_status > -1)
110 window.setTimeout(pulse, 500);
116 * perform a search for something (or wait until index is loaded)
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 style="display: none"></p>').appendTo(this.out);
124 this.output = $('<ul class="search"/>').appendTo(this.out);
126 $('#search-progress').text(_('Preparing search...'));
129 // index already loaded, the browser was quick!
133 this.deferQuery(query);
137 * execute search (requires search index to be loaded)
139 query : function(query) {
142 // stem the searchterms and add them to the correct list
143 var stemmer = new Stemmer();
144 var searchterms = [];
147 var tmp = splitQuery(query);
148 var objectterms = [];
149 for (i = 0; i < tmp.length; i++) {
151 objectterms.push(tmp[i].toLowerCase());
154 if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
160 var word = stemmer.stemWord(tmp[i].toLowerCase());
161 // prevent stemmer from cutting word smaller than two chars
162 if(word.length < 3 && tmp[i].length >= 3) {
166 // select the correct list
167 if (word[0] == '-') {
169 word = word.substr(1);
172 toAppend = searchterms;
173 hlterms.push(tmp[i].toLowerCase());
175 // only add if not already in the list
176 if (!$u.contains(toAppend, word))
179 var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
181 // console.debug('SEARCH: searching for:');
182 // console.info('required: ', searchterms);
183 // console.info('excluded: ', excluded);
186 var terms = this._index.terms;
187 var titleterms = this._index.titleterms;
189 // array of [filename, title, anchor, descr, score]
191 $('#search-progress').empty();
194 for (i = 0; i < objectterms.length; i++) {
195 var others = [].concat(objectterms.slice(0, i),
196 objectterms.slice(i+1, objectterms.length));
197 results = results.concat(this.performObjectSearch(objectterms[i], others));
200 // lookup as search terms in fulltext
201 results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
203 // let the scorer override scores with a custom scoring function
205 for (i = 0; i < results.length; i++)
206 results[i][4] = Scorer.score(results[i]);
209 // now sort the results by score (in opposite order of appearance, since the
210 // display function below uses pop() to retrieve items) and then
212 results.sort(function(a, b) {
217 } else if (left < right) {
220 // same score: sort alphabetically
221 left = a[1].toLowerCase();
222 right = b[1].toLowerCase();
223 return (left > right) ? -1 : ((left < right) ? 1 : 0);
228 //Search.lastresults = results.slice(); // a copy
229 //console.info('search results:', Search.lastresults);
232 var resultCount = results.length;
233 function displayNextItem() {
234 // results left, load the summary and display it
235 if (results.length) {
236 var item = results.pop();
237 var listItem = $('<li style="display:none"></li>');
238 if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
240 var dirname = item[0] + '/';
241 if (dirname.match(/\/index\/$/)) {
242 dirname = dirname.substring(0, dirname.length-6);
243 } else if (dirname == 'index/') {
246 listItem.append($('<a/>').attr('href',
247 DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
248 highlightstring + item[2]).html(item[1]));
250 // normal html builders
251 listItem.append($('<a/>').attr('href',
252 item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
253 highlightstring + item[2]).html(item[1]));
256 listItem.append($('<span> (' + item[3] + ')</span>'));
257 Search.output.append(listItem);
258 listItem.slideDown(5, function() {
261 } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
262 var suffix = DOCUMENTATION_OPTIONS.SOURCELINK_SUFFIX;
263 if (suffix === undefined) {
266 $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].slice(-suffix.length) === suffix ? '' : suffix),
268 complete: function(jqxhr, textstatus) {
269 var data = jqxhr.responseText;
270 if (data !== '' && data !== undefined) {
271 listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
273 Search.output.append(listItem);
274 listItem.slideDown(5, function() {
279 // no source available, just display title
280 Search.output.append(listItem);
281 listItem.slideDown(5, function() {
286 // search finished, update title and status message
289 Search.title.text(_('Search Results'));
291 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.'));
293 Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
294 Search.status.fadeIn(500);
301 * search for object names
303 performObjectSearch : function(object, otherterms) {
304 var filenames = this._index.filenames;
305 var docnames = this._index.docnames;
306 var objects = this._index.objects;
307 var objnames = this._index.objnames;
308 var titles = this._index.titles;
313 for (var prefix in objects) {
314 for (var name in objects[prefix]) {
315 var fullname = (prefix ? prefix + '.' : '') + name;
316 if (fullname.toLowerCase().indexOf(object) > -1) {
318 var parts = fullname.split('.');
319 // check for different match types: exact matches of full name or
320 // "last name" (i.e. last dotted part)
321 if (fullname == object || parts[parts.length - 1] == object) {
322 score += Scorer.objNameMatch;
323 // matches in last name
324 } else if (parts[parts.length - 1].indexOf(object) > -1) {
325 score += Scorer.objPartialMatch;
327 var match = objects[prefix][name];
328 var objname = objnames[match[1]][2];
329 var title = titles[match[0]];
330 // If more than one term searched for, we require other words to be
331 // found in the name/title/description
332 if (otherterms.length > 0) {
333 var haystack = (prefix + ' ' + name + ' ' +
334 objname + ' ' + title).toLowerCase();
336 for (i = 0; i < otherterms.length; i++) {
337 if (haystack.indexOf(otherterms[i]) == -1) {
346 var descr = objname + _(', in ') + title;
348 var anchor = match[3];
351 else if (anchor == '-')
352 anchor = objnames[match[1]][1] + '-' + fullname;
353 // add custom score for some objects according to scorer
354 if (Scorer.objPrio.hasOwnProperty(match[2])) {
355 score += Scorer.objPrio[match[2]];
357 score += Scorer.objPrioDefault;
359 results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
368 * search for full-text terms in the index
370 performTermsSearch : function(searchterms, excluded, terms, titleterms) {
371 var docnames = this._index.docnames;
372 var filenames = this._index.filenames;
373 var titles = this._index.titles;
380 // perform the search on the required terms
381 for (i = 0; i < searchterms.length; i++) {
382 var word = searchterms[i];
385 {files: terms[word], score: Scorer.term},
386 {files: titleterms[word], score: Scorer.title}
389 // no match but word was a required one
390 if ($u.every(_o, function(o){return o.files === undefined;})) {
393 // found search word in contents
394 $u.each(_o, function(o) {
395 var _files = o.files;
396 if (_files === undefined)
399 if (_files.length === undefined)
401 files = files.concat(_files);
403 // set score for the word in each file to Scorer.term
404 for (j = 0; j < _files.length; j++) {
406 if (!(file in scoreMap))
408 scoreMap[file][word] = o.score;
412 // create the mapping
413 for (j = 0; j < files.length; j++) {
416 fileMap[file].push(word);
418 fileMap[file] = [word];
422 // now check if the files don't contain excluded terms
423 for (file in fileMap) {
426 // check if all requirements are matched
427 if (fileMap[file].length != searchterms.length)
430 // ensure that none of the excluded terms is in the search result
431 for (i = 0; i < excluded.length; i++) {
432 if (terms[excluded[i]] == file ||
433 titleterms[excluded[i]] == file ||
434 $u.contains(terms[excluded[i]] || [], file) ||
435 $u.contains(titleterms[excluded[i]] || [], file)) {
441 // if we have still a valid result we can add it to the result list
443 // select one (max) score for the file.
444 // for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
445 var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
446 results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
453 * helper function to return a node containing the
454 * search summary for a given text. keywords is a list
455 * of stemmed words, hlwords is the list of normal, unstemmed
456 * words. the first one is used to find the occurrence, the
457 * latter for highlighting it.
459 makeSearchSummary : function(text, keywords, hlwords) {
460 var textLower = text.toLowerCase();
462 $.each(keywords, function() {
463 var i = textLower.indexOf(this.toLowerCase());
467 start = Math.max(start - 120, 0);
468 var excerpt = ((start > 0) ? '...' : '') +
469 $.trim(text.substr(start, 240)) +
470 ((start + 240 - text.length) ? '...' : '');
471 var rv = $('<div class="context"></div>').text(excerpt);
472 $.each(hlwords, function() {
473 rv = rv.highlightText(this, 'highlighted');
479 $(document).ready(function() {