PageRenderTime 55ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/syntaxhighlighter_3.0.83/src/shCore.js

#
JavaScript | 1721 lines | 965 code | 284 blank | 472 comment | 215 complexity | d70a059774f9aefdad094b4e3aa6d1d7 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, BSD-3-Clause
  1. /**
  2. * SyntaxHighlighter
  3. * http://alexgorbatchev.com/SyntaxHighlighter
  4. *
  5. * SyntaxHighlighter is donationware. If you are using it, please donate.
  6. * http://alexgorbatchev.com/SyntaxHighlighter/donate.html
  7. *
  8. * @version
  9. * 3.0.83 (July 02 2010)
  10. *
  11. * @copyright
  12. * Copyright (C) 2004-2010 Alex Gorbatchev.
  13. *
  14. * @license
  15. * Dual licensed under the MIT and GPL licenses.
  16. */
  17. //
  18. // Begin anonymous function. This is used to contain local scope variables without polutting global scope.
  19. //
  20. var SyntaxHighlighter = function() {
  21. // CommonJS
  22. if (typeof(require) != 'undefined' && typeof(XRegExp) == 'undefined')
  23. {
  24. XRegExp = require('XRegExp').XRegExp;
  25. }
  26. // Shortcut object which will be assigned to the SyntaxHighlighter variable.
  27. // This is a shorthand for local reference in order to avoid long namespace
  28. // references to SyntaxHighlighter.whatever...
  29. var sh = {
  30. defaults : {
  31. /** Additional CSS class names to be added to highlighter elements. */
  32. 'class-name' : '',
  33. /** First line number. */
  34. 'first-line' : 1,
  35. /**
  36. * Pads line numbers. Possible values are:
  37. *
  38. * false - don't pad line numbers.
  39. * true - automaticaly pad numbers with minimum required number of leading zeroes.
  40. * [int] - length up to which pad line numbers.
  41. */
  42. 'pad-line-numbers' : false,
  43. /** Lines to highlight. */
  44. 'highlight' : null,
  45. /** Title to be displayed above the code block. */
  46. 'title' : null,
  47. /** Enables or disables smart tabs. */
  48. 'smart-tabs' : true,
  49. /** Gets or sets tab size. */
  50. 'tab-size' : 4,
  51. /** Enables or disables gutter. */
  52. 'gutter' : true,
  53. /** Enables or disables toolbar. */
  54. 'toolbar' : true,
  55. /** Enables quick code copy and paste from double click. */
  56. 'quick-code' : true,
  57. /** Forces code view to be collapsed. */
  58. 'collapse' : false,
  59. /** Enables or disables automatic links. */
  60. 'auto-links' : true,
  61. /** Gets or sets light mode. Equavalent to turning off gutter and toolbar. */
  62. 'light' : false,
  63. 'html-script' : false
  64. },
  65. config : {
  66. space : ' ',
  67. /** Enables use of <SCRIPT type="syntaxhighlighter" /> tags. */
  68. useScriptTags : true,
  69. /** Blogger mode flag. */
  70. bloggerMode : false,
  71. stripBrs : false,
  72. /** Name of the tag that SyntaxHighlighter will automatically look for. */
  73. tagName : 'pre',
  74. strings : {
  75. expandSource : 'expand source',
  76. help : '?',
  77. alert: 'SyntaxHighlighter\n\n',
  78. noBrush : 'Can\'t find brush for: ',
  79. brushNotHtmlScript : 'Brush wasn\'t configured for html-script option: ',
  80. // this is populated by the build script
  81. aboutDialog : '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>About SyntaxHighlighter</title></head><body style="font-family:Geneva,Arial,Helvetica,sans-serif;background-color:#fff;color:#000;font-size:1em;text-align:center;"><div style="text-align:center;margin-top:1.5em;"><div style="font-size:xx-large;">SyntaxHighlighter</div><div style="font-size:.75em;margin-bottom:3em;"><div>version 3.0.83 (July 02 2010)</div><div><a href="http://alexgorbatchev.com/SyntaxHighlighter" target="_blank" style="color:#005896">http://alexgorbatchev.com/SyntaxHighlighter</a></div><div>JavaScript code syntax highlighter.</div><div>Copyright 2004-2010 Alex Gorbatchev.</div></div><div>If you like this script, please <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2930402" style="color:#005896">donate</a> to <br/>keep development active!</div></div></body></html>'
  82. }
  83. },
  84. /** Internal 'global' variables. */
  85. vars : {
  86. discoveredBrushes : null,
  87. highlighters : {}
  88. },
  89. /** This object is populated by user included external brush files. */
  90. brushes : {},
  91. /** Common regular expressions. */
  92. regexLib : {
  93. multiLineCComments : /\/\*[\s\S]*?\*\//gm,
  94. singleLineCComments : /\/\/.*$/gm,
  95. singleLinePerlComments : /#.*$/gm,
  96. doubleQuotedString : /"([^\\"\n]|\\.)*"/g,
  97. singleQuotedString : /'([^\\'\n]|\\.)*'/g,
  98. multiLineDoubleQuotedString : new XRegExp('"([^\\\\"]|\\\\.)*"', 'gs'),
  99. multiLineSingleQuotedString : new XRegExp("'([^\\\\']|\\\\.)*'", 'gs'),
  100. xmlComments : /(&lt;|<)!--[\s\S]*?--(&gt;|>)/gm,
  101. url : /\w+:\/\/[\w-.\/?%&=:@;]*/g,
  102. /** <?= ?> tags. */
  103. phpScriptTags : { left: /(&lt;|<)\?=?/g, right: /\?(&gt;|>)/g },
  104. /** <%= %> tags. */
  105. aspScriptTags : { left: /(&lt;|<)%=?/g, right: /%(&gt;|>)/g },
  106. /** <script></script> tags. */
  107. scriptScriptTags : { left: /(&lt;|<)\s*script.*?(&gt;|>)/gi, right: /(&lt;|<)\/\s*script\s*(&gt;|>)/gi }
  108. },
  109. toolbar: {
  110. /**
  111. * Generates HTML markup for the toolbar.
  112. * @param {Highlighter} highlighter Highlighter instance.
  113. * @return {String} Returns HTML markup.
  114. */
  115. getHtml: function(highlighter)
  116. {
  117. var html = '<div class="toolbar">',
  118. items = sh.toolbar.items,
  119. list = items.list
  120. ;
  121. function defaultGetHtml(highlighter, name)
  122. {
  123. return sh.toolbar.getButtonHtml(highlighter, name, sh.config.strings[name]);
  124. };
  125. for (var i = 0; i < list.length; i++)
  126. html += (items[list[i]].getHtml || defaultGetHtml)(highlighter, list[i]);
  127. html += '</div>';
  128. return html;
  129. },
  130. /**
  131. * Generates HTML markup for a regular button in the toolbar.
  132. * @param {Highlighter} highlighter Highlighter instance.
  133. * @param {String} commandName Command name that would be executed.
  134. * @param {String} label Label text to display.
  135. * @return {String} Returns HTML markup.
  136. */
  137. getButtonHtml: function(highlighter, commandName, label)
  138. {
  139. return '<span><a href="#" class="toolbar_item'
  140. + ' command_' + commandName
  141. + ' ' + commandName
  142. + '">' + label + '</a></span>'
  143. ;
  144. },
  145. /**
  146. * Event handler for a toolbar anchor.
  147. */
  148. handler: function(e)
  149. {
  150. var target = e.target,
  151. className = target.className || ''
  152. ;
  153. function getValue(name)
  154. {
  155. var r = new RegExp(name + '_(\\w+)'),
  156. match = r.exec(className)
  157. ;
  158. return match ? match[1] : null;
  159. };
  160. var highlighter = getHighlighterById(findParentElement(target, '.syntaxhighlighter').id),
  161. commandName = getValue('command')
  162. ;
  163. // execute the toolbar command
  164. if (highlighter && commandName)
  165. sh.toolbar.items[commandName].execute(highlighter);
  166. // disable default A click behaviour
  167. e.preventDefault();
  168. },
  169. /** Collection of toolbar items. */
  170. items : {
  171. // Ordered lis of items in the toolbar. Can't expect `for (var n in items)` to be consistent.
  172. list: ['expandSource', 'help'],
  173. expandSource: {
  174. getHtml: function(highlighter)
  175. {
  176. if (highlighter.getParam('collapse') != true)
  177. return '';
  178. var title = highlighter.getParam('title');
  179. return sh.toolbar.getButtonHtml(highlighter, 'expandSource', title ? title : sh.config.strings.expandSource);
  180. },
  181. execute: function(highlighter)
  182. {
  183. var div = getHighlighterDivById(highlighter.id);
  184. removeClass(div, 'collapsed');
  185. }
  186. },
  187. /** Command to display the about dialog window. */
  188. help: {
  189. execute: function(highlighter)
  190. {
  191. var wnd = popup('', '_blank', 500, 250, 'scrollbars=0'),
  192. doc = wnd.document
  193. ;
  194. doc.write(sh.config.strings.aboutDialog);
  195. doc.close();
  196. wnd.focus();
  197. }
  198. }
  199. }
  200. },
  201. /**
  202. * Finds all elements on the page which should be processes by SyntaxHighlighter.
  203. *
  204. * @param {Object} globalParams Optional parameters which override element's
  205. * parameters. Only used if element is specified.
  206. *
  207. * @param {Object} element Optional element to highlight. If none is
  208. * provided, all elements in the current document
  209. * are returned which qualify.
  210. *
  211. * @return {Array} Returns list of <code>{ target: DOMElement, params: Object }</code> objects.
  212. */
  213. findElements: function(globalParams, element)
  214. {
  215. var elements = element ? [element] : toArray(document.getElementsByTagName(sh.config.tagName)),
  216. conf = sh.config,
  217. result = []
  218. ;
  219. // support for <SCRIPT TYPE="syntaxhighlighter" /> feature
  220. if (conf.useScriptTags)
  221. elements = elements.concat(getSyntaxHighlighterScriptTags());
  222. if (elements.length === 0)
  223. return result;
  224. for (var i = 0; i < elements.length; i++)
  225. {
  226. var item = {
  227. target: elements[i],
  228. // local params take precedence over globals
  229. params: merge(globalParams, parseParams(elements[i].className))
  230. };
  231. if (item.params['brush'] == null)
  232. continue;
  233. result.push(item);
  234. }
  235. return result;
  236. },
  237. /**
  238. * Shorthand to highlight all elements on the page that are marked as
  239. * SyntaxHighlighter source code.
  240. *
  241. * @param {Object} globalParams Optional parameters which override element's
  242. * parameters. Only used if element is specified.
  243. *
  244. * @param {Object} element Optional element to highlight. If none is
  245. * provided, all elements in the current document
  246. * are highlighted.
  247. */
  248. highlight: function(globalParams, element)
  249. {
  250. var elements = this.findElements(globalParams, element),
  251. propertyName = 'innerHTML',
  252. highlighter = null,
  253. conf = sh.config
  254. ;
  255. if (elements.length === 0)
  256. return;
  257. for (var i = 0; i < elements.length; i++)
  258. {
  259. var element = elements[i],
  260. target = element.target,
  261. params = element.params,
  262. brushName = params.brush,
  263. code
  264. ;
  265. if (brushName == null)
  266. continue;
  267. // Instantiate a brush
  268. if (params['html-script'] == 'true' || sh.defaults['html-script'] == true)
  269. {
  270. highlighter = new sh.HtmlScript(brushName);
  271. brushName = 'htmlscript';
  272. }
  273. else
  274. {
  275. var brush = findBrush(brushName);
  276. if (brush)
  277. highlighter = new brush();
  278. else
  279. continue;
  280. }
  281. code = target[propertyName];
  282. // remove CDATA from <SCRIPT/> tags if it's present
  283. if (conf.useScriptTags)
  284. code = stripCData(code);
  285. // Inject title if the attribute is present
  286. if ((target.title || '') != '')
  287. params.title = target.title;
  288. params['brush'] = brushName;
  289. highlighter.init(params);
  290. element = highlighter.getDiv(code);
  291. // carry over ID
  292. if ((target.id || '') != '')
  293. element.id = target.id;
  294. target.parentNode.replaceChild(element, target);
  295. }
  296. },
  297. /**
  298. * Main entry point for the SyntaxHighlighter.
  299. * @param {Object} params Optional params to apply to all highlighted elements.
  300. */
  301. all: function(params)
  302. {
  303. attachEvent(
  304. window,
  305. 'load',
  306. function() { sh.highlight(params); }
  307. );
  308. }
  309. }; // end of sh
  310. sh['all'] = sh.all;
  311. sh['highlight'] = sh.highlight;
  312. /**
  313. * Checks if target DOM elements has specified CSS class.
  314. * @param {DOMElement} target Target DOM element to check.
  315. * @param {String} className Name of the CSS class to check for.
  316. * @return {Boolean} Returns true if class name is present, false otherwise.
  317. */
  318. function hasClass(target, className)
  319. {
  320. return target.className.indexOf(className) != -1;
  321. };
  322. /**
  323. * Adds CSS class name to the target DOM element.
  324. * @param {DOMElement} target Target DOM element.
  325. * @param {String} className New CSS class to add.
  326. */
  327. function addClass(target, className)
  328. {
  329. if (!hasClass(target, className))
  330. target.className += ' ' + className;
  331. };
  332. /**
  333. * Removes CSS class name from the target DOM element.
  334. * @param {DOMElement} target Target DOM element.
  335. * @param {String} className CSS class to remove.
  336. */
  337. function removeClass(target, className)
  338. {
  339. target.className = target.className.replace(className, '');
  340. };
  341. /**
  342. * Converts the source to array object. Mostly used for function arguments and
  343. * lists returned by getElementsByTagName() which aren't Array objects.
  344. * @param {List} source Source list.
  345. * @return {Array} Returns array.
  346. */
  347. function toArray(source)
  348. {
  349. var result = [];
  350. for (var i = 0; i < source.length; i++)
  351. result.push(source[i]);
  352. return result;
  353. };
  354. /**
  355. * Splits block of text into lines.
  356. * @param {String} block Block of text.
  357. * @return {Array} Returns array of lines.
  358. */
  359. function splitLines(block)
  360. {
  361. return block.split('\n');
  362. }
  363. /**
  364. * Generates HTML ID for the highlighter.
  365. * @param {String} highlighterId Highlighter ID.
  366. * @return {String} Returns HTML ID.
  367. */
  368. function getHighlighterId(id)
  369. {
  370. var prefix = 'highlighter_';
  371. return id.indexOf(prefix) == 0 ? id : prefix + id;
  372. };
  373. /**
  374. * Finds Highlighter instance by ID.
  375. * @param {String} highlighterId Highlighter ID.
  376. * @return {Highlighter} Returns instance of the highlighter.
  377. */
  378. function getHighlighterById(id)
  379. {
  380. return sh.vars.highlighters[getHighlighterId(id)];
  381. };
  382. /**
  383. * Finds highlighter's DIV container.
  384. * @param {String} highlighterId Highlighter ID.
  385. * @return {Element} Returns highlighter's DIV element.
  386. */
  387. function getHighlighterDivById(id)
  388. {
  389. return document.getElementById(getHighlighterId(id));
  390. };
  391. /**
  392. * Stores highlighter so that getHighlighterById() can do its thing. Each
  393. * highlighter must call this method to preserve itself.
  394. * @param {Highilghter} highlighter Highlighter instance.
  395. */
  396. function storeHighlighter(highlighter)
  397. {
  398. sh.vars.highlighters[getHighlighterId(highlighter.id)] = highlighter;
  399. };
  400. /**
  401. * Looks for a child or parent node which has specified classname.
  402. * Equivalent to jQuery's $(container).find(".className")
  403. * @param {Element} target Target element.
  404. * @param {String} search Class name or node name to look for.
  405. * @param {Boolean} reverse If set to true, will go up the node tree instead of down.
  406. * @return {Element} Returns found child or parent element on null.
  407. */
  408. function findElement(target, search, reverse /* optional */)
  409. {
  410. if (target == null)
  411. return null;
  412. var nodes = reverse != true ? target.childNodes : [ target.parentNode ],
  413. propertyToFind = { '#' : 'id', '.' : 'className' }[search.substr(0, 1)] || 'nodeName',
  414. expectedValue,
  415. found
  416. ;
  417. expectedValue = propertyToFind != 'nodeName'
  418. ? search.substr(1)
  419. : search.toUpperCase()
  420. ;
  421. // main return of the found node
  422. if ((target[propertyToFind] || '').indexOf(expectedValue) != -1)
  423. return target;
  424. for (var i = 0; nodes && i < nodes.length && found == null; i++)
  425. found = findElement(nodes[i], search, reverse);
  426. return found;
  427. };
  428. /**
  429. * Looks for a parent node which has specified classname.
  430. * This is an alias to <code>findElement(container, className, true)</code>.
  431. * @param {Element} target Target element.
  432. * @param {String} className Class name to look for.
  433. * @return {Element} Returns found parent element on null.
  434. */
  435. function findParentElement(target, className)
  436. {
  437. return findElement(target, className, true);
  438. };
  439. /**
  440. * Finds an index of element in the array.
  441. * @ignore
  442. * @param {Object} searchElement
  443. * @param {Number} fromIndex
  444. * @return {Number} Returns index of element if found; -1 otherwise.
  445. */
  446. function indexOf(array, searchElement, fromIndex)
  447. {
  448. fromIndex = Math.max(fromIndex || 0, 0);
  449. for (var i = fromIndex; i < array.length; i++)
  450. if(array[i] == searchElement)
  451. return i;
  452. return -1;
  453. };
  454. /**
  455. * Generates a unique element ID.
  456. */
  457. function guid(prefix)
  458. {
  459. return (prefix || '') + Math.round(Math.random() * 1000000).toString();
  460. };
  461. /**
  462. * Merges two objects. Values from obj2 override values in obj1.
  463. * Function is NOT recursive and works only for one dimensional objects.
  464. * @param {Object} obj1 First object.
  465. * @param {Object} obj2 Second object.
  466. * @return {Object} Returns combination of both objects.
  467. */
  468. function merge(obj1, obj2)
  469. {
  470. var result = {}, name;
  471. for (name in obj1)
  472. result[name] = obj1[name];
  473. for (name in obj2)
  474. result[name] = obj2[name];
  475. return result;
  476. };
  477. /**
  478. * Attempts to convert string to boolean.
  479. * @param {String} value Input string.
  480. * @return {Boolean} Returns true if input was "true", false if input was "false" and value otherwise.
  481. */
  482. function toBoolean(value)
  483. {
  484. var result = { "true" : true, "false" : false }[value];
  485. return result == null ? value : result;
  486. };
  487. /**
  488. * Opens up a centered popup window.
  489. * @param {String} url URL to open in the window.
  490. * @param {String} name Popup name.
  491. * @param {int} width Popup width.
  492. * @param {int} height Popup height.
  493. * @param {String} options window.open() options.
  494. * @return {Window} Returns window instance.
  495. */
  496. function popup(url, name, width, height, options)
  497. {
  498. var x = (screen.width - width) / 2,
  499. y = (screen.height - height) / 2
  500. ;
  501. options += ', left=' + x +
  502. ', top=' + y +
  503. ', width=' + width +
  504. ', height=' + height
  505. ;
  506. options = options.replace(/^,/, '');
  507. var win = window.open(url, name, options);
  508. win.focus();
  509. return win;
  510. };
  511. /**
  512. * Adds event handler to the target object.
  513. * @param {Object} obj Target object.
  514. * @param {String} type Name of the event.
  515. * @param {Function} func Handling function.
  516. */
  517. function attachEvent(obj, type, func, scope)
  518. {
  519. function handler(e)
  520. {
  521. e = e || window.event;
  522. if (!e.target)
  523. {
  524. e.target = e.srcElement;
  525. e.preventDefault = function()
  526. {
  527. this.returnValue = false;
  528. };
  529. }
  530. func.call(scope || window, e);
  531. };
  532. if (obj.attachEvent)
  533. {
  534. obj.attachEvent('on' + type, handler);
  535. }
  536. else
  537. {
  538. obj.addEventListener(type, handler, false);
  539. }
  540. };
  541. /**
  542. * Displays an alert.
  543. * @param {String} str String to display.
  544. */
  545. function alert(str)
  546. {
  547. window.alert(sh.config.strings.alert + str);
  548. };
  549. /**
  550. * Finds a brush by its alias.
  551. *
  552. * @param {String} alias Brush alias.
  553. * @param {Boolean} showAlert Suppresses the alert if false.
  554. * @return {Brush} Returns bursh constructor if found, null otherwise.
  555. */
  556. function findBrush(alias, showAlert)
  557. {
  558. var brushes = sh.vars.discoveredBrushes,
  559. result = null
  560. ;
  561. if (brushes == null)
  562. {
  563. brushes = {};
  564. // Find all brushes
  565. for (var brush in sh.brushes)
  566. {
  567. var info = sh.brushes[brush],
  568. aliases = info.aliases
  569. ;
  570. if (aliases == null)
  571. continue;
  572. // keep the brush name
  573. info.brushName = brush.toLowerCase();
  574. for (var i = 0; i < aliases.length; i++)
  575. brushes[aliases[i]] = brush;
  576. }
  577. sh.vars.discoveredBrushes = brushes;
  578. }
  579. result = sh.brushes[brushes[alias]];
  580. if (result == null && showAlert != false)
  581. alert(sh.config.strings.noBrush + alias);
  582. return result;
  583. };
  584. /**
  585. * Executes a callback on each line and replaces each line with result from the callback.
  586. * @param {Object} str Input string.
  587. * @param {Object} callback Callback function taking one string argument and returning a string.
  588. */
  589. function eachLine(str, callback)
  590. {
  591. var lines = splitLines(str);
  592. for (var i = 0; i < lines.length; i++)
  593. lines[i] = callback(lines[i], i);
  594. return lines.join('\n');
  595. };
  596. /**
  597. * This is a special trim which only removes first and last empty lines
  598. * and doesn't affect valid leading space on the first line.
  599. *
  600. * @param {String} str Input string
  601. * @return {String} Returns string without empty first and last lines.
  602. */
  603. function trimFirstAndLastLines(str)
  604. {
  605. return str.replace(/^[ ]*[\n]+|[\n]*[ ]*$/g, '');
  606. };
  607. /**
  608. * Parses key/value pairs into hash object.
  609. *
  610. * Understands the following formats:
  611. * - name: word;
  612. * - name: [word, word];
  613. * - name: "string";
  614. * - name: 'string';
  615. *
  616. * For example:
  617. * name1: value; name2: [value, value]; name3: 'value'
  618. *
  619. * @param {String} str Input string.
  620. * @return {Object} Returns deserialized object.
  621. */
  622. function parseParams(str)
  623. {
  624. var match,
  625. result = {},
  626. arrayRegex = new XRegExp("^\\[(?<values>(.*?))\\]$"),
  627. regex = new XRegExp(
  628. "(?<name>[\\w-]+)" +
  629. "\\s*:\\s*" +
  630. "(?<value>" +
  631. "[\\w-%#]+|" + // word
  632. "\\[.*?\\]|" + // [] array
  633. '".*?"|' + // "" string
  634. "'.*?'" + // '' string
  635. ")\\s*;?",
  636. "g"
  637. )
  638. ;
  639. while ((match = regex.exec(str)) != null)
  640. {
  641. var value = match.value
  642. .replace(/^['"]|['"]$/g, '') // strip quotes from end of strings
  643. ;
  644. // try to parse array value
  645. if (value != null && arrayRegex.test(value))
  646. {
  647. var m = arrayRegex.exec(value);
  648. value = m.values.length > 0 ? m.values.split(/\s*,\s*/) : [];
  649. }
  650. result[match.name] = value;
  651. }
  652. return result;
  653. };
  654. /**
  655. * Wraps each line of the string into <code/> tag with given style applied to it.
  656. *
  657. * @param {String} str Input string.
  658. * @param {String} css Style name to apply to the string.
  659. * @return {String} Returns input string with each line surrounded by <span/> tag.
  660. */
  661. function wrapLinesWithCode(str, css)
  662. {
  663. if (str == null || str.length == 0 || str == '\n')
  664. return str;
  665. str = str.replace(/</g, '&lt;');
  666. // Replace two or more sequential spaces with &nbsp; leaving last space untouched.
  667. str = str.replace(/ {2,}/g, function(m)
  668. {
  669. var spaces = '';
  670. for (var i = 0; i < m.length - 1; i++)
  671. spaces += sh.config.space;
  672. return spaces + ' ';
  673. });
  674. // Split each line and apply <span class="...">...</span> to them so that
  675. // leading spaces aren't included.
  676. if (css != null)
  677. str = eachLine(str, function(line)
  678. {
  679. if (line.length == 0)
  680. return '';
  681. var spaces = '';
  682. line = line.replace(/^(&nbsp;| )+/, function(s)
  683. {
  684. spaces = s;
  685. return '';
  686. });
  687. if (line.length == 0)
  688. return spaces;
  689. return spaces + '<code class="' + css + '">' + line + '</code>';
  690. });
  691. return str;
  692. };
  693. /**
  694. * Pads number with zeros until it's length is the same as given length.
  695. *
  696. * @param {Number} number Number to pad.
  697. * @param {Number} length Max string length with.
  698. * @return {String} Returns a string padded with proper amount of '0'.
  699. */
  700. function padNumber(number, length)
  701. {
  702. var result = number.toString();
  703. while (result.length < length)
  704. result = '0' + result;
  705. return result;
  706. };
  707. /**
  708. * Replaces tabs with spaces.
  709. *
  710. * @param {String} code Source code.
  711. * @param {Number} tabSize Size of the tab.
  712. * @return {String} Returns code with all tabs replaces by spaces.
  713. */
  714. function processTabs(code, tabSize)
  715. {
  716. var tab = '';
  717. for (var i = 0; i < tabSize; i++)
  718. tab += ' ';
  719. return code.replace(/\t/g, tab);
  720. };
  721. /**
  722. * Replaces tabs with smart spaces.
  723. *
  724. * @param {String} code Code to fix the tabs in.
  725. * @param {Number} tabSize Number of spaces in a column.
  726. * @return {String} Returns code with all tabs replaces with roper amount of spaces.
  727. */
  728. function processSmartTabs(code, tabSize)
  729. {
  730. var lines = splitLines(code),
  731. tab = '\t',
  732. spaces = ''
  733. ;
  734. // Create a string with 1000 spaces to copy spaces from...
  735. // It's assumed that there would be no indentation longer than that.
  736. for (var i = 0; i < 50; i++)
  737. spaces += ' '; // 20 spaces * 50
  738. // This function inserts specified amount of spaces in the string
  739. // where a tab is while removing that given tab.
  740. function insertSpaces(line, pos, count)
  741. {
  742. return line.substr(0, pos)
  743. + spaces.substr(0, count)
  744. + line.substr(pos + 1, line.length) // pos + 1 will get rid of the tab
  745. ;
  746. };
  747. // Go through all the lines and do the 'smart tabs' magic.
  748. code = eachLine(code, function(line)
  749. {
  750. if (line.indexOf(tab) == -1)
  751. return line;
  752. var pos = 0;
  753. while ((pos = line.indexOf(tab)) != -1)
  754. {
  755. // This is pretty much all there is to the 'smart tabs' logic.
  756. // Based on the position within the line and size of a tab,
  757. // calculate the amount of spaces we need to insert.
  758. var spaces = tabSize - pos % tabSize;
  759. line = insertSpaces(line, pos, spaces);
  760. }
  761. return line;
  762. });
  763. return code;
  764. };
  765. /**
  766. * Performs various string fixes based on configuration.
  767. */
  768. function fixInputString(str)
  769. {
  770. var br = /<br\s*\/?>|&lt;br\s*\/?&gt;/gi;
  771. if (sh.config.bloggerMode == true)
  772. str = str.replace(br, '\n');
  773. if (sh.config.stripBrs == true)
  774. str = str.replace(br, '');
  775. return str;
  776. };
  777. /**
  778. * Removes all white space at the begining and end of a string.
  779. *
  780. * @param {String} str String to trim.
  781. * @return {String} Returns string without leading and following white space characters.
  782. */
  783. function trim(str)
  784. {
  785. return str.replace(/^\s+|\s+$/g, '');
  786. };
  787. /**
  788. * Unindents a block of text by the lowest common indent amount.
  789. * @param {String} str Text to unindent.
  790. * @return {String} Returns unindented text block.
  791. */
  792. function unindent(str)
  793. {
  794. var lines = splitLines(fixInputString(str)),
  795. indents = new Array(),
  796. regex = /^\s*/,
  797. min = 1000
  798. ;
  799. // go through every line and check for common number of indents
  800. for (var i = 0; i < lines.length && min > 0; i++)
  801. {
  802. var line = lines[i];
  803. if (trim(line).length == 0)
  804. continue;
  805. var matches = regex.exec(line);
  806. // In the event that just one line doesn't have leading white space
  807. // we can't unindent anything, so bail completely.
  808. if (matches == null)
  809. return str;
  810. min = Math.min(matches[0].length, min);
  811. }
  812. // trim minimum common number of white space from the begining of every line
  813. if (min > 0)
  814. for (var i = 0; i < lines.length; i++)
  815. lines[i] = lines[i].substr(min);
  816. return lines.join('\n');
  817. };
  818. /**
  819. * Callback method for Array.sort() which sorts matches by
  820. * index position and then by length.
  821. *
  822. * @param {Match} m1 Left object.
  823. * @param {Match} m2 Right object.
  824. * @return {Number} Returns -1, 0 or -1 as a comparison result.
  825. */
  826. function matchesSortCallback(m1, m2)
  827. {
  828. // sort matches by index first
  829. if(m1.index < m2.index)
  830. return -1;
  831. else if(m1.index > m2.index)
  832. return 1;
  833. else
  834. {
  835. // if index is the same, sort by length
  836. if(m1.length < m2.length)
  837. return -1;
  838. else if(m1.length > m2.length)
  839. return 1;
  840. }
  841. return 0;
  842. };
  843. /**
  844. * Executes given regular expression on provided code and returns all
  845. * matches that are found.
  846. *
  847. * @param {String} code Code to execute regular expression on.
  848. * @param {Object} regex Regular expression item info from <code>regexList</code> collection.
  849. * @return {Array} Returns a list of Match objects.
  850. */
  851. function getMatches(code, regexInfo)
  852. {
  853. function defaultAdd(match, regexInfo)
  854. {
  855. return match[0];
  856. };
  857. var index = 0,
  858. match = null,
  859. matches = [],
  860. func = regexInfo.func ? regexInfo.func : defaultAdd
  861. ;
  862. while((match = regexInfo.regex.exec(code)) != null)
  863. {
  864. var resultMatch = func(match, regexInfo);
  865. if (typeof(resultMatch) == 'string')
  866. resultMatch = [new sh.Match(resultMatch, match.index, regexInfo.css)];
  867. matches = matches.concat(resultMatch);
  868. }
  869. return matches;
  870. };
  871. /**
  872. * Turns all URLs in the code into <a/> tags.
  873. * @param {String} code Input code.
  874. * @return {String} Returns code with </a> tags.
  875. */
  876. function processUrls(code)
  877. {
  878. var gt = /(.*)((&gt;|&lt;).*)/;
  879. return code.replace(sh.regexLib.url, function(m)
  880. {
  881. var suffix = '',
  882. match = null
  883. ;
  884. // We include &lt; and &gt; in the URL for the common cases like <http://google.com>
  885. // The problem is that they get transformed into &lt;http://google.com&gt;
  886. // Where as &gt; easily looks like part of the URL string.
  887. if (match = gt.exec(m))
  888. {
  889. m = match[1];
  890. suffix = match[2];
  891. }
  892. return '<a href="' + m + '">' + m + '</a>' + suffix;
  893. });
  894. };
  895. /**
  896. * Finds all <SCRIPT TYPE="syntaxhighlighter" /> elementss.
  897. * @return {Array} Returns array of all found SyntaxHighlighter tags.
  898. */
  899. function getSyntaxHighlighterScriptTags()
  900. {
  901. var tags = document.getElementsByTagName('script'),
  902. result = []
  903. ;
  904. for (var i = 0; i < tags.length; i++)
  905. if (tags[i].type == 'syntaxhighlighter')
  906. result.push(tags[i]);
  907. return result;
  908. };
  909. /**
  910. * Strips <![CDATA[]]> from <SCRIPT /> content because it should be used
  911. * there in most cases for XHTML compliance.
  912. * @param {String} original Input code.
  913. * @return {String} Returns code without leading <![CDATA[]]> tags.
  914. */
  915. function stripCData(original)
  916. {
  917. var left = '<![CDATA[',
  918. right = ']]>',
  919. // for some reason IE inserts some leading blanks here
  920. copy = trim(original),
  921. changed = false,
  922. leftLength = left.length,
  923. rightLength = right.length
  924. ;
  925. if (copy.indexOf(left) == 0)
  926. {
  927. copy = copy.substring(leftLength);
  928. changed = true;
  929. }
  930. var copyLength = copy.length;
  931. if (copy.indexOf(right) == copyLength - rightLength)
  932. {
  933. copy = copy.substring(0, copyLength - rightLength);
  934. changed = true;
  935. }
  936. return changed ? copy : original;
  937. };
  938. /**
  939. * Quick code mouse double click handler.
  940. */
  941. function quickCodeHandler(e)
  942. {
  943. var target = e.target,
  944. highlighterDiv = findParentElement(target, '.syntaxhighlighter'),
  945. container = findParentElement(target, '.container'),
  946. textarea = document.createElement('textarea'),
  947. highlighter
  948. ;
  949. if (!container || !highlighterDiv || findElement(container, 'textarea'))
  950. return;
  951. highlighter = getHighlighterById(highlighterDiv.id);
  952. // add source class name
  953. addClass(highlighterDiv, 'source');
  954. // Have to go over each line and grab it's text, can't just do it on the
  955. // container because Firefox loses all \n where as Webkit doesn't.
  956. var lines = container.childNodes,
  957. code = []
  958. ;
  959. for (var i = 0; i < lines.length; i++)
  960. code.push(lines[i].innerText || lines[i].textContent);
  961. // using \r instead of \r or \r\n makes this work equally well on IE, FF and Webkit
  962. code = code.join('\r');
  963. // inject <textarea/> tag
  964. textarea.appendChild(document.createTextNode(code));
  965. container.appendChild(textarea);
  966. // preselect all text
  967. textarea.focus();
  968. textarea.select();
  969. // set up handler for lost focus
  970. attachEvent(textarea, 'blur', function(e)
  971. {
  972. textarea.parentNode.removeChild(textarea);
  973. removeClass(highlighterDiv, 'source');
  974. });
  975. };
  976. /**
  977. * Match object.
  978. */
  979. sh.Match = function(value, index, css)
  980. {
  981. this.value = value;
  982. this.index = index;
  983. this.length = value.length;
  984. this.css = css;
  985. this.brushName = null;
  986. };
  987. sh.Match.prototype.toString = function()
  988. {
  989. return this.value;
  990. };
  991. /**
  992. * Simulates HTML code with a scripting language embedded.
  993. *
  994. * @param {String} scriptBrushName Brush name of the scripting language.
  995. */
  996. sh.HtmlScript = function(scriptBrushName)
  997. {
  998. var brushClass = findBrush(scriptBrushName),
  999. scriptBrush,
  1000. xmlBrush = new sh.brushes.Xml(),
  1001. bracketsRegex = null,
  1002. ref = this,
  1003. methodsToExpose = 'getDiv getHtml init'.split(' ')
  1004. ;
  1005. if (brushClass == null)
  1006. return;
  1007. scriptBrush = new brushClass();
  1008. for(var i = 0; i < methodsToExpose.length; i++)
  1009. // make a closure so we don't lose the name after i changes
  1010. (function() {
  1011. var name = methodsToExpose[i];
  1012. ref[name] = function()
  1013. {
  1014. return xmlBrush[name].apply(xmlBrush, arguments);
  1015. };
  1016. })();
  1017. if (scriptBrush.htmlScript == null)
  1018. {
  1019. alert(sh.config.strings.brushNotHtmlScript + scriptBrushName);
  1020. return;
  1021. }
  1022. xmlBrush.regexList.push(
  1023. { regex: scriptBrush.htmlScript.code, func: process }
  1024. );
  1025. function offsetMatches(matches, offset)
  1026. {
  1027. for (var j = 0; j < matches.length; j++)
  1028. matches[j].index += offset;
  1029. }
  1030. function process(match, info)
  1031. {
  1032. var code = match.code,
  1033. matches = [],
  1034. regexList = scriptBrush.regexList,
  1035. offset = match.index + match.left.length,
  1036. htmlScript = scriptBrush.htmlScript,
  1037. result
  1038. ;
  1039. // add all matches from the code
  1040. for (var i = 0; i < regexList.length; i++)
  1041. {
  1042. result = getMatches(code, regexList[i]);
  1043. offsetMatches(result, offset);
  1044. matches = matches.concat(result);
  1045. }
  1046. // add left script bracket
  1047. if (htmlScript.left != null && match.left != null)
  1048. {
  1049. result = getMatches(match.left, htmlScript.left);
  1050. offsetMatches(result, match.index);
  1051. matches = matches.concat(result);
  1052. }
  1053. // add right script bracket
  1054. if (htmlScript.right != null && match.right != null)
  1055. {
  1056. result = getMatches(match.right, htmlScript.right);
  1057. offsetMatches(result, match.index + match[0].lastIndexOf(match.right));
  1058. matches = matches.concat(result);
  1059. }
  1060. for (var j = 0; j < matches.length; j++)
  1061. matches[j].brushName = brushClass.brushName;
  1062. return matches;
  1063. }
  1064. };
  1065. /**
  1066. * Main Highlither class.
  1067. * @constructor
  1068. */
  1069. sh.Highlighter = function()
  1070. {
  1071. // not putting any code in here because of the prototype inheritance
  1072. };
  1073. sh.Highlighter.prototype = {
  1074. /**
  1075. * Returns value of the parameter passed to the highlighter.
  1076. * @param {String} name Name of the parameter.
  1077. * @param {Object} defaultValue Default value.
  1078. * @return {Object} Returns found value or default value otherwise.
  1079. */
  1080. getParam: function(name, defaultValue)
  1081. {
  1082. var result = this.params[name];
  1083. return toBoolean(result == null ? defaultValue : result);
  1084. },
  1085. /**
  1086. * Shortcut to document.createElement().
  1087. * @param {String} name Name of the element to create (DIV, A, etc).
  1088. * @return {HTMLElement} Returns new HTML element.
  1089. */
  1090. create: function(name)
  1091. {
  1092. return document.createElement(name);
  1093. },
  1094. /**
  1095. * Applies all regular expression to the code and stores all found
  1096. * matches in the `this.matches` array.
  1097. * @param {Array} regexList List of regular expressions.
  1098. * @param {String} code Source code.
  1099. * @return {Array} Returns list of matches.
  1100. */
  1101. findMatches: function(regexList, code)
  1102. {
  1103. var result = [];
  1104. if (regexList != null)
  1105. for (var i = 0; i < regexList.length; i++)
  1106. // BUG: length returns len+1 for array if methods added to prototype chain (oising@gmail.com)
  1107. if (typeof (regexList[i]) == "object")
  1108. result = result.concat(getMatches(code, regexList[i]));
  1109. // sort and remove nested the matches
  1110. return this.removeNestedMatches(result.sort(matchesSortCallback));
  1111. },
  1112. /**
  1113. * Checks to see if any of the matches are inside of other matches.
  1114. * This process would get rid of highligted strings inside comments,
  1115. * keywords inside strings and so on.
  1116. */
  1117. removeNestedMatches: function(matches)
  1118. {
  1119. // Optimized by Jose Prado (http://joseprado.com)
  1120. for (var i = 0; i < matches.length; i++)
  1121. {
  1122. if (matches[i] === null)
  1123. continue;
  1124. var itemI = matches[i],
  1125. itemIEndPos = itemI.index + itemI.length
  1126. ;
  1127. for (var j = i + 1; j < matches.length && matches[i] !== null; j++)
  1128. {
  1129. var itemJ = matches[j];
  1130. if (itemJ === null)
  1131. continue;
  1132. else if (itemJ.index > itemIEndPos)
  1133. break;
  1134. else if (itemJ.index == itemI.index && itemJ.length > itemI.length)
  1135. matches[i] = null;
  1136. else if (itemJ.index >= itemI.index && itemJ.index < itemIEndPos)
  1137. matches[j] = null;
  1138. }
  1139. }
  1140. return matches;
  1141. },
  1142. /**
  1143. * Creates an array containing integer line numbers starting from the 'first-line' param.
  1144. * @return {Array} Returns array of integers.
  1145. */
  1146. figureOutLineNumbers: function(code)
  1147. {
  1148. var lines = [],
  1149. firstLine = parseInt(this.getParam('first-line'))
  1150. ;
  1151. eachLine(code, function(line, index)
  1152. {
  1153. lines.push(index + firstLine);
  1154. });
  1155. return lines;
  1156. },
  1157. /**
  1158. * Determines if specified line number is in the highlighted list.
  1159. */
  1160. isLineHighlighted: function(lineNumber)
  1161. {
  1162. var list = this.getParam('highlight', []);
  1163. if (typeof(list) != 'object' && list.push == null)
  1164. list = [ list ];
  1165. return indexOf(list, lineNumber.toString()) != -1;
  1166. },
  1167. /**
  1168. * Generates HTML markup for a single line of code while determining alternating line style.
  1169. * @param {Integer} lineNumber Line number.
  1170. * @param {String} code Line HTML markup.
  1171. * @return {String} Returns HTML markup.
  1172. */
  1173. getLineHtml: function(lineIndex, lineNumber, code)
  1174. {
  1175. var classes = [
  1176. 'line',
  1177. 'number' + lineNumber,
  1178. 'index' + lineIndex,
  1179. 'alt' + (lineNumber % 2 == 0 ? 1 : 2).toString()
  1180. ];
  1181. if (this.isLineHighlighted(lineNumber))
  1182. classes.push('highlighted');
  1183. if (lineNumber == 0)
  1184. classes.push('break');
  1185. return '<div class="' + classes.join(' ') + '">' + code + '</div>';
  1186. },
  1187. /**
  1188. * Generates HTML markup for line number column.
  1189. * @param {String} code Complete code HTML markup.
  1190. * @param {Array} lineNumbers Calculated line numbers.
  1191. * @return {String} Returns HTML markup.
  1192. */
  1193. getLineNumbersHtml: function(code, lineNumbers)
  1194. {
  1195. var html = '',
  1196. count = splitLines(code).length,
  1197. firstLine = parseInt(this.getParam('first-line')),
  1198. pad = this.getParam('pad-line-numbers')
  1199. ;
  1200. if (pad == true)
  1201. pad = (firstLine + count - 1).toString().length;
  1202. else if (isNaN(pad) == true)
  1203. pad = 0;
  1204. for (var i = 0; i < count; i++)
  1205. {
  1206. var lineNumber = lineNumbers ? lineNumbers[i] : firstLine + i,
  1207. code = lineNumber == 0 ? sh.config.space : padNumber(lineNumber, pad)
  1208. ;
  1209. html += this.getLineHtml(i, lineNumber, code);
  1210. }
  1211. return html;
  1212. },
  1213. /**
  1214. * Splits block of text into individual DIV lines.
  1215. * @param {String} code Code to highlight.
  1216. * @param {Array} lineNumbers Calculated line numbers.
  1217. * @return {String} Returns highlighted code in HTML form.
  1218. */
  1219. getCodeLinesHtml: function(html, lineNumbers)
  1220. {
  1221. html = trim(html);
  1222. var lines = splitLines(html),
  1223. padLength = this.getParam('pad-line-numbers'),
  1224. firstLine = parseInt(this.getParam('first-line')),
  1225. html = '',
  1226. brushName = this.getParam('brush')
  1227. ;
  1228. for (var i = 0; i < lines.length; i++)
  1229. {
  1230. var line = lines[i],
  1231. indent = /^(&nbsp;|\s)+/.exec(line),
  1232. spaces = null,
  1233. lineNumber = lineNumbers ? lineNumbers[i] : firstLine + i;
  1234. ;
  1235. if (indent != null)
  1236. {
  1237. spaces = indent[0].toString();
  1238. line = line.substr(spaces.length);
  1239. spaces = spaces.replace(' ', sh.config.space);
  1240. }
  1241. line = trim(line);
  1242. if (line.length == 0)
  1243. line = sh.config.space;
  1244. html += this.getLineHtml(
  1245. i,
  1246. lineNumber,
  1247. (spaces != null ? '<code class="' + brushName + ' spaces">' + spaces + '</code>' : '') + line
  1248. );
  1249. }
  1250. return html;
  1251. },
  1252. /**
  1253. * Returns HTML for the table title or empty string if title is null.
  1254. */
  1255. getTitleHtml: function(title)
  1256. {
  1257. return title ? '<caption>' + title + '</caption>' : '';
  1258. },
  1259. /**
  1260. * Finds all matches in the source code.
  1261. * @param {String} code Source code to process matches in.
  1262. * @param {Array} matches Discovered regex matches.
  1263. * @return {String} Returns formatted HTML with processed mathes.
  1264. */
  1265. getMatchesHtml: function(code, matches)
  1266. {
  1267. var pos = 0,
  1268. result = '',
  1269. brushName = this.getParam('brush', '')
  1270. ;
  1271. function getBrushNameCss(match)
  1272. {
  1273. var result = match ? (match.brushName || brushName) : brushName;
  1274. return result ? result + ' ' : '';
  1275. };
  1276. // Finally, go through the final list of matches and pull the all
  1277. // together adding everything in between that isn't a match.
  1278. for (var i = 0; i < matches.length; i++)
  1279. {
  1280. var match = matches[i],
  1281. matchBrushName
  1282. ;
  1283. if (match === null || match.length === 0)
  1284. continue;
  1285. matchBrushName = getBrushNameCss(match);
  1286. result += wrapLinesWithCode(code.substr(pos, match.index - pos), matchBrushName + 'plain')
  1287. + wrapLinesWithCode(match.value, matchBrushName + match.css)
  1288. ;
  1289. pos = match.index + match.length + (match.offset || 0);
  1290. }
  1291. // don't forget to add whatever's remaining in the string
  1292. result += wrapLinesWithCode(code.substr(pos), getBrushNameCss() + 'plain');
  1293. return result;
  1294. },
  1295. /**
  1296. * Generates HTML markup for the whole syntax highlighter.
  1297. * @param {String} code Source code.
  1298. * @return {String} Returns HTML markup.
  1299. */
  1300. getHtml: function(code)
  1301. {
  1302. var html = '',
  1303. classes = [ 'syntaxhighlighter' ],
  1304. tabSize,
  1305. matches,
  1306. lineNumbers
  1307. ;
  1308. // process light mode
  1309. if (this.getParam('light') == true)
  1310. this.params.toolbar = this.params.gutter = false;
  1311. className = 'syntaxhighlighter';
  1312. if (this.getParam('collapse') == true)
  1313. classes.push('collapsed');
  1314. if ((gutter = this.getParam('gutter')) == false)
  1315. classes.push('nogutter');
  1316. // add custom user style name
  1317. classes.push(this.getParam('class-name'));
  1318. // add brush alias to the class name for custom CSS
  1319. classes.push(this.getParam('brush'));
  1320. code = trimFirstAndLastLines(code)
  1321. .replace(/\r/g, ' ') // IE lets these buggers through
  1322. ;
  1323. tabSize = this.getParam('tab-size');
  1324. // replace tabs with spaces
  1325. code = this.getParam('smart-tabs') == true
  1326. ? processSmartTabs(code, tabSize)
  1327. : processTabs(code, tabSize)
  1328. ;
  1329. // unindent code by the common indentation
  1330. code = unindent(code);
  1331. if (gutter)
  1332. lineNumbers = this.figureOutLineNumbers(code);
  1333. // find matches in the code using brushes regex list
  1334. matches = this.findMatches(this.regexList, code);
  1335. // processes found matches into the html
  1336. html = this.getMatchesHtml(code, matches);
  1337. // finally, split all lines so that they wrap well
  1338. html = this.getCodeLinesHtml(html, lineNumbers);
  1339. // finally, process the links
  1340. if (this.getParam('auto-links'))
  1341. html = processUrls(html);
  1342. if (typeof(navigator) != 'undefined' && navigator.userAgent && navigator.userAgent.match(/MSIE/))
  1343. classes.push('ie');
  1344. html =
  1345. '<div id="' + getHighlighterId(this.id) + '" class="' + classes.join(' ') + '">'
  1346. + (this.getParam('toolbar') ? sh.toolbar.getHtml(this) : '')
  1347. + '<table border="0" cellpadding="0" cellspacing="0">'
  1348. + this.getTitleHtml(this.getParam('title'))
  1349. + '<tbody>'
  1350. + '<tr>'
  1351. + (gutter ? '<td class="gutter">' + this.getLineNumbersHtml(code) + '</td>' : '')
  1352. + '<td class="code">'
  1353. + '<div class="container">'
  1354. + html
  1355. + '</div>'
  1356. + '</td>'
  1357. + '</tr>'
  1358. + '</tbody>'
  1359. + '</table>'
  1360. + '</div>'
  1361. ;
  1362. return html;
  1363. },
  1364. /**
  1365. * Highlights the code and returns complete HTML.
  1366. * @param {String} code Code to highlight.
  1367. * @return {Element} Returns container DIV element with all markup.
  1368. */
  1369. getDiv: function(code)
  1370. {
  1371. if (code === null)
  1372. code = '';
  1373. this.code = code;
  1374. var div = this.create('div');
  1375. // create main HTML
  1376. div.innerHTML = this.getHtml(code);
  1377. // set up click handlers
  1378. if (this.getParam('toolbar'))
  1379. attachEvent(findElement(div, '.toolbar'), 'click', sh.toolbar.handler);
  1380. if (this.getParam('quick-code'))
  1381. attachEvent(findElement(div, '.code'), 'dblclick', quickCodeHandler);
  1382. return div;
  1383. },
  1384. /**
  1385. * Initializes the highlighter/brush.
  1386. *
  1387. * Constructor isn't used for initialization so that nothing executes during necessary
  1388. * `new SyntaxHighlighter.Highlighter()` call when setting up brush inheritence.
  1389. *
  1390. * @param {Hash} params Highlighter parameters.
  1391. */
  1392. init: function(params)
  1393. {
  1394. this.id = guid();
  1395. // register this instance in the highlighters list
  1396. storeHighlighter(this);
  1397. // local params take precedence over defaults
  1398. this.params = merge(sh.defaults, params || {})
  1399. // process light mode
  1400. if (this.getParam('light') == true)
  1401. this.params.toolbar = this.params.gutter = false;
  1402. },
  1403. /**
  1404. * Converts space separated list of keywords into a regular expression string.
  1405. * @param {String} str Space separated keywords.
  1406. * @return {String} Returns regular expression string.
  1407. */
  1408. getKeywords: function(str)
  1409. {
  1410. str = str
  1411. .replace(/^\s+|\s+$/g, '')
  1412. .replace(/\s+/g, '|')
  1413. ;
  1414. return '\\b(?:' + str + ')\\b';
  1415. },
  1416. /**
  1417. * Makes a brush compatible with the `html-script` functionality.
  1418. * @param {Object} regexGroup Object containing `left` and `right` regular expressions.
  1419. */
  1420. forHtmlScript: function(regexGroup)
  1421. {
  1422. this.htmlScript = {
  1423. left : { regex: regexGroup.left, css: 'script' },
  1424. right : { regex: regexGroup.right, css: 'script' },
  1425. code : new XRegExp(
  1426. "(?<left>" + regexGroup.left.source + ")" +
  1427. "(?<code>.*?)" +
  1428. "(?<right>" + regexGroup.right.source + ")",
  1429. "sgi"
  1430. )
  1431. };
  1432. }
  1433. }; // end of Highlighter
  1434. return sh;
  1435. }(); // end of anonymous function
  1436. // CommonJS
  1437. typeof(exports) != 'undefined' ? exports['SyntaxHighlighter'] = SyntaxHighlighter : null;