| Download
Reference manual of the SageMath package kerrgeodesic_gw
Project: Sagittarius
Views: 7653License: GPL3
Image: ubuntu2004
/*1* searchtools.js2* ~~~~~~~~~~~~~~~~3*4* Sphinx JavaScript utilities for the full-text search.5*6* :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.7* :license: BSD, see LICENSE for details.8*9*/1011if (!Scorer) {12/**13* Simple result scoring code.14*/15var Scorer = {16// Implement the following function to further tweak the score for each result17// The function takes a result array [filename, title, anchor, descr, score]18// and returns the new score.19/*20score: function(result) {21return result[4];22},23*/2425// query matches the full name of an object26objNameMatch: 11,27// or matches in the last dotted part of the object name28objPartialMatch: 6,29// Additive scores depending on the priority of the object30objPrio: {0: 15, // used to be importantResults311: 5, // used to be objectResults322: -5}, // used to be unimportantResults33// Used when the priority is not in the mapping.34objPrioDefault: 0,3536// query found in title37title: 15,38partialTitle: 7,39// query found in terms40term: 5,41partialTerm: 242};43}4445if (!splitQuery) {46function splitQuery(query) {47return query.split(/\s+/);48}49}5051/**52* Search Module53*/54var Search = {5556_index : null,57_queued_query : null,58_pulse_status : -1,5960htmlToText : function(htmlString) {61var virtualDocument = document.implementation.createHTMLDocument('virtual');62var htmlElement = $(htmlString, virtualDocument);63htmlElement.find('.headerlink').remove();64docContent = htmlElement.find('[role=main]')[0];65if(docContent === undefined) {66console.warn("Content block not found. Sphinx search tries to obtain it " +67"via '[role=main]'. Could you check your theme or template.");68return "";69}70return docContent.textContent || docContent.innerText;71},7273init : function() {74var params = $.getQueryParameters();75if (params.q) {76var query = params.q[0];77$('input[name="q"]')[0].value = query;78this.performSearch(query);79}80},8182loadIndex : function(url) {83$.ajax({type: "GET", url: url, data: null,84dataType: "script", cache: true,85complete: function(jqxhr, textstatus) {86if (textstatus != "success") {87document.getElementById("searchindexloader").src = url;88}89}});90},9192setIndex : function(index) {93var q;94this._index = index;95if ((q = this._queued_query) !== null) {96this._queued_query = null;97Search.query(q);98}99},100101hasIndex : function() {102return this._index !== null;103},104105deferQuery : function(query) {106this._queued_query = query;107},108109stopPulse : function() {110this._pulse_status = 0;111},112113startPulse : function() {114if (this._pulse_status >= 0)115return;116function pulse() {117var i;118Search._pulse_status = (Search._pulse_status + 1) % 4;119var dotString = '';120for (i = 0; i < Search._pulse_status; i++)121dotString += '.';122Search.dots.text(dotString);123if (Search._pulse_status > -1)124window.setTimeout(pulse, 500);125}126pulse();127},128129/**130* perform a search for something (or wait until index is loaded)131*/132performSearch : function(query) {133// create the required interface elements134this.out = $('#search-results');135this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);136this.dots = $('<span></span>').appendTo(this.title);137this.status = $('<p class="search-summary"> </p>').appendTo(this.out);138this.output = $('<ul class="search"/>').appendTo(this.out);139140$('#search-progress').text(_('Preparing search...'));141this.startPulse();142143// index already loaded, the browser was quick!144if (this.hasIndex())145this.query(query);146else147this.deferQuery(query);148},149150/**151* execute search (requires search index to be loaded)152*/153query : function(query) {154var i;155156// stem the searchterms and add them to the correct list157var stemmer = new Stemmer();158var searchterms = [];159var excluded = [];160var hlterms = [];161var tmp = splitQuery(query);162var objectterms = [];163for (i = 0; i < tmp.length; i++) {164if (tmp[i] !== "") {165objectterms.push(tmp[i].toLowerCase());166}167168if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i] === "") {169// skip this "word"170continue;171}172// stem the word173var word = stemmer.stemWord(tmp[i].toLowerCase());174// prevent stemmer from cutting word smaller than two chars175if(word.length < 3 && tmp[i].length >= 3) {176word = tmp[i];177}178var toAppend;179// select the correct list180if (word[0] == '-') {181toAppend = excluded;182word = word.substr(1);183}184else {185toAppend = searchterms;186hlterms.push(tmp[i].toLowerCase());187}188// only add if not already in the list189if (!$u.contains(toAppend, word))190toAppend.push(word);191}192var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));193194// console.debug('SEARCH: searching for:');195// console.info('required: ', searchterms);196// console.info('excluded: ', excluded);197198// prepare search199var terms = this._index.terms;200var titleterms = this._index.titleterms;201202// array of [filename, title, anchor, descr, score]203var results = [];204$('#search-progress').empty();205206// lookup as object207for (i = 0; i < objectterms.length; i++) {208var others = [].concat(objectterms.slice(0, i),209objectterms.slice(i+1, objectterms.length));210results = results.concat(this.performObjectSearch(objectterms[i], others));211}212213// lookup as search terms in fulltext214results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));215216// let the scorer override scores with a custom scoring function217if (Scorer.score) {218for (i = 0; i < results.length; i++)219results[i][4] = Scorer.score(results[i]);220}221222// now sort the results by score (in opposite order of appearance, since the223// display function below uses pop() to retrieve items) and then224// alphabetically225results.sort(function(a, b) {226var left = a[4];227var right = b[4];228if (left > right) {229return 1;230} else if (left < right) {231return -1;232} else {233// same score: sort alphabetically234left = a[1].toLowerCase();235right = b[1].toLowerCase();236return (left > right) ? -1 : ((left < right) ? 1 : 0);237}238});239240// for debugging241//Search.lastresults = results.slice(); // a copy242//console.info('search results:', Search.lastresults);243244// print the results245var resultCount = results.length;246function displayNextItem() {247// results left, load the summary and display it248if (results.length) {249var item = results.pop();250var listItem = $('<li></li>');251var requestUrl = "";252var linkUrl = "";253if (DOCUMENTATION_OPTIONS.BUILDER === 'dirhtml') {254// dirhtml builder255var dirname = item[0] + '/';256if (dirname.match(/\/index\/$/)) {257dirname = dirname.substring(0, dirname.length-6);258} else if (dirname == 'index/') {259dirname = '';260}261requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + dirname;262linkUrl = requestUrl;263264} else {265// normal html builders266requestUrl = DOCUMENTATION_OPTIONS.URL_ROOT + item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX;267linkUrl = item[0] + DOCUMENTATION_OPTIONS.LINK_SUFFIX;268}269listItem.append($('<a/>').attr('href',270linkUrl +271highlightstring + item[2]).html(item[1]));272if (item[3]) {273listItem.append($('<span> (' + item[3] + ')</span>'));274Search.output.append(listItem);275setTimeout(function() {276displayNextItem();277}, 5);278} else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {279$.ajax({url: requestUrl,280dataType: "text",281complete: function(jqxhr, textstatus) {282var data = jqxhr.responseText;283if (data !== '' && data !== undefined) {284listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));285}286Search.output.append(listItem);287setTimeout(function() {288displayNextItem();289}, 5);290}});291} else {292// no source available, just display title293Search.output.append(listItem);294setTimeout(function() {295displayNextItem();296}, 5);297}298}299// search finished, update title and status message300else {301Search.stopPulse();302Search.title.text(_('Search Results'));303if (!resultCount)304Search.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.'));305else306Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));307Search.status.fadeIn(500);308}309}310displayNextItem();311},312313/**314* search for object names315*/316performObjectSearch : function(object, otherterms) {317var filenames = this._index.filenames;318var docnames = this._index.docnames;319var objects = this._index.objects;320var objnames = this._index.objnames;321var titles = this._index.titles;322323var i;324var results = [];325326for (var prefix in objects) {327for (var name in objects[prefix]) {328var fullname = (prefix ? prefix + '.' : '') + name;329var fullnameLower = fullname.toLowerCase()330if (fullnameLower.indexOf(object) > -1) {331var score = 0;332var parts = fullnameLower.split('.');333// check for different match types: exact matches of full name or334// "last name" (i.e. last dotted part)335if (fullnameLower == object || parts[parts.length - 1] == object) {336score += Scorer.objNameMatch;337// matches in last name338} else if (parts[parts.length - 1].indexOf(object) > -1) {339score += Scorer.objPartialMatch;340}341var match = objects[prefix][name];342var objname = objnames[match[1]][2];343var title = titles[match[0]];344// If more than one term searched for, we require other words to be345// found in the name/title/description346if (otherterms.length > 0) {347var haystack = (prefix + ' ' + name + ' ' +348objname + ' ' + title).toLowerCase();349var allfound = true;350for (i = 0; i < otherterms.length; i++) {351if (haystack.indexOf(otherterms[i]) == -1) {352allfound = false;353break;354}355}356if (!allfound) {357continue;358}359}360var descr = objname + _(', in ') + title;361362var anchor = match[3];363if (anchor === '')364anchor = fullname;365else if (anchor == '-')366anchor = objnames[match[1]][1] + '-' + fullname;367// add custom score for some objects according to scorer368if (Scorer.objPrio.hasOwnProperty(match[2])) {369score += Scorer.objPrio[match[2]];370} else {371score += Scorer.objPrioDefault;372}373results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);374}375}376}377378return results;379},380381/**382* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions383*/384escapeRegExp : function(string) {385return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string386},387388/**389* search for full-text terms in the index390*/391performTermsSearch : function(searchterms, excluded, terms, titleterms) {392var docnames = this._index.docnames;393var filenames = this._index.filenames;394var titles = this._index.titles;395396var i, j, file;397var fileMap = {};398var scoreMap = {};399var results = [];400401// perform the search on the required terms402for (i = 0; i < searchterms.length; i++) {403var word = searchterms[i];404var files = [];405var _o = [406{files: terms[word], score: Scorer.term},407{files: titleterms[word], score: Scorer.title}408];409// add support for partial matches410if (word.length > 2) {411var word_regex = this.escapeRegExp(word);412for (var w in terms) {413if (w.match(word_regex) && !terms[word]) {414_o.push({files: terms[w], score: Scorer.partialTerm})415}416}417for (var w in titleterms) {418if (w.match(word_regex) && !titleterms[word]) {419_o.push({files: titleterms[w], score: Scorer.partialTitle})420}421}422}423424// no match but word was a required one425if ($u.every(_o, function(o){return o.files === undefined;})) {426break;427}428// found search word in contents429$u.each(_o, function(o) {430var _files = o.files;431if (_files === undefined)432return433434if (_files.length === undefined)435_files = [_files];436files = files.concat(_files);437438// set score for the word in each file to Scorer.term439for (j = 0; j < _files.length; j++) {440file = _files[j];441if (!(file in scoreMap))442scoreMap[file] = {};443scoreMap[file][word] = o.score;444}445});446447// create the mapping448for (j = 0; j < files.length; j++) {449file = files[j];450if (file in fileMap && fileMap[file].indexOf(word) === -1)451fileMap[file].push(word);452else453fileMap[file] = [word];454}455}456457// now check if the files don't contain excluded terms458for (file in fileMap) {459var valid = true;460461// check if all requirements are matched462var filteredTermCount = // as search terms with length < 3 are discarded: ignore463searchterms.filter(function(term){return term.length > 2}).length464if (465fileMap[file].length != searchterms.length &&466fileMap[file].length != filteredTermCount467) continue;468469// ensure that none of the excluded terms is in the search result470for (i = 0; i < excluded.length; i++) {471if (terms[excluded[i]] == file ||472titleterms[excluded[i]] == file ||473$u.contains(terms[excluded[i]] || [], file) ||474$u.contains(titleterms[excluded[i]] || [], file)) {475valid = false;476break;477}478}479480// if we have still a valid result we can add it to the result list481if (valid) {482// select one (max) score for the file.483// for better ranking, we should calculate ranking by using words statistics like basic tf-idf...484var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));485results.push([docnames[file], titles[file], '', null, score, filenames[file]]);486}487}488return results;489},490491/**492* helper function to return a node containing the493* search summary for a given text. keywords is a list494* of stemmed words, hlwords is the list of normal, unstemmed495* words. the first one is used to find the occurrence, the496* latter for highlighting it.497*/498makeSearchSummary : function(htmlText, keywords, hlwords) {499var text = Search.htmlToText(htmlText);500var textLower = text.toLowerCase();501var start = 0;502$.each(keywords, function() {503var i = textLower.indexOf(this.toLowerCase());504if (i > -1)505start = i;506});507start = Math.max(start - 120, 0);508var excerpt = ((start > 0) ? '...' : '') +509$.trim(text.substr(start, 240)) +510((start + 240 - text.length) ? '...' : '');511var rv = $('<p class="context"></p>').text(excerpt);512$.each(hlwords, function() {513rv = rv.highlightText(this, 'highlighted');514});515return rv;516}517};518519$(document).ready(function() {520Search.init();521});522523524