1 gitbook.require(["jQuery"], function(jQuery) {
4 * jQuery Highlight plugin
6 * Based on highlight v3 by Johann Burkard
7 * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
9 * Code a little bit refactored and cleaned (in my humble opinion).
10 * Most important changes:
11 * - has an option to highlight only entire words (wordsOnly - false by default),
12 * - has an option to be case sensitive (caseSensitive - false by default)
13 * - highlight element tag and class names can be specified in options
15 * Copyright (c) 2009 Bartek Szopka
17 * Licensed under MIT license.
22 highlight: function (node, re, nodeName, className) {
23 if (node.nodeType === 3) {
24 var match = node.data.match(re);
26 var highlight = document.createElement(nodeName || 'span');
27 highlight.className = className || 'highlight';
28 var wordNode = node.splitText(match.index);
29 wordNode.splitText(match[0].length);
30 var wordClone = wordNode.cloneNode(true);
31 highlight.appendChild(wordClone);
32 wordNode.parentNode.replaceChild(highlight, wordNode);
33 return 1; //skip added node in parent
35 } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children
36 !/(script|style)/i.test(node.tagName) && // ignore script and style nodes
37 !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted
38 for (var i = 0; i < node.childNodes.length; i++) {
39 i += jQuery.highlight(node.childNodes[i], re, nodeName, className);
46 jQuery.fn.unhighlight = function (options) {
47 var settings = { className: 'highlight', element: 'span' };
48 jQuery.extend(settings, options);
50 return this.find(settings.element + "." + settings.className).each(function () {
51 var parent = this.parentNode;
52 parent.replaceChild(this.firstChild, this);
57 jQuery.fn.highlight = function (words, options) {
58 var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false };
59 jQuery.extend(settings, options);
61 if (words.constructor === String) {
63 // also match 'foo-bar' if search for 'foo bar'
64 if (/\s/.test(words[0])) words.push(words[0].replace(/\s+/, '-'));
66 words = jQuery.grep(words, function(word, i){
69 words = jQuery.map(words, function(word, i) {
70 return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
72 if (words.length === 0) { return this; }
74 var flag = settings.caseSensitive ? "" : "i";
75 var pattern = "(" + words.join("|") + ")";
76 if (settings.wordsOnly) {
77 pattern = "\\b" + pattern + "\\b";
79 var re = new RegExp(pattern, flag);
81 return this.each(function () {
82 jQuery.highlight(this, re, settings.element, settings.className);