5 * Sphinx JavaScript utilties for the full-text search.
7 * :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
8 * :license: BSD, see LICENSE for details.
13 * helper function to return a node containing the
14 * search summary for a given text. keywords is a list
15 * of stemmed words, hlwords is the list of normal, unstemmed
16 * words. the first one is used to find the occurance, the
17 * latter for highlighting it.
20 jQuery.makeSearchSummary = function(text, keywords, hlwords) {
21 var textLower = text.toLowerCase();
23 $.each(keywords, function() {
24 var i = textLower.indexOf(this.toLowerCase());
28 start = Math.max(start - 120, 0);
29 var excerpt = ((start > 0) ? '...' : '') +
30 $.trim(text.substr(start, 240)) +
31 ((start + 240 - text.length) ? '...' : '');
32 var rv = $('<div class="context"></div>').text(excerpt);
33 $.each(hlwords, function() {
34 rv = rv.highlightText(this, 'highlighted');
42 var PorterStemmer = function() {
78 var c = "[^aeiou]"; // consonant
79 var v = "[aeiouy]"; // vowel
80 var C = c + "[^aeiouy]*"; // consonant sequence
81 var V = v + "[aeiou]*"; // vowel sequence
83 var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
84 var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
85 var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
86 var s_v = "^(" + C + ")?" + v; // vowel in stem
88 this.stemWord = function (w) {
102 firstch = w.substr(0,1);
104 w = firstch.toUpperCase() + w.substr(1);
107 re = /^(.+?)(ss|i)es$/;
108 re2 = /^(.+?)([^s])s$/;
111 w = w.replace(re,"$1$2");
112 else if (re2.test(w))
113 w = w.replace(re2,"$1$2");
117 re2 = /^(.+?)(ed|ing)$/;
120 re = new RegExp(mgr0);
121 if (re.test(fp[1])) {
123 w = w.replace(re,"");
126 else if (re2.test(w)) {
127 var fp = re2.exec(w);
129 re2 = new RegExp(s_v);
130 if (re2.test(stem)) {
133 re3 = new RegExp("([^aeiouylsz])\\1$");
134 re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
137 else if (re3.test(w)) {
139 w = w.replace(re,"");
141 else if (re4.test(w))
151 re = new RegExp(s_v);
157 re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
162 re = new RegExp(mgr0);
164 w = stem + step2list[suffix];
168 re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
173 re = new RegExp(mgr0);
175 w = stem + step3list[suffix];
179 re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
180 re2 = /^(.+?)(s|t)(ion)$/;
184 re = new RegExp(mgr1);
188 else if (re2.test(w)) {
189 var fp = re2.exec(w);
190 stem = fp[1] + fp[2];
191 re2 = new RegExp(mgr1);
201 re = new RegExp(mgr1);
202 re2 = new RegExp(meq1);
203 re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
204 if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
208 re2 = new RegExp(mgr1);
209 if (re.test(w) && re2.test(w)) {
211 w = w.replace(re,"");
214 // and turn initial Y back to y
216 w = firstch.toLowerCase() + w.substr(1);
228 _queued_query : null,
232 var params = $.getQueryParameters();
234 var query = params.q[0];
235 $('input[name="q"]')[0].value = query;
236 this.performSearch(query);
240 loadIndex : function(url) {
241 $.ajax({type: "GET", url: url, data: null, success: null,
242 dataType: "script", cache: true});
245 setIndex : function(index) {
248 if ((q = this._queued_query) !== null) {
249 this._queued_query = null;
254 hasIndex : function() {
255 return this._index !== null;
258 deferQuery : function(query) {
259 this._queued_query = query;
262 stopPulse : function() {
263 this._pulse_status = 0;
266 startPulse : function() {
267 if (this._pulse_status >= 0)
270 Search._pulse_status = (Search._pulse_status + 1) % 4;
272 for (var i = 0; i < Search._pulse_status; i++)
274 Search.dots.text(dotString);
275 if (Search._pulse_status > -1)
276 window.setTimeout(pulse, 500);
282 * perform a search for something
284 performSearch : function(query) {
285 // create the required interface elements
286 this.out = $('#search-results');
287 this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
288 this.dots = $('<span></span>').appendTo(this.title);
289 this.status = $('<p style="display: none"></p>').appendTo(this.out);
290 this.output = $('<ul class="search"/>').appendTo(this.out);
292 $('#search-progress').text(_('Preparing search...'));
295 // index already loaded, the browser was quick!
299 this.deferQuery(query);
302 query : function(query) {
303 var stopwords = ['and', 'then', 'into', 'it', 'as', 'are', 'in',
304 'if', 'for', 'no', 'there', 'their', 'was', 'is',
305 'be', 'to', 'that', 'but', 'they', 'not', 'such',
306 'with', 'by', 'a', 'on', 'these', 'of', 'will',
307 'this', 'near', 'the', 'or', 'at'];
309 // stem the searchterms and add them to the correct list
310 var stemmer = new PorterStemmer();
311 var searchterms = [];
314 var tmp = query.split(/\s+/);
315 var object = (tmp.length == 1) ? tmp[0].toLowerCase() : null;
316 for (var i = 0; i < tmp.length; i++) {
317 if ($u.indexOf(stopwords, tmp[i]) != -1 || tmp[i].match(/^\d+$/) ||
323 var word = stemmer.stemWord(tmp[i]).toLowerCase();
324 // select the correct list
325 if (word[0] == '-') {
326 var toAppend = excluded;
327 word = word.substr(1);
330 var toAppend = searchterms;
331 hlterms.push(tmp[i].toLowerCase());
333 // only add if not already in the list
334 if (!$.contains(toAppend, word))
337 var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
339 // console.debug('SEARCH: searching for:');
340 // console.info('required: ', searchterms);
341 // console.info('excluded: ', excluded);
344 var filenames = this._index.filenames;
345 var titles = this._index.titles;
346 var terms = this._index.terms;
347 var objects = this._index.objects;
348 var objtypes = this._index.objtypes;
349 var objnames = this._index.objnames;
352 // different result priorities
353 var importantResults = [];
354 var objectResults = [];
355 var regularResults = [];
356 var unimportantResults = [];
357 $('#search-progress').empty();
360 if (object != null) {
361 for (var prefix in objects) {
362 for (var name in objects[prefix]) {
363 var fullname = (prefix ? prefix + '.' : '') + name;
364 if (fullname.toLowerCase().indexOf(object) > -1) {
365 match = objects[prefix][name];
366 descr = objnames[match[1]] + _(', in ') + titles[match[0]];
367 // XXX the generated anchors are not generally correct
368 // XXX there may be custom prefixes
369 result = [filenames[match[0]], fullname, '#'+fullname, descr];
371 case 1: objectResults.push(result); break;
372 case 0: importantResults.push(result); break;
373 case 2: unimportantResults.push(result); break;
380 // sort results descending
381 objectResults.sort(function(a, b) {
382 return (a[1] > b[1]) ? -1 : ((a[1] < b[1]) ? 1 : 0);
385 importantResults.sort(function(a, b) {
386 return (a[1] > b[1]) ? -1 : ((a[1] < b[1]) ? 1 : 0);
389 unimportantResults.sort(function(a, b) {
390 return (a[1] > b[1]) ? -1 : ((a[1] < b[1]) ? 1 : 0);
394 // perform the search on the required terms
395 for (var i = 0; i < searchterms.length; i++) {
396 var word = searchterms[i];
397 // no match but word was a required one
398 if ((files = terms[word]) == null)
400 if (files.length == undefined) {
403 // create the mapping
404 for (var j = 0; j < files.length; j++) {
407 fileMap[file].push(word);
409 fileMap[file] = [word];
413 // now check if the files don't contain excluded terms
414 for (var file in fileMap) {
417 // check if all requirements are matched
418 if (fileMap[file].length != searchterms.length)
421 // ensure that none of the excluded terms is in the
423 for (var i = 0; i < excluded.length; i++) {
424 if (terms[excluded[i]] == file ||
425 $.contains(terms[excluded[i]] || [], file)) {
431 // if we have still a valid result we can add it
432 // to the result list
434 regularResults.push([filenames[file], titles[file], '', null]);
437 // delete unused variables in order to not waste
438 // memory until list is retrieved completely
439 delete filenames, titles, terms;
441 // now sort the regular results descending by title
442 regularResults.sort(function(a, b) {
443 var left = a[1].toLowerCase();
444 var right = b[1].toLowerCase();
445 return (left > right) ? -1 : ((left < right) ? 1 : 0);
448 // combine all results
449 var results = unimportantResults.concat(regularResults)
450 .concat(objectResults).concat(importantResults);
453 var resultCount = results.length;
454 function displayNextItem() {
455 // results left, load the summary and display it
456 if (results.length) {
457 var item = results.pop();
458 var listItem = $('<li style="display:none"></li>');
459 if (DOCUMENTATION_OPTIONS.FILE_SUFFIX == '') {
461 var dirname = item[0] + '/';
462 if (dirname.match(/\/index\/$/)) {
463 dirname = dirname.substring(0, dirname.length-6);
464 } else if (dirname == 'index/') {
467 listItem.append($('<a/>').attr('href',
468 DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
469 highlightstring + item[2]).html(item[1]));
471 // normal html builders
472 listItem.append($('<a/>').attr('href',
473 item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
474 highlightstring + item[2]).html(item[1]));
477 listItem.append($('<span> (' + item[3] + ')</span>'));
478 Search.output.append(listItem);
479 listItem.slideDown(5, function() {
482 } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
483 $.get(DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' +
484 item[0] + '.txt', function(data) {
486 listItem.append($.makeSearchSummary(data, searchterms, hlterms));
487 Search.output.append(listItem);
489 listItem.slideDown(5, function() {
494 // no source available, just display title
495 Search.output.append(listItem);
496 listItem.slideDown(5, function() {
501 // search finished, update title and status message
504 Search.title.text(_('Search Results'));
506 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.'));
508 Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
509 Search.status.fadeIn(500);
516 $(document).ready(function() {