prettify.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. // Copyright (C) 2006 Google Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview
  16. * some functions for browser-side pretty printing of code contained in html.
  17. *
  18. * The lexer should work on a number of languages including C and friends,
  19. * Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles.
  20. * It works passably on Ruby, PHP and Awk and a decent subset of Perl, but,
  21. * because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or
  22. * CAML-like languages.
  23. *
  24. * If there's a language not mentioned here, then I don't know it, and don't
  25. * know whether it works. If it has a C-like, Bash-like, or XML-like syntax
  26. * then it should work passably.
  27. *
  28. * Usage:
  29. * 1) include this source file in an html page via
  30. * <script type="text/javascript" src="/path/to/prettify.js"></script>
  31. * 2) define style rules. See the example page for examples.
  32. * 3) mark the <pre> and <code> tags in your source with class=prettyprint.
  33. * You can also use the (html deprecated) <xmp> tag, but the pretty printer
  34. * needs to do more substantial DOM manipulations to support that, so some
  35. * css styles may not be preserved.
  36. * That's it. I wanted to keep the API as simple as possible, so there's no
  37. * need to specify which language the code is in.
  38. *
  39. * Change log:
  40. * cbeust, 2006/08/22
  41. * Java annotations (start with "@") are now captured as literals ("lit")
  42. */
  43. var PR_keywords = {};
  44. /** initialize the keyword list for our target languages. */
  45. (function () {
  46. var CPP_KEYWORDS = "abstract bool break case catch char class const " +
  47. "const_cast continue default delete deprecated dllexport dllimport do " +
  48. "double dynamic_cast else enum explicit extern false float for friend " +
  49. "goto if inline int long mutable naked namespace new noinline noreturn " +
  50. "nothrow novtable operator private property protected public register " +
  51. "reinterpret_cast return selectany short signed sizeof static " +
  52. "static_cast struct switch template this thread throw true try typedef " +
  53. "typeid typename union unsigned using declaration, directive uuid " +
  54. "virtual void volatile while typeof";
  55. var CSHARP_KEYWORDS = "as base by byte checked decimal delegate descending " +
  56. "event finally fixed foreach from group implicit in interface internal " +
  57. "into is lock null object out override orderby params readonly ref sbyte " +
  58. "sealed stackalloc string select uint ulong unchecked unsafe ushort var";
  59. var JAVA_KEYWORDS = "package synchronized boolean implements import throws " +
  60. "instanceof transient extends final strictfp native super";
  61. var JSCRIPT_KEYWORDS = "debugger export function with NaN Infinity";
  62. var PERL_KEYWORDS = "require sub unless until use elsif BEGIN END";
  63. var PYTHON_KEYWORDS = "and assert def del elif except exec global lambda " +
  64. "not or pass print raise yield False True None";
  65. var RUBY_KEYWORDS = "then end begin rescue ensure module when undef next " +
  66. "redo retry alias defined";
  67. var SH_KEYWORDS = "done fi";
  68. var KEYWORDS = [CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_KEYWORDS,
  69. JSCRIPT_KEYWORDS, PERL_KEYWORDS, PYTHON_KEYWORDS,
  70. RUBY_KEYWORDS, SH_KEYWORDS];
  71. for (var k = 0; k < KEYWORDS.length; k++) {
  72. var kw = KEYWORDS[k].split(' ');
  73. for (var i = 0; i < kw.length; i++) {
  74. if (kw[i]) { PR_keywords[kw[i]] = true; }
  75. }
  76. }
  77. }).call(this);
  78. // token style names. correspond to css classes
  79. /** token style for a string literal */
  80. var PR_STRING = 'str';
  81. /** token style for a keyword */
  82. var PR_KEYWORD = 'kwd';
  83. /** token style for a comment */
  84. var PR_COMMENT = 'com';
  85. /** token style for a type */
  86. var PR_TYPE = 'typ';
  87. /** token style for a literal value. e.g. 1, null, true. */
  88. var PR_LITERAL = 'lit';
  89. /** token style for a punctuation string. */
  90. var PR_PUNCTUATION = 'pun';
  91. /** token style for a punctuation string. */
  92. var PR_PLAIN = 'pln';
  93. /** token style for an sgml tag. */
  94. var PR_TAG = 'tag';
  95. /** token style for a markup declaration such as a DOCTYPE. */
  96. var PR_DECLARATION = 'dec';
  97. /** token style for embedded source. */
  98. var PR_SOURCE = 'src';
  99. /** token style for an sgml attribute name. */
  100. var PR_ATTRIB_NAME = 'atn';
  101. /** token style for an sgml attribute value. */
  102. var PR_ATTRIB_VALUE = 'atv';
  103. /** the number of characters between tab columns */
  104. var PR_TAB_WIDTH = 4;
  105. // some string utilities
  106. function PR_isWordChar(ch) {
  107. return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
  108. }
  109. /** Splice one array into another.
  110. * Like the python <code>
  111. * container[containerPosition:containerPosition + countReplaced] = inserted
  112. * </code>
  113. * @param {Array} inserted
  114. * @param {Array} container modified in place
  115. * @param {Number} containerPosition
  116. * @param {Number} countReplaced
  117. */
  118. function PR_spliceArrayInto(
  119. inserted, container, containerPosition, countReplaced) {
  120. inserted.unshift(containerPosition, countReplaced || 0);
  121. try {
  122. container.splice.apply(container, inserted);
  123. } finally {
  124. inserted.splice(0, 2);
  125. }
  126. }
  127. /** a set of tokens that can precede a regular expression literal in javascript.
  128. * http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full
  129. * list, but I've removed ones that might be problematic when seen in languages
  130. * that don't support regular expression literals.
  131. *
  132. * <p>Specifically, I've removed any keywords that can't precede a regexp
  133. * literal in a syntactically legal javascript program, and I've removed the
  134. * "in" keyword since it's not a keyword in many languages, and might be used
  135. * as a count of inches.
  136. * @private
  137. */
  138. var REGEXP_PRECEDER_PATTERN = (function () {
  139. var preceders = [
  140. "!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=",
  141. "&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=",
  142. "->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";",
  143. "<", "<<", "<<=", "<=", "=", "==", "===", ">",
  144. ">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[",
  145. "^", "^=", "^^", "^^=", "{", "|", "|=", "||",
  146. "||=", "~", "break", "case", "continue", "delete",
  147. "do", "else", "finally", "instanceof",
  148. "return", "throw", "try", "typeof"
  149. ];
  150. var pattern = '(?:' +
  151. '(?:(?:^|[^0-9\.])\\.{1,3})|' + // a dot that's not part of a number
  152. '(?:(?:^|[^\\+])\\+)|' + // allow + but not ++
  153. '(?:(?:^|[^\\-])-)' // allow - but not --
  154. ;
  155. for (var i = 0; i < preceders.length; ++i) {
  156. var preceder = preceders[i];
  157. if (PR_isWordChar(preceder.charAt(0))) {
  158. pattern += '|\\b' + preceder;
  159. } else {
  160. pattern += '|' + preceder.replace(/([^=<>:&])/g, '\\$1');
  161. }
  162. }
  163. pattern += '|^)\\s*$'; // matches at end, and matches empty string
  164. return new RegExp(pattern);
  165. // CAVEAT: this does not properly handle the case where a regular expression
  166. // immediately follows another since a regular expression may have flags
  167. // for case-sensitivity and the like. Having regexp tokens adjacent is not
  168. // valid in any language I'm aware of, so I'm punting.
  169. // TODO: maybe style special characters inside a regexp as punctuation.
  170. })();
  171. // Define regexps here so that the interpreter doesn't have to create an object
  172. // each time the function containing them is called.
  173. // The language spec requires a new object created even if you don't access the
  174. // $1 members.
  175. var pr_amp = /&/g;
  176. var pr_lt = /</g;
  177. var pr_gt = />/g;
  178. var pr_quot = /\"/g;
  179. /** like textToHtml but escapes double quotes to be attribute safe. */
  180. function PR_attribToHtml(str) {
  181. return str.replace(pr_amp, '&amp;')
  182. .replace(pr_lt, '&lt;')
  183. .replace(pr_gt, '&gt;')
  184. .replace(pr_quot, '&quot;');
  185. }
  186. /** escapest html special characters to html. */
  187. function PR_textToHtml(str) {
  188. return str.replace(pr_amp, '&amp;')
  189. .replace(pr_lt, '&lt;')
  190. .replace(pr_gt, '&gt;');
  191. }
  192. var pr_ltEnt = /&lt;/g;
  193. var pr_gtEnt = /&gt;/g;
  194. var pr_aposEnt = /&apos;/g;
  195. var pr_quotEnt = /&quot;/g;
  196. var pr_ampEnt = /&amp;/g;
  197. /** unescapes html to plain text. */
  198. function PR_htmlToText(html) {
  199. var pos = html.indexOf('&');
  200. if (pos < 0) { return html; }
  201. // Handle numeric entities specially. We can't use functional substitution
  202. // since that doesn't work in older versions of Safari.
  203. // These should be rare since most browsers convert them to normal chars.
  204. for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
  205. var end = html.indexOf(';', pos);
  206. if (end >= 0) {
  207. var num = html.substring(pos + 3, end);
  208. var radix = 10;
  209. if (num && num.charAt(0) == 'x') {
  210. num = num.substring(1);
  211. radix = 16;
  212. }
  213. var codePoint = parseInt(num, radix);
  214. if (!isNaN(codePoint)) {
  215. html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
  216. html.substring(end + 1));
  217. }
  218. }
  219. }
  220. return html.replace(pr_ltEnt, '<')
  221. .replace(pr_gtEnt, '>')
  222. .replace(pr_aposEnt, "'")
  223. .replace(pr_quotEnt, '"')
  224. .replace(pr_ampEnt, '&');
  225. }
  226. /** is the given node's innerHTML normally unescaped? */
  227. function PR_isRawContent(node) {
  228. return 'XMP' == node.tagName;
  229. }
  230. var PR_innerHtmlWorks = null;
  231. function PR_getInnerHtml(node) {
  232. // inner html is hopelessly broken in Safari 2.0.4 when the content is
  233. // an html description of well formed XML and the containing tag is a PRE
  234. // tag, so we detect that case and emulate innerHTML.
  235. if (null === PR_innerHtmlWorks) {
  236. var testNode = document.createElement('PRE');
  237. testNode.appendChild(
  238. document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
  239. PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
  240. }
  241. if (PR_innerHtmlWorks) {
  242. var content = node.innerHTML;
  243. // XMP tags contain unescaped entities so require special handling.
  244. if (PR_isRawContent(node)) {
  245. content = PR_textToHtml(content);
  246. }
  247. return content;
  248. }
  249. var out = [];
  250. for (var child = node.firstChild; child; child = child.nextSibling) {
  251. PR_normalizedHtml(child, out);
  252. }
  253. return out.join('');
  254. }
  255. /** walks the DOM returning a properly escaped version of innerHTML.
  256. */
  257. function PR_normalizedHtml(node, out) {
  258. switch (node.nodeType) {
  259. case 1: // an element
  260. var name = node.tagName.toLowerCase();
  261. out.push('\074', name);
  262. for (var i = 0; i < node.attributes.length; ++i) {
  263. var attr = node.attributes[i];
  264. if (!attr.specified) { continue; }
  265. out.push(' ');
  266. PR_normalizedHtml(attr, out);
  267. }
  268. out.push('>');
  269. for (var child = node.firstChild; child; child = child.nextSibling) {
  270. PR_normalizedHtml(child, out);
  271. }
  272. if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
  273. out.push('<\/', name, '>');
  274. }
  275. break;
  276. case 2: // an attribute
  277. out.push(node.name.toLowerCase(), '="', PR_attribToHtml(node.value), '"');
  278. break;
  279. case 3: case 4: // text
  280. out.push(PR_textToHtml(node.nodeValue));
  281. break;
  282. }
  283. }
  284. /** returns a function that expand tabs to spaces. This function can be fed
  285. * successive chunks of text, and will maintain its own internal state to
  286. * keep track of how tabs are expanded.
  287. * @return {function (plainText : String) : String } a function that takes
  288. * plain text and return the text with tabs expanded.
  289. * @private
  290. */
  291. function PR_tabExpander(tabWidth) {
  292. var SPACES = ' ';
  293. var charInLine = 0;
  294. return function (plainText) {
  295. // walk over each character looking for tabs and newlines.
  296. // On tabs, expand them. On newlines, reset charInLine.
  297. // Otherwise increment charInLine
  298. var out = null;
  299. var pos = 0;
  300. for (var i = 0, n = plainText.length; i < n; ++i) {
  301. var ch = plainText.charAt(i);
  302. switch (ch) {
  303. case '\t':
  304. if (!out) { out = []; }
  305. out.push(plainText.substring(pos, i));
  306. // calculate how much space we need in front of this part
  307. // nSpaces is the amount of padding -- the number of spaces needed to
  308. // move us to the next column, where columns occur at factors of
  309. // tabWidth.
  310. var nSpaces = tabWidth - (charInLine % tabWidth);
  311. charInLine += nSpaces;
  312. for (; nSpaces >= 0; nSpaces -= SPACES.length) {
  313. out.push(SPACES.substring(0, nSpaces));
  314. }
  315. pos = i + 1;
  316. break;
  317. case '\n':
  318. charInLine = 0;
  319. break;
  320. default:
  321. ++charInLine;
  322. }
  323. }
  324. if (!out) { return plainText; }
  325. out.push(plainText.substring(pos));
  326. return out.join('');
  327. };
  328. }
  329. // The below pattern matches one of the following
  330. // (1) /[^<]+/ : A run of characters other than '<'
  331. // (2) /<!--.*?-->/: an HTML comment
  332. // (3) /<!\[CDATA\[.*?\]\]>/: a cdata section
  333. // (3) /<\/?[a-zA-Z][^>]*>/ : A probably tag that should not be highlighted
  334. // (4) /</ : A '<' that does not begin a larger chunk. Treated as 1
  335. var pr_chunkPattern =
  336. /(?:[^<]+|<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g;
  337. var pr_commentPrefix = /^<!--/;
  338. var pr_cdataPrefix = /^<\[CDATA\[/;
  339. var pr_brPrefix = /^<br\b/i;
  340. /** split markup into chunks of html tags (style null) and
  341. * plain text (style {@link #PR_PLAIN}), converting tags which are significant
  342. * for tokenization (<br>) into their textual equivalent.
  343. *
  344. * @param {String} s html where whitespace is considered significant.
  345. * @return {Object} source code and extracted tags.
  346. * @private
  347. */
  348. function PR_extractTags(s) {
  349. // since the pattern has the 'g' modifier and defines no capturing groups,
  350. // this will return a list of all chunks which we then classify and wrap as
  351. // PR_Tokens
  352. var matches = s.match(pr_chunkPattern);
  353. var sourceBuf = [];
  354. var sourceBufLen = 0;
  355. var extractedTags = [];
  356. if (matches) {
  357. for (var i = 0, n = matches.length; i < n; ++i) {
  358. var match = matches[i];
  359. if (match.length > 1 && match.charAt(0) === '<') {
  360. if (pr_commentPrefix.test(match)) { continue; }
  361. if (pr_cdataPrefix.test(match)) {
  362. // strip CDATA prefix and suffix. Don't unescape since it's CDATA
  363. sourceBuf.push(match.substring(9, match.length - 3));
  364. sourceBufLen += match.length - 12;
  365. } else if (pr_brPrefix.test(match)) {
  366. // <br> tags are lexically significant so convert them to text.
  367. // This is undone later.
  368. // <br> tags are lexically significant
  369. sourceBuf.push('\n');
  370. sourceBufLen += 1;
  371. } else {
  372. extractedTags.push(sourceBufLen, match);
  373. }
  374. } else {
  375. var literalText = PR_htmlToText(match);
  376. sourceBuf.push(literalText);
  377. sourceBufLen += literalText.length;
  378. }
  379. }
  380. }
  381. return { source: sourceBuf.join(''), tags: extractedTags };
  382. }
  383. /** Given triples of [style, pattern, context] returns a lexing function,
  384. * The lexing function interprets the patterns to find token boundaries and
  385. * returns a decoration list of the form
  386. * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
  387. * where index_n is an index into the sourceCode, and style_n is a style
  388. * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
  389. * all characters in sourceCode[index_n-1:index_n].
  390. *
  391. * The stylePatterns is a list whose elements have the form
  392. * [style : String, pattern : RegExp, context : RegExp, shortcut : String].
  393. &
  394. * Style is a style constant like PR_PLAIN.
  395. *
  396. * Pattern must only match prefixes, and if it matches a prefix and context is
  397. * null or matches the last non-comment token parsed, then that match is
  398. * considered a token with the same style.
  399. *
  400. * Context is applied to the last non-whitespace, non-comment token recognized.
  401. *
  402. * Shortcut is an optional string of characters, any of which, if the first
  403. * character, gurantee that this pattern and only this pattern matches.
  404. *
  405. * @param {Array} shortcutStylePatterns patterns that always start with
  406. * a known character. Must have a shortcut string.
  407. * @param {Array} fallthroughStylePatterns patterns that will be tried in order
  408. * if the shortcut ones fail. May have shortcuts.
  409. *
  410. * @return {function (sourceCode : String) -> Array.<Number|String>} a function
  411. * that takes source code and a list of decorations to append to.
  412. */
  413. function PR_createSimpleLexer(shortcutStylePatterns,
  414. fallthroughStylePatterns) {
  415. var shortcuts = {};
  416. (function () {
  417. var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
  418. for (var i = allPatterns.length; --i >= 0;) {
  419. var patternParts = allPatterns[i];
  420. var shortcutChars = patternParts[3];
  421. if (shortcutChars) {
  422. for (var c = shortcutChars.length; --c >= 0;) {
  423. shortcuts[shortcutChars.charAt(c)] = patternParts;
  424. }
  425. }
  426. }
  427. })();
  428. var nPatterns = fallthroughStylePatterns.length;
  429. return function (sourceCode, opt_basePos) {
  430. opt_basePos = opt_basePos || 0;
  431. var decorations = [opt_basePos, PR_PLAIN];
  432. var lastToken = '';
  433. var pos = 0; // index into sourceCode
  434. var tail = sourceCode;
  435. while (tail.length) {
  436. var style;
  437. var token = null;
  438. var patternParts = shortcuts[tail.charAt(0)];
  439. if (patternParts) {
  440. var match = tail.match(patternParts[1]);
  441. token = match[0];
  442. style = patternParts[0];
  443. } else {
  444. for (var i = 0; i < nPatterns; ++i) {
  445. patternParts = fallthroughStylePatterns[i];
  446. var contextPattern = patternParts[2];
  447. if (contextPattern && !contextPattern.test(lastToken)) {
  448. // rule can't be used
  449. continue;
  450. }
  451. var match = tail.match(patternParts[1]);
  452. if (match) {
  453. token = match[0];
  454. style = patternParts[0];
  455. break;
  456. }
  457. }
  458. if (!token) { // make sure that we make progress
  459. style = PR_PLAIN;
  460. token = tail.substring(0, 1);
  461. }
  462. }
  463. decorations.push(opt_basePos + pos, style);
  464. pos += token.length;
  465. tail = tail.substring(token.length);
  466. if (style !== PR_COMMENT && /\S/.test(token)) { lastToken = token; }
  467. }
  468. return decorations;
  469. };
  470. }
  471. var PR_C_STYLE_STRING_AND_COMMENT_LEXER = PR_createSimpleLexer([
  472. [PR_STRING, /^\'(?:[^\\\']|\\[\s\S])*(?:\'|$)/, null, "'"],
  473. [PR_STRING, /^\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)/, null, '"'],
  474. [PR_STRING, /^\`(?:[^\\\`]|\\[\s\S])*(?:\`|$)/, null, '`']
  475. ], [
  476. [PR_PLAIN, /^(?:[^\'\"\`\/\#]+)/, null, ' \r\n'],
  477. [PR_COMMENT, /^#[^\r\n]*/, null, '#'],
  478. [PR_COMMENT, /^\/\/[^\r\n]*/, null],
  479. [PR_STRING, /^\/(?:[^\\\*\/]|\\[\s\S])+(?:\/|$)/, REGEXP_PRECEDER_PATTERN],
  480. [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]
  481. ]);
  482. /** splits the given string into comment, string, and "other" tokens.
  483. * @param {String} sourceCode as plain text
  484. * @return {Array.<Number|String>} a decoration list.
  485. * @private
  486. */
  487. function PR_splitStringAndCommentTokens(sourceCode) {
  488. return PR_C_STYLE_STRING_AND_COMMENT_LEXER(sourceCode);
  489. }
  490. var PR_C_STYLE_LITERAL_IDENTIFIER_PUNC_RECOGNIZER = PR_createSimpleLexer([], [
  491. [PR_PLAIN, /^\s+/, null, ' \r\n'],
  492. // TODO(mikesamuel): recognize non-latin letters and numerals in identifiers
  493. [PR_PLAIN, /^[a-z_$@][a-z_$@0-9]*/i, null],
  494. // A hex number
  495. [PR_LITERAL, /^0x[a-f0-9]+[a-z]/i, null],
  496. // An octal or decimal number, possibly in scientific notation
  497. [PR_LITERAL, /^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?[a-z]*/i,
  498. null, '123456789'],
  499. [PR_PUNCTUATION, /^[^\s\w\.$@]+/, null]
  500. // Fallback will handle decimal points not adjacent to a digit
  501. ]);
  502. /** splits plain text tokens into more specific tokens, and then tries to
  503. * recognize keywords, and types.
  504. * @private
  505. */
  506. function PR_splitNonStringNonCommentTokens(source, decorations) {
  507. for (var i = 0; i < decorations.length; i += 2) {
  508. var style = decorations[i + 1];
  509. if (style === PR_PLAIN) {
  510. var start = decorations[i];
  511. var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
  512. var chunk = source.substring(start, end);
  513. var subDecs = PR_C_STYLE_LITERAL_IDENTIFIER_PUNC_RECOGNIZER(chunk, start);
  514. for (var j = 0, m = subDecs.length; j < m; j += 2) {
  515. var subStyle = subDecs[j + 1];
  516. if (subStyle === PR_PLAIN) {
  517. var subStart = subDecs[j];
  518. var subEnd = j + 2 < m ? subDecs[j + 2] : chunk.length;
  519. var token = source.substring(subStart, subEnd);
  520. if (token == '.') {
  521. subDecs[j + 1] = PR_PUNCTUATION;
  522. } else if (token in PR_keywords) {
  523. subDecs[j + 1] = PR_KEYWORD;
  524. } else if (/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(token)) {
  525. // classify types and annotations using Java's style conventions
  526. subDecs[j + 1] = token.charAt(0) == '@' ? PR_LITERAL : PR_TYPE;
  527. }
  528. }
  529. }
  530. PR_spliceArrayInto(subDecs, decorations, i, 2);
  531. i += subDecs.length - 2;
  532. }
  533. }
  534. return decorations;
  535. }
  536. var PR_MARKUP_LEXER = PR_createSimpleLexer([], [
  537. [PR_PLAIN, /^[^<]+/, null],
  538. [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/, null],
  539. [PR_COMMENT, /^<!--[\s\S]*?(?:-->|$)/, null],
  540. [PR_SOURCE, /^<\?[\s\S]*?(?:\?>|$)/, null],
  541. [PR_SOURCE, /^<%[\s\S]*?(?:%>|$)/, null],
  542. [PR_SOURCE,
  543. // Tags whose content is not escaped, and which contain source code.
  544. /^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i, null],
  545. [PR_TAG, /^<\/?\w[^<>]*>/, null]
  546. ]);
  547. // Splits any of the source|style|xmp entries above into a start tag,
  548. // source content, and end tag.
  549. var PR_SOURCE_CHUNK_PARTS = /^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/;
  550. /** split markup on tags, comments, application directives, and other top level
  551. * constructs. Tags are returned as a single token - attributes are not yet
  552. * broken out.
  553. * @private
  554. */
  555. function PR_tokenizeMarkup(source) {
  556. var decorations = PR_MARKUP_LEXER(source);
  557. for (var i = 0; i < decorations.length; i += 2) {
  558. if (decorations[i + 1] === PR_SOURCE) {
  559. var start = decorations[i];
  560. var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
  561. // Split out start and end script tags as actual tags, and leave the body
  562. // with style SCRIPT.
  563. var sourceChunk = source.substring(start, end);
  564. var match = (sourceChunk.match(PR_SOURCE_CHUNK_PARTS)
  565. //|| sourceChunk.match(/^(<[?%])([\s\S]*)([?%]>)$/)
  566. );
  567. if (match) {
  568. decorations.splice(
  569. i, 2,
  570. start, PR_TAG, // the open chunk
  571. start + match[1].length, PR_SOURCE,
  572. start + match[1].length + (match[2] || '').length, PR_TAG);
  573. }
  574. }
  575. }
  576. return decorations;
  577. }
  578. var PR_TAG_LEXER = PR_createSimpleLexer([
  579. [PR_ATTRIB_VALUE, /^\'[^\']*(?:\'|$)/, null, "'"],
  580. [PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'],
  581. [PR_PUNCTUATION, /^[<>\/=]+/, null, '<>/=']
  582. ], [
  583. [PR_TAG, /^[\w-]+/, /^</],
  584. [PR_ATTRIB_VALUE, /^[\w-]+/, /^=/],
  585. [PR_ATTRIB_NAME, /^[\w-]+/, null],
  586. [PR_PLAIN, /^\s+/, null, ' \r\n']
  587. ]);
  588. /** split tags attributes and their values out from the tag name, and
  589. * recursively lex source chunks.
  590. * @private
  591. */
  592. function PR_splitTagAttributes(source, decorations) {
  593. for (var i = 0; i < decorations.length; i += 2) {
  594. var style = decorations[i + 1];
  595. if (style === PR_TAG) {
  596. var start = decorations[i];
  597. var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
  598. var chunk = source.substring(start, end);
  599. var subDecorations = PR_TAG_LEXER(chunk, start);
  600. PR_spliceArrayInto(subDecorations, decorations, i, 2);
  601. i += subDecorations.length - 2;
  602. }
  603. }
  604. return decorations;
  605. }
  606. /** identify regions of markup that are really source code, and recursivley
  607. * lex them.
  608. * @private
  609. */
  610. function PR_splitSourceNodes(source, decorations) {
  611. for (var i = 0; i < decorations.length; i += 2) {
  612. var style = decorations[i + 1];
  613. if (style == PR_SOURCE) {
  614. // Recurse using the non-markup lexer
  615. var start = decorations[i];
  616. var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
  617. var subDecorations = PR_decorateSource(source.substring(start, end));
  618. for (var j = 0, m = subDecorations.length; j < m; j += 2) {
  619. subDecorations[j] += start;
  620. }
  621. PR_spliceArrayInto(subDecorations, decorations, i, 2);
  622. i += subDecorations.length - 2;
  623. }
  624. }
  625. return decorations;
  626. }
  627. /** identify attribute values that really contain source code and recursively
  628. * lex them.
  629. * @private
  630. */
  631. function PR_splitSourceAttributes(source, decorations) {
  632. var nextValueIsSource = false;
  633. for (var i = 0; i < decorations.length; i += 2) {
  634. var style = decorations[i + 1];
  635. if (style === PR_ATTRIB_NAME) {
  636. var start = decorations[i];
  637. var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
  638. nextValueIsSource = /^on|^style$/i.test(source.substring(start, end));
  639. } else if (style == PR_ATTRIB_VALUE) {
  640. if (nextValueIsSource) {
  641. var start = decorations[i];
  642. var end
  643. = i + 2 < decorations.length ? decorations[i + 2] : source.length;
  644. var attribValue = source.substring(start, end);
  645. var attribLen = attribValue.length;
  646. var quoted =
  647. (attribLen >= 2 && /^[\"\']/.test(attribValue) &&
  648. attribValue.charAt(0) === attribValue.charAt(attribLen - 1));
  649. var attribSource;
  650. var attribSourceStart;
  651. var attribSourceEnd;
  652. if (quoted) {
  653. attribSourceStart = start + 1;
  654. attribSourceEnd = end - 1;
  655. attribSource = attribValue;
  656. } else {
  657. attribSourceStart = start + 1;
  658. attribSourceEnd = end - 1;
  659. attribSource = attribValue.substring(1, attribValue.length - 1);
  660. }
  661. var attribSourceDecorations = PR_decorateSource(attribSource);
  662. for (var j = 0, m = attribSourceDecorations.length; j < m; j += 2) {
  663. attribSourceDecorations[j] += attribSourceStart;
  664. }
  665. if (quoted) {
  666. attribSourceDecorations.push(attribSourceEnd, PR_ATTRIB_VALUE);
  667. PR_spliceArrayInto(attribSourceDecorations, decorations, i + 2, 0);
  668. } else {
  669. PR_spliceArrayInto(attribSourceDecorations, decorations, i, 2);
  670. }
  671. }
  672. nextValueIsSource = false;
  673. }
  674. }
  675. return decorations;
  676. }
  677. /** returns a list of decorations, where even entries
  678. *
  679. * This code treats ", ', and ` as string delimiters, and \ as a string escape.
  680. * It does not recognize perl's qq() style strings. It has no special handling
  681. * for double delimiter escapes as in basic, or tje tripled delimiters used in
  682. * python, but should work on those regardless although in those cases a single
  683. * string literal may be broken up into multiple adjacent string literals.
  684. *
  685. * It recognizes C, C++, and shell style comments.
  686. *
  687. * @param {String} sourceCode as plain text
  688. * @return {Array.<String,Number>} a decoration list
  689. */
  690. function PR_decorateSource(sourceCode) {
  691. // Split into strings, comments, and other.
  692. // We do this because strings and comments are easily recognizable and can
  693. // contain stuff that looks like other tokens, so we want to mark those early
  694. // so we don't recurse into them.
  695. var decorations = PR_splitStringAndCommentTokens(sourceCode);
  696. // Split non comment|string tokens on whitespace and word boundaries
  697. decorations = PR_splitNonStringNonCommentTokens(sourceCode, decorations);
  698. return decorations;
  699. }
  700. /** returns a decoration list given a string of markup.
  701. *
  702. * This code recognizes a number of constructs.
  703. * <!-- ... --> comment
  704. * <!\w ... > declaration
  705. * <\w ... > tag
  706. * </\w ... > tag
  707. * <?...?> embedded source
  708. * <%...%> embedded source
  709. * &[#\w]...; entity
  710. *
  711. * It does not recognizes %foo; doctype entities from .
  712. *
  713. * It will recurse into any <style>, <script>, and on* attributes using
  714. * PR_lexSource.
  715. */
  716. function PR_decorateMarkup(sourceCode) {
  717. // This function works as follows:
  718. // 1) Start by splitting the markup into text and tag chunks
  719. // Input: String s
  720. // Output: List<PR_Token> where style in (PR_PLAIN, null)
  721. // 2) Then split the text chunks further into comments, declarations,
  722. // tags, etc.
  723. // After each split, consider whether the token is the start of an
  724. // embedded source section, i.e. is an open <script> tag. If it is,
  725. // find the corresponding close token, and don't bother to lex in between.
  726. // Input: List<String>
  727. // Output: List<PR_Token> with style in (PR_TAG, PR_PLAIN, PR_SOURCE, null)
  728. // 3) Finally go over each tag token and split out attribute names and values.
  729. // Input: List<PR_Token>
  730. // Output: List<PR_Token> where style in
  731. // (PR_TAG, PR_PLAIN, PR_SOURCE, NAME, VALUE, null)
  732. var decorations = PR_tokenizeMarkup(sourceCode);
  733. decorations = PR_splitTagAttributes(sourceCode, decorations);
  734. decorations = PR_splitSourceNodes(sourceCode, decorations);
  735. decorations = PR_splitSourceAttributes(sourceCode, decorations);
  736. return decorations;
  737. }
  738. /**
  739. * @param {String} sourceText plain text
  740. * @param {Array.<Number|String>} extractedTags chunks of raw html preceded by
  741. * their position in sourceText in order.
  742. * @param {Array.<Number|String> decorations style classes preceded by their
  743. * position in sourceText in order.
  744. * @return {String} html
  745. * @private
  746. */
  747. function PR_recombineTagsAndDecorations(
  748. sourceText, extractedTags, decorations) {
  749. var html = [];
  750. var outputIdx = 0; // index past the last char in sourceText written to html
  751. var openDecoration = null;
  752. var currentDecoration = null;
  753. var tagPos = 0; // index into extractedTags
  754. var decPos = 0; // index into decorations
  755. var tabExpander = PR_tabExpander(PR_TAB_WIDTH);
  756. // A helper function that is responsible for opening sections of decoration
  757. // and outputing properly escaped chunks of source
  758. function emitTextUpTo(sourceIdx) {
  759. if (sourceIdx > outputIdx) {
  760. if (openDecoration && openDecoration !== currentDecoration) {
  761. // Close the current decoration
  762. html.push('</span>');
  763. openDecoration = null;
  764. }
  765. if (!openDecoration && currentDecoration) {
  766. openDecoration = currentDecoration;
  767. html.push('<span class="', openDecoration, '">');
  768. }
  769. // This interacts badly with some wikis which introduces paragraph tags
  770. // into pre blocks for some strange reason.
  771. // It's necessary for IE though which seems to lose the preformattednes
  772. // of <pre> tags when their innerHTML is assigned.
  773. // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
  774. // and it serves to undo the conversion of <br>s to newlines done in
  775. // chunkify.
  776. var htmlChunk = PR_textToHtml(
  777. tabExpander(sourceText.substring(outputIdx, sourceIdx)))
  778. .replace(/(\r\n?|\n| ) /g, '$1&nbsp;')
  779. .replace(/\r\n?|\n/g, '<br>');
  780. html.push(htmlChunk);
  781. outputIdx = sourceIdx;
  782. }
  783. }
  784. while (true) {
  785. // Determine if we're going to consume a tag this time around. Otherwise we
  786. // consume a decoration or exit.
  787. var outputTag;
  788. if (tagPos < extractedTags.length) {
  789. if (decPos < decorations.length) {
  790. // Pick one giving preference to extractedTags since we shouldn't open
  791. // a new style that we're going to have to immediately close in order
  792. // to output a tag.
  793. outputTag = extractedTags[tagPos] <= decorations[decPos];
  794. } else {
  795. outputTag = true;
  796. }
  797. } else {
  798. outputTag = false;
  799. }
  800. // Consume either a decoration or a tag or exit.
  801. if (outputTag) {
  802. emitTextUpTo(extractedTags[tagPos]);
  803. if (openDecoration) {
  804. // Close the current decoration
  805. html.push('</span>');
  806. openDecoration = null;
  807. }
  808. html.push(extractedTags[tagPos + 1]);
  809. tagPos += 2;
  810. } else if (decPos < decorations.length) {
  811. emitTextUpTo(decorations[decPos]);
  812. currentDecoration = decorations[decPos + 1];
  813. decPos += 2;
  814. } else {
  815. break;
  816. }
  817. }
  818. emitTextUpTo(sourceText.length);
  819. if (openDecoration) {
  820. html.push('</span>');
  821. }
  822. return html.join('');
  823. }
  824. /** pretty print a chunk of code.
  825. *
  826. * @param {String} sourceCodeHtml code as html
  827. * @return {String} code as html, but prettier
  828. */
  829. function prettyPrintOne(sourceCodeHtml) {
  830. try {
  831. // Extract tags, and convert the source code to plain text.
  832. var sourceAndExtractedTags = PR_extractTags(sourceCodeHtml);
  833. /** Plain text. @type {String} */
  834. var source = sourceAndExtractedTags.source;
  835. /** Even entries are positions in source in ascending order. Odd entries
  836. * are tags that were extracted at that position.
  837. * @type {Array.<Number|String>}
  838. */
  839. var extractedTags = sourceAndExtractedTags.tags;
  840. // Pick a lexer and apply it.
  841. /** Treat it as markup if the first non whitespace character is a < and the
  842. * last non-whitespace character is a >.
  843. * @type {Boolean}
  844. */
  845. var isMarkup = /^\s*</.test(source) && />\s*$/.test(source);
  846. /** Even entires are positions in source in ascending order. Odd enties are
  847. * style markers (e.g., PR_COMMENT) that run from that position until the
  848. * end.
  849. * @type {Array.<Number|String>}
  850. */
  851. var decorations = isMarkup
  852. ? PR_decorateMarkup(source)
  853. : PR_decorateSource(source);
  854. // Integrate the decorations and tags back into the source code to produce
  855. // a decorated html string.
  856. return PR_recombineTagsAndDecorations(source, extractedTags, decorations);
  857. } catch (e) {
  858. if ('console' in window) {
  859. console.log(e);
  860. console.trace();
  861. }
  862. return sourceCodeHtml;
  863. }
  864. }
  865. var PR_SHOULD_USE_CONTINUATION = true;
  866. /** find all the < pre > and < code > tags in the DOM with class=prettyprint and
  867. * prettify them.
  868. * @param {Function} opt_whenDone if specified, called when the last entry
  869. * has been finished.
  870. */
  871. function prettyPrint(opt_whenDone) {
  872. // fetch a list of nodes to rewrite
  873. var codeSegments = [
  874. document.getElementsByTagName('pre'),
  875. document.getElementsByTagName('code'),
  876. document.getElementsByTagName('xmp') ];
  877. var elements = [];
  878. for (var i = 0; i < codeSegments.length; ++i) {
  879. for (var j = 0; j < codeSegments[i].length; ++j) {
  880. elements.push(codeSegments[i][j]);
  881. }
  882. }
  883. codeSegments = null;
  884. // the loop is broken into a series of continuations to make sure that we
  885. // don't make the browser unresponsive when rewriting a large page.
  886. var k = 0;
  887. function doWork() {
  888. var endTime = (PR_SHOULD_USE_CONTINUATION
  889. ? new Date().getTime() + 250
  890. : Infinity);
  891. for (; k < elements.length && new Date().getTime() < endTime; k++) {
  892. var cs = elements[k];
  893. if (cs.className && cs.className.indexOf('prettyprint') >= 0 || true) {
  894. // make sure this is not nested in an already prettified element
  895. var nested = false;
  896. for (var p = cs.parentNode; p != null; p = p.parentNode) {
  897. if ((p.tagName == 'pre' || p.tagName == 'code' ||
  898. p.tagName == 'xmp') &&
  899. (p.className && p.className.indexOf('prettyprint') >= 0 || true) ) {
  900. nested = true;
  901. break;
  902. }
  903. }
  904. if (!nested) {
  905. // fetch the content as a snippet of properly escaped HTML.
  906. // Firefox adds newlines at the end.
  907. var content = PR_getInnerHtml(cs);
  908. content = content.replace(/(?:\r\n?|\n)$/, '');
  909. // do the pretty printing
  910. var newContent = prettyPrintOne(content);
  911. // push the prettified html back into the tag.
  912. if (!PR_isRawContent(cs)) {
  913. // just replace the old html with the new
  914. cs.innerHTML = newContent;
  915. } else {
  916. // we need to change the tag to a <pre> since <xmp>s do not allow
  917. // embedded tags such as the span tags used to attach styles to
  918. // sections of source code.
  919. var pre = document.createElement('PRE');
  920. for (var i = 0; i < cs.attributes.length; ++i) {
  921. var a = cs.attributes[i];
  922. if (a.specified) {
  923. pre.setAttribute(a.name, a.value);
  924. }
  925. }
  926. pre.innerHTML = newContent;
  927. // remove the old
  928. cs.parentNode.replaceChild(pre, cs);
  929. }
  930. }
  931. }
  932. }
  933. if (k < elements.length) {
  934. // finish up in a continuation
  935. setTimeout(doWork, 250);
  936. } else if (opt_whenDone) {
  937. opt_whenDone();
  938. }
  939. }
  940. doWork();
  941. }