highlight the search words provided in the url in the text
199665
function() {
    var params = $.getQueryParameters();
    var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
    if (terms.length) {
      var body = $('div.body');
      window.setTimeout(function() {
        $.each(terms, function() {
          body.highlightText(this.toLowerCase(), 'highlight');
        });
      }, 10);
      $('<li class="highlight-link"><a href="javascript:Documentation.' +
        'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
          .appendTo($('.sidebar .this-page-menu'));
    }
  }
803526
public function highlightSearch($value, $searchString)
    {
        if (strlen($value) < 1 || strlen($searchString) < 1) {
            return $value;
        }
        preg_match_all("/$searchString+/i", $value, $matches);
        if (is_array($matches[0]) && count($matches[0]) > 0) {
            return str_replace($matches[0][0], '<em class="ccm-highlight-search">' . $matches[0][0] . '</em>', $value);
        }

        return $value;
    }
1155094
function(text) {

            urls = [];
            titles = [];
            htmlBlock = [];

            text = text.replace(/~/g,"~T");
            text = text.replace(/\$/g,"~D");
            text = text.replace(/\r\n/g,"\n");
            text = text.replace(/\r/g,"\n");
            text = "\n\n" + text + "\n\n";
            text = detab(text);
            text = text.replace(/^[ \t]+$/mg,"");
            text = hashHTMLBlocks(text);
            text = stripLinkDefinitions(text);
            text = runBlockGamut(text);
            text = unescapeSpecialChars(text);
            text = text.replace(/~D/g,"$$");
            text = text.replace(/~T/g,"~");

            return text;
        }
707732
def find( self, flags = 0 ):
        
        # check against the web and text views
        if ( not (self._textEdit or self._webView) ):
            fg = QColor('darkRed')
            bg = QColor('red').lighter(180)
            
            palette = self.palette()
            palette.setColor(palette.Text, fg)
            palette.setColor(palette.Base, bg)
            
            self._searchEdit.setPalette(palette)
            self._searchEdit.setToolTip( 'No Text Edit is linked.' )
            
            return False
        
        if ( self._caseSensitiveCheckbox.isChecked() ):
            flags |= QTextDocument.FindCaseSensitively
        
        if ( self._textEdit and self._wholeWordsCheckbox.isChecked() ):
            flags |= QTextDocument.FindWholeWords
        
        terms = self._searchEdit.text()
        if ( terms != self._lastText ):
            self._lastCursor = QTextCursor()
        
        if ( self._regexCheckbox.isChecked() ):
            terms = QRegExp(terms)
        
        palette = self.palette()
        
        # search on a text edit
        if ( self._textEdit ):
            cursor  = self._textEdit.document().find(terms, 
                                                 self._lastCursor, 
                                                 QTextDocument.FindFlags(flags))
            found   = not cursor.isNull()
            self._lastCursor = cursor
            self._textEdit.setTextCursor(cursor)
        
        elif ( QWebPage ):
            flags = QWebPage.FindFlags(flags)
            flags |= QWebPage.FindWrapsAroundDocument
            
            found = self._webView.findText(terms, flags)
        
        self._lastText = self._searchEdit.text()
        
        if ( not terms or found ):
            fg = palette.color(palette.Text)
            bg = palette.color(palette.Base)
        else:
            fg = QColor('darkRed')
            bg = QColor('red').lighter(180)
        
        palette.setColor(palette.Text, fg)
        palette.setColor(palette.Base, bg)
        
        self._searchEdit.setPalette(palette)
        
        return found
1154859
def keyword(self, text):
        """"""
        cls = self.KEYWORDS[text]
        self.push_token(cls(text, self.lineno, self.offset))
339442
def parse_text (url_data):
    """"""
    lineno = 0
    for line in url_data.get_content().splitlines():
        lineno += 1
        line = line.strip()
        if not line or line.startswith('#'):
            continue
        url_data.add_url(line, line=lineno)
388879
def url_read_text(url, verbose=True):
    
    """
    data = url_read(url, verbose)
    text = data.decode('utf8')
    return text
346172
def highlight_block(self, text):
        """"""
        text = to_text_string(text)
        inside_comment = tbh.get_state(self.currentBlock().previous()) == self.INSIDE_COMMENT
        self.setFormat(0, len(text),
                       self.formats["comment" if inside_comment else "normal"])
        
        match = self.PROG.search(text)
        index = 0
        while match:
            for key, value in list(match.groupdict().items()):
                if value:
                    start, end = match.span(key)
                    index += end-start
                    if key == "comment_start":
                        inside_comment = True
                        self.setFormat(start, len(text)-start,
                                       self.formats["comment"])
                    elif key == "comment_end":
                        inside_comment = False
                        self.setFormat(start, end-start,
                                       self.formats["comment"])
                    elif inside_comment:
                        self.setFormat(start, end-start,
                                       self.formats["comment"])
                    elif key == "define":
                        self.setFormat(start, end-start,
                                       self.formats["number"])
                    else:
                        self.setFormat(start, end-start, self.formats[key])
                    
            match = self.PROG.search(text, match.end())
        
        self.highlight_spaces(text)
        
        last_state = self.INSIDE_COMMENT if inside_comment else self.NORMAL
        tbh.set_state(self.currentBlock(), last_state)
355541
def in_book_search_highlighted_results(request):
    """"""
    results = {}

    args = request.matchdict
    ident_hash = args['ident_hash']

    page_ident_hash = args['page_ident_hash']
    try:
        page_uuid, _ = split_ident_hash(page_ident_hash)
    except IdentHashShortId as e:
        page_uuid = get_uuid(e.id)
    except IdentHashMissingVersion as e:
        page_uuid = e.id
    args['page_uuid'] = page_uuid

    args['search_term'] = request.params.get('q', '')

    query_type = request.params.get('query_type', '')
    combiner = ''
    if query_type:
        if query_type.lower() == 'or':
            combiner = '_or'

    # Get version from URL params
    id, version = split_ident_hash(ident_hash)
    args['uuid'] = id
    args['version'] = version

    with db_connect() as db_connection:
        with db_connection.cursor() as cursor:
            cursor.execute(SQL['get-collated-state'], args)
            res = cursor.fetchall()
            if res and res[0][0]:
                statement = SQL['get-in-collated-book-search-full-page']
            else:
                statement = SQL['get-in-book-search-full-page']
            cursor.execute(statement.format(combiner=combiner), args)
            res = cursor.fetchall()

            results['results'] = {'query': [],
                                  'total': len(res),
                                  'items': []}
            results['results']['query'] = {
                'search_term': args['search_term'],
                'collection_id': ident_hash,
            }
            for uuid, version, title, headline, rank in res:
                results['results']['items'].append({
                    'rank': '{}'.format(rank),
                    'id': '{}'.format(page_ident_hash),
                    'title': '{}'.format(title),
                    'html': '{}'.format(headline),
                })

    resp = request.response
    resp.status = '200 OK'
    resp.content_type = 'application/json'
    resp.body = json.dumps(results)

    return resp
987722
def _search_url_titles(self, title):
        
        # make the search
        logger.info('Searching title name for %r', title)
        r = self.session.get(self.server_url + 'subtitle/search/', params={'q': title}, timeout=10)
        r.raise_for_status()

        # check for redirections
        if r.history and all([h.status_code == 302 for h in r.history]):
            logger.debug('Redirected to the subtitles page')
            links = [r.url]
        else:
            # get the suggestions (if needed)
            soup = ParserBeautifulSoup(r.content, ['lxml', 'html.parser'])
            links = [link.attrs['href'] for link in soup.select('#processes div.generalWindowTop a')]
            logger.debug('Found %d suggestions', len(links))

        url_titles = defaultdict(list)
        for link in links:
            parts = link.split('/')
            url_titles[parts[-3]].append(parts[-2])

        return url_titles
217153
def highlight_spaces(self, text, offset=0):
        
        flags_text = self.document().defaultTextOption().flags()
        show_blanks =  flags_text & QTextOption.ShowTabsAndSpaces
        if show_blanks:
            format_leading = self.formats.get("leading", None)
            format_trailing = self.formats.get("trailing", None)
            match = self.BLANKPROG.search(text, offset)
            while match:
                start, end = match.span()
                start = max([0, start+offset])
                end = max([0, end+offset])
                # Format trailing spaces at the end of the line. 
                if end == len(text) and format_trailing is not None:
                    self.setFormat(start, end, format_trailing)
                # Format leading spaces, e.g. indentation.
                if start == 0 and format_leading is not None:
                    self.setFormat(start, end, format_leading)
                format = self.format(start)
                color_foreground = format.foreground().color()
                alpha_new = self.BLANK_ALPHA_FACTOR * color_foreground.alphaF()
                color_foreground.setAlphaF(alpha_new)
                self.setFormat(start, end-start, color_foreground)
                match = self.BLANKPROG.search(text, match.end())
470641
static function highlight ($code)
  {
    $o = highlight_string ("<?php;$code ?>", true);
    $o = str_extract ($o, '%php</span>.*?</span>(.*)<span[^>]*>\?&gt;%s');
    return $o !== '' ? $o : $code;
  }
959487
def scrape_links(self, text, context=False):
        ''''''
        return self.iter_processed_links(io.StringIO(text), context=context)
1213796
def search_line(line, search, searchtype):
    """"""
    if searchtype == 're' or searchtype == 'word':
        return re.search(search, line)  #, re.IGNORECASE)
    elif searchtype == 'pos':
        return searcher.search_out(line, search)
    elif searchtype == 'hyper':
        return searcher.hypernym_search(line, search)
816805
def fetchText(cls, url, data, textSearch, optional):
        """"""
        if textSearch:
            match = textSearch.search(data[0])
            if match:
                text = match.group(1)
                out.debug(u'matched text %r with pattern %s' % (text, textSearch.pattern))
                return unescape(text).strip()
            if optional:
                return None
            else:
                raise ValueError("Pattern %s not found at URL %s." % (textSearch.pattern, url))
        else:
            return None
671837
def highlighted_fulltext(self):
        """"""
        terms = self.fields.get('fulltext', [])
        if not terms:
            return None
        arguments = {'id': self['id'],
                     'query': ' & '.join(terms),
                     }
        with db_connect() as db_connection:
            with db_connection.cursor() as cursor:
                cursor.execute(_read_sql_file('highlighted-fulltext'),
                               arguments)
                hl_fulltext = cursor.fetchone()[0]
        return hl_fulltext
637684
function surroundKeywords(keywords, text, prefix, suffix) {
	if (!keywords.length) return text;

	let regexString = keywords.map((k) => {
		if (k.type === 'regex') {
			return stringUtilsCommon.replaceRegexDiacritics(k.valueRegex);
		} else {
			const value = typeof k === 'string' ? k : k.value;
			return stringUtilsCommon.replaceRegexDiacritics(stringUtilsCommon.pregQuote(value));
		}
	}).join('|');
	regexString = '(' + regexString + ')'
	const re = new RegExp(regexString, 'gi');
	return text.replace(re, prefix + '$1' + suffix);
}