2
// This code comes from the December 2009 release of Google Prettify, which is Copyright � 2006 Google Inc.
3
// Minor modifications are marked with "ND Change" comments.
4
// As part of Natural Docs, this code is licensed under version 3 of the GNU Affero General Public License (AGPL.)
5
// However, it may also be obtained separately under version 2.0 of the Apache License.
6
// Refer to License.txt for the complete details
10
// ____________________________________________________________________________
12
// Copyright (C) 2006 Google Inc.
14
// Licensed under the Apache License, Version 2.0 (the "License");
15
// you may not use this file except in compliance with the License.
16
// You may obtain a copy of the License at
18
// http://www.apache.org/licenses/LICENSE-2.0
20
// Unless required by applicable law or agreed to in writing, software
21
// distributed under the License is distributed on an "AS IS" BASIS,
22
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
// See the License for the specific language governing permissions and
24
// limitations under the License.
29
* some functions for browser-side pretty printing of code contained in html.
32
* For a fairly comprehensive set of languages see the
33
* <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
34
* file that came with this source. At a minimum, the lexer should work on a
35
* number of languages including C and friends, Java, Python, Bash, SQL, HTML,
36
* XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
37
* and a subset of Perl, but, because of commenting conventions, doesn't work on
38
* Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
41
* <li> include this source file in an html page via
42
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
43
* <li> define style rules. See the example page for examples.
44
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
45
* {@code class=prettyprint.}
46
* You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
47
* printer needs to do more substantial DOM manipulations to support that, so
48
* some css styles may not be preserved.
50
* That's it. I wanted to keep the API as simple as possible, so there's no
51
* need to specify which language the code is in, but if you wish, you can add
52
* another class to the {@code <pre>} or {@code <code>} element to specify the
53
* language, as in {@code <pre class="prettyprint lang-java">}. Any class that
54
* starts with "lang-" followed by a file extension, specifies the file type.
55
* See the "lang-*.js" files in this directory for code that implements
56
* per-language file handlers.
61
* Java annotations (start with "@") are now captured as literals ("lit")
67
// JSLint declarations
68
/*global console, document, navigator, setTimeout, window */
71
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
73
* If set to {@code false}, {@code prettyPrint()} is synchronous.
75
window['PR_SHOULD_USE_CONTINUATION'] = true;
77
/** the number of characters between tab columns */
78
window['PR_TAB_WIDTH'] = 8;
80
/** Walks the DOM returning a properly escaped version of innerHTML.
82
* @param {Array.<string>} out output buffer that receives chunks of HTML.
84
window['PR_normalizedHtml']
86
/** Contains functions for creating and registering new language handlers.
91
/** Pretty print a chunk of code.
93
* @param {string} sourceCodeHtml code as html
94
* @return {string} code as html, but prettier
96
= window['prettyPrintOne']
97
/** Find all the {@code <pre>} and {@code <code>} tags in the DOM with
98
* {@code class=prettyprint} and prettify them.
99
* @param {Function?} opt_whenDone if specified, called when the last entry
102
= window['prettyPrint'] = void 0;
104
/** browser detection. @extern @returns false if not IE, otherwise the major version. */
105
window['_pr_isIE6'] = function () {
106
var ieVersion = navigator && navigator.userAgent &&
107
navigator.userAgent.match(/\bMSIE ([678])\./);
108
ieVersion = ieVersion ? +ieVersion[1] : false;
109
window['_pr_isIE6'] = function () { return ieVersion; };
115
// Keyword lists for various languages.
116
var FLOW_CONTROL_KEYWORDS =
117
"break continue do else for if return while ";
118
var C_KEYWORDS = FLOW_CONTROL_KEYWORDS + "auto case char const default " +
119
"double enum extern float goto int long register short signed sizeof " +
120
"static struct switch typedef union unsigned void volatile ";
121
var COMMON_KEYWORDS = C_KEYWORDS + "catch class delete false import " +
122
"new operator private protected public this throw true try typeof ";
123
var CPP_KEYWORDS = COMMON_KEYWORDS + "alignof align_union asm axiom bool " +
124
"concept concept_map const_cast constexpr decltype " +
125
"dynamic_cast explicit export friend inline late_check " +
126
"mutable namespace nullptr reinterpret_cast static_assert static_cast " +
127
"template typeid typename using virtual wchar_t where ";
128
var JAVA_KEYWORDS = COMMON_KEYWORDS +
129
"abstract boolean byte extends final finally implements import " +
130
"instanceof null native package strictfp super synchronized throws " +
132
var CSHARP_KEYWORDS = JAVA_KEYWORDS +
133
"as base by checked decimal delegate descending event " +
134
"fixed foreach from group implicit in interface internal into is lock " +
135
"object out override orderby params partial readonly ref sbyte sealed " +
136
"stackalloc string select uint ulong unchecked unsafe ushort var ";
137
var JSCRIPT_KEYWORDS = COMMON_KEYWORDS +
138
"debugger eval export function get null set undefined var with " +
140
var PERL_KEYWORDS = "caller delete die do dump elsif eval exit foreach for " +
141
"goto if import last local my next no our print package redo require " +
142
"sub undef unless until use wantarray while BEGIN END ";
143
var PYTHON_KEYWORDS = FLOW_CONTROL_KEYWORDS + "and as assert class def del " +
144
"elif except exec finally from global import in is lambda " +
145
"nonlocal not or pass print raise try with yield " +
147
var RUBY_KEYWORDS = FLOW_CONTROL_KEYWORDS + "alias and begin case class def" +
148
" defined elsif end ensure false in module next nil not or redo rescue " +
149
"retry self super then true undef unless until when yield BEGIN END ";
150
var SH_KEYWORDS = FLOW_CONTROL_KEYWORDS + "case done elif esac eval fi " +
151
"function in local set then until ";
153
CPP_KEYWORDS + CSHARP_KEYWORDS + JSCRIPT_KEYWORDS + PERL_KEYWORDS +
154
PYTHON_KEYWORDS + RUBY_KEYWORDS + SH_KEYWORDS);
156
// token style names. correspond to css classes
157
/** token style for a string literal */
158
var PR_STRING = 'str';
159
/** token style for a keyword */
160
var PR_KEYWORD = 'kwd';
161
/** token style for a comment */
162
var PR_COMMENT = 'com';
163
/** token style for a type */
165
/** token style for a literal value. e.g. 1, null, true. */
166
var PR_LITERAL = 'lit';
167
/** token style for a punctuation string. */
168
var PR_PUNCTUATION = 'pun';
169
/** token style for a punctuation string. */
170
var PR_PLAIN = 'pln';
172
/** token style for an sgml tag. */
174
/** token style for a markup declaration such as a DOCTYPE. */
175
var PR_DECLARATION = 'dec';
176
/** token style for embedded source. */
177
var PR_SOURCE = 'src';
178
/** token style for an sgml attribute name. */
179
var PR_ATTRIB_NAME = 'atn';
180
/** token style for an sgml attribute value. */
181
var PR_ATTRIB_VALUE = 'atv';
184
* A class that indicates a section of markup that is not code, e.g. to allow
185
* embedding of line numbers within code listings.
187
var PR_NOCODE = 'nocode';
189
/** A set of tokens that can precede a regular expression literal in
191
* http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full
192
* list, but I've removed ones that might be problematic when seen in
193
* languages that don't support regular expression literals.
195
* <p>Specifically, I've removed any keywords that can't precede a regexp
196
* literal in a syntactically legal javascript program, and I've removed the
197
* "in" keyword since it's not a keyword in many languages, and might be used
198
* as a count of inches.
200
* <p>The link a above does not accurately describe EcmaScript rules since
201
* it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
202
* very well in practice.
206
var REGEXP_PRECEDER_PATTERN = function () {
208
"!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=",
209
"&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=",
210
"->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";",
211
"<", "<<", "<<=", "<=", "=", "==", "===", ">",
212
">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[",
213
"^", "^=", "^^", "^^=", "{", "|", "|=", "||",
214
"||=", "~" /* handles =~ and !~ */,
215
"break", "case", "continue", "delete",
216
"do", "else", "finally", "instanceof",
217
"return", "throw", "try", "typeof"
219
var pattern = '(?:^^|[+-]';
220
for (var i = 0; i < preceders.length; ++i) {
221
pattern += '|' + preceders[i].replace(/([^=<>:&a-z])/g, '\\$1');
223
pattern += ')\\s*'; // matches at end, and matches empty string
225
// CAVEAT: this does not properly handle the case where a regular
226
// expression immediately follows another since a regular expression may
227
// have flags for case-sensitivity and the like. Having regexp tokens
228
// adjacent is not valid in any language I'm aware of, so I'm punting.
229
// TODO: maybe style special characters inside a regexp as punctuation.
232
// Define regexps here so that the interpreter doesn't have to create an
233
// object each time the function containing them is called.
234
// The language spec requires a new object created even if you don't access
240
/** like textToHtml but escapes double quotes to be attribute safe. */
241
function attribToHtml(str) {
242
return str.replace(pr_amp, '&')
243
.replace(pr_lt, '<')
244
.replace(pr_gt, '>')
245
.replace(pr_quot, '"');
248
/** escapest html special characters to html. */
249
function textToHtml(str) {
250
return str.replace(pr_amp, '&')
251
.replace(pr_lt, '<')
252
.replace(pr_gt, '>');
256
var pr_ltEnt = /</g;
257
var pr_gtEnt = />/g;
258
var pr_aposEnt = /'/g;
259
var pr_quotEnt = /"/g;
260
var pr_ampEnt = /&/g;
261
var pr_nbspEnt = / /g;
262
/** unescapes html to plain text. */
263
function htmlToText(html) {
264
var pos = html.indexOf('&');
265
if (pos < 0) { return html; }
266
// Handle numeric entities specially. We can't use functional substitution
267
// since that doesn't work in older versions of Safari.
268
// These should be rare since most browsers convert them to normal chars.
269
for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
270
var end = html.indexOf(';', pos);
272
var num = html.substring(pos + 3, end);
274
if (num && num.charAt(0) === 'x') {
275
num = num.substring(1);
278
var codePoint = parseInt(num, radix);
279
if (!isNaN(codePoint)) {
280
html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
281
html.substring(end + 1));
286
return html.replace(pr_ltEnt, '<')
287
.replace(pr_gtEnt, '>')
288
.replace(pr_aposEnt, "'")
289
.replace(pr_quotEnt, '"')
290
.replace(pr_nbspEnt, ' ')
291
.replace(pr_ampEnt, '&');
294
/** is the given node's innerHTML normally unescaped? */
295
function isRawContent(node) {
296
return 'XMP' === node.tagName;
299
var newlineRe = /[\r\n]/g;
301
* Are newlines and adjacent spaces significant in the given node's innerHTML?
303
function isPreformatted(node, content) {
304
// PRE means preformatted, and is a very common case, so don't create
305
// unnecessary computed style objects.
306
if ('PRE' === node.tagName) { return true; }
307
if (!newlineRe.test(content)) { return true; } // Don't care
309
// For disconnected nodes, IE has no currentStyle.
310
if (node.currentStyle) {
311
whitespace = node.currentStyle.whiteSpace;
312
} else if (window.getComputedStyle) {
313
// Firefox makes a best guess if node is disconnected whereas Safari
314
// returns the empty string.
315
whitespace = window.getComputedStyle(node, null).whiteSpace;
317
return !whitespace || whitespace === 'pre';
320
function normalizedHtml(node, out) {
321
switch (node.nodeType) {
322
case 1: // an element
323
var name = node.tagName.toLowerCase();
325
for (var i = 0; i < node.attributes.length; ++i) {
326
var attr = node.attributes[i];
327
if (!attr.specified) { continue; }
329
normalizedHtml(attr, out);
332
for (var child = node.firstChild; child; child = child.nextSibling) {
333
normalizedHtml(child, out);
335
if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
336
out.push('<\/', name, '>');
339
case 2: // an attribute
340
out.push(node.name.toLowerCase(), '="', attribToHtml(node.value), '"');
342
case 3: case 4: // text
343
out.push(textToHtml(node.nodeValue));
349
* Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
350
* matches the union o the sets o strings matched d by the input RegExp.
351
* Since it matches globally, if the input strings have a start-of-input
352
* anchor (/^.../), it is ignored for the purposes of unioning.
353
* @param {Array.<RegExp>} regexs non multiline, non-global regexs.
354
* @return {RegExp} a global regex.
356
function combinePrefixPatterns(regexs) {
357
var capturedGroupIndex = 0;
359
var needToFoldCase = false;
360
var ignoreCase = false;
361
for (var i = 0, n = regexs.length; i < n; ++i) {
362
var regex = regexs[i];
363
if (regex.ignoreCase) {
365
} else if (/[a-z]/i.test(regex.source.replace(
366
/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
367
needToFoldCase = true;
373
function decodeEscape(charsetPart) {
374
if (charsetPart.charAt(0) !== '\\') { return charsetPart.charCodeAt(0); }
375
switch (charsetPart.charAt(1)) {
378
case 'n': return 0xa;
379
case 'v': return 0xb;
380
case 'f': return 0xc;
381
case 'r': return 0xd;
383
return parseInt(charsetPart.substring(2), 16)
384
|| charsetPart.charCodeAt(1);
385
case '0': case '1': case '2': case '3': case '4':
386
case '5': case '6': case '7':
387
return parseInt(charsetPart.substring(1), 8);
388
default: return charsetPart.charCodeAt(1);
392
function encodeEscape(charCode) {
393
if (charCode < 0x20) {
394
return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
396
var ch = String.fromCharCode(charCode);
397
if (ch === '\\' || ch === '-' || ch === '[' || ch === ']') {
403
function caseFoldCharset(charSet) {
404
var charsetParts = charSet.substring(1, charSet.length - 1).match(
406
'\\\\u[0-9A-Fa-f]{4}'
407
+ '|\\\\x[0-9A-Fa-f]{2}'
408
+ '|\\\\[0-3][0-7]{0,2}'
416
var inverse = charsetParts[0] === '^';
417
for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
418
var p = charsetParts[i];
420
case '\\B': case '\\b':
421
case '\\D': case '\\d':
422
case '\\S': case '\\s':
423
case '\\W': case '\\w':
427
var start = decodeEscape(p);
429
if (i + 2 < n && '-' === charsetParts[i + 1]) {
430
end = decodeEscape(charsetParts[i + 2]);
435
ranges.push([start, end]);
436
// If the range might intersect letters, then expand it.
437
if (!(end < 65 || start > 122)) {
438
if (!(end < 65 || start > 90)) {
439
ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
441
if (!(end < 97 || start > 122)) {
442
ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
447
// [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
448
// -> [[1, 12], [14, 14], [16, 17]]
449
ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
450
var consolidatedRanges = [];
451
var lastRange = [NaN, NaN];
452
for (var i = 0; i < ranges.length; ++i) {
453
var range = ranges[i];
454
if (range[0] <= lastRange[1] + 1) {
455
lastRange[1] = Math.max(lastRange[1], range[1]);
457
consolidatedRanges.push(lastRange = range);
462
if (inverse) { out.push('^'); }
463
out.push.apply(out, groups);
464
for (var i = 0; i < consolidatedRanges.length; ++i) {
465
var range = consolidatedRanges[i];
466
out.push(encodeEscape(range[0]));
467
if (range[1] > range[0]) {
468
if (range[1] + 1 > range[0]) { out.push('-'); }
469
out.push(encodeEscape(range[1]));
476
function allowAnywhereFoldCaseAndRenumberGroups(regex) {
477
// Split into character sets, escape sequences, punctuation strings
478
// like ('(', '(?:', ')', '^'), and runs of characters that do not
479
// include any of the above.
480
var parts = regex.source.match(
483
+ '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
484
+ '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
485
+ '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
486
+ '|\\\\[0-9]+' // a back-reference or octal escape
487
+ '|\\\\[^ux0-9]' // other escape sequence
488
+ '|\\(\\?[:!=]' // start of a non-capturing group
489
+ '|[\\(\\)\\^]' // start/emd of a group, or line start
490
+ '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
493
var n = parts.length;
495
// Maps captured group numbers to the number they will occupy in
496
// the output or to -1 if that has not been determined, or to
497
// undefined if they need not be capturing in the output.
498
var capturedGroups = [];
500
// Walk over and identify back references to build the capturedGroups
502
for (var i = 0, groupIndex = 0; i < n; ++i) {
505
// groups are 1-indexed, so max group index is count of '('
507
} else if ('\\' === p.charAt(0)) {
508
var decimalValue = +p.substring(1);
509
if (decimalValue && decimalValue <= groupIndex) {
510
capturedGroups[decimalValue] = -1;
515
// Renumber groups and reduce capturing groups to non-capturing groups
517
for (var i = 1; i < capturedGroups.length; ++i) {
518
if (-1 === capturedGroups[i]) {
519
capturedGroups[i] = ++capturedGroupIndex;
522
for (var i = 0, groupIndex = 0; i < n; ++i) {
526
if (capturedGroups[groupIndex] === undefined) {
529
} else if ('\\' === p.charAt(0)) {
530
var decimalValue = +p.substring(1);
531
if (decimalValue && decimalValue <= groupIndex) {
532
parts[i] = '\\' + capturedGroups[groupIndex];
537
// Remove any prefix anchors so that the output will match anywhere.
538
// ^^ really does mean an anchored match though.
539
for (var i = 0, groupIndex = 0; i < n; ++i) {
540
if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
543
// Expand letters to groupts to handle mixing of case-sensitive and
544
// case-insensitive patterns if necessary.
545
if (regex.ignoreCase && needToFoldCase) {
546
for (var i = 0; i < n; ++i) {
548
var ch0 = p.charAt(0);
549
if (p.length >= 2 && ch0 === '[') {
550
parts[i] = caseFoldCharset(p);
551
} else if (ch0 !== '\\') {
552
// TODO: handle letters in numeric escapes.
553
parts[i] = p.replace(
556
var cc = ch.charCodeAt(0);
557
return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
563
return parts.join('');
567
for (var i = 0, n = regexs.length; i < n; ++i) {
568
var regex = regexs[i];
569
if (regex.global || regex.multiline) { throw new Error('' + regex); }
571
'(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
574
return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
577
var PR_innerHtmlWorks = null;
578
function getInnerHtml(node) {
579
// inner html is hopelessly broken in Safari 2.0.4 when the content is
580
// an html description of well formed XML and the containing tag is a PRE
581
// tag, so we detect that case and emulate innerHTML.
582
if (null === PR_innerHtmlWorks) {
583
var testNode = document.createElement('PRE');
584
testNode.appendChild(
585
document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
586
PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
589
if (PR_innerHtmlWorks) {
590
var content = node.innerHTML;
591
// XMP tags contain unescaped entities so require special handling.
592
if (isRawContent(node)) {
593
content = textToHtml(content);
594
} else if (!isPreformatted(node, content)) {
595
content = content.replace(/(<br\s*\/?>)[\r\n]+/g, '$1')
596
.replace(/(?:[\r\n]+[ \t]*)+/g, ' ');
602
for (var child = node.firstChild; child; child = child.nextSibling) {
603
normalizedHtml(child, out);
608
/** returns a function that expand tabs to spaces. This function can be fed
609
* successive chunks of text, and will maintain its own internal state to
610
* keep track of how tabs are expanded.
611
* @return {function (string) : string} a function that takes
612
* plain text and return the text with tabs expanded.
615
function makeTabExpander(tabWidth) {
619
return function (plainText) {
620
// walk over each character looking for tabs and newlines.
621
// On tabs, expand them. On newlines, reset charInLine.
622
// Otherwise increment charInLine
625
for (var i = 0, n = plainText.length; i < n; ++i) {
626
var ch = plainText.charAt(i);
630
if (!out) { out = []; }
631
out.push(plainText.substring(pos, i));
632
// calculate how much space we need in front of this part
633
// nSpaces is the amount of padding -- the number of spaces needed
634
// to move us to the next column, where columns occur at factors of
636
var nSpaces = tabWidth - (charInLine % tabWidth);
637
charInLine += nSpaces;
638
for (; nSpaces >= 0; nSpaces -= SPACES.length) {
639
out.push(SPACES.substring(0, nSpaces));
650
if (!out) { return plainText; }
651
out.push(plainText.substring(pos));
656
var pr_chunkPattern = new RegExp(
657
'[^<]+' // A run of characters other than '<'
658
+ '|<\!--[\\s\\S]*?--\>' // an HTML comment
659
+ '|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>' // a CDATA section
660
// a probable tag that should not be highlighted
661
+ '|<\/?[a-zA-Z](?:[^>\"\']|\'[^\']*\'|\"[^\"]*\")*>'
662
+ '|<', // A '<' that does not begin a larger chunk
664
var pr_commentPrefix = /^<\!--/;
665
var pr_cdataPrefix = /^<!\[CDATA\[/;
666
var pr_brPrefix = /^<br\b/i;
667
var pr_tagNameRe = /^<(\/?)([a-zA-Z][a-zA-Z0-9]*)/;
669
/** split markup into chunks of html tags (style null) and
670
* plain text (style {@link #PR_PLAIN}), converting tags which are
671
* significant for tokenization (<br>) into their textual equivalent.
673
* @param {string} s html where whitespace is considered significant.
674
* @return {Object} source code and extracted tags.
677
function extractTags(s) {
678
// since the pattern has the 'g' modifier and defines no capturing groups,
679
// this will return a list of all chunks which we then classify and wrap as
681
var matches = s.match(pr_chunkPattern);
683
var sourceBufLen = 0;
684
var extractedTags = [];
686
for (var i = 0, n = matches.length; i < n; ++i) {
687
var match = matches[i];
688
if (match.length > 1 && match.charAt(0) === '<') {
689
if (pr_commentPrefix.test(match)) { continue; }
690
if (pr_cdataPrefix.test(match)) {
691
// strip CDATA prefix and suffix. Don't unescape since it's CDATA
692
sourceBuf.push(match.substring(9, match.length - 3));
693
sourceBufLen += match.length - 12;
694
} else if (pr_brPrefix.test(match)) {
695
// <br> tags are lexically significant so convert them to text.
696
// This is undone later.
697
sourceBuf.push('\n');
700
if (match.indexOf(PR_NOCODE) >= 0 && isNoCodeTag(match)) {
701
// A <span class="nocode"> will start a section that should be
702
// ignored. Continue walking the list until we see a matching end
704
var name = match.match(pr_tagNameRe)[2];
708
for (j = i + 1; j < n; ++j) {
709
var name2 = matches[j].match(pr_tagNameRe);
710
if (name2 && name2[2] === name) {
711
if (name2[1] === '/') {
712
if (--depth === 0) { break end_tag_loop; }
720
sourceBufLen, matches.slice(i, j + 1).join(''));
722
} else { // Ignore unclosed sections.
723
extractedTags.push(sourceBufLen, match);
726
extractedTags.push(sourceBufLen, match);
730
var literalText = htmlToText(match);
731
sourceBuf.push(literalText);
732
sourceBufLen += literalText.length;
736
return { source: sourceBuf.join(''), tags: extractedTags };
739
/** True if the given tag contains a class attribute with the nocode class. */
740
function isNoCodeTag(tag) {
742
// First canonicalize the representation of attributes
743
.replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g,
745
// Then look for the attribute we want.
746
.match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/);
750
* Apply the given language handler to sourceCode and add the resulting
751
* decorations to out.
752
* @param {number} basePos the index of sourceCode within the chunk of source
753
* whose decorations are already present on out.
755
function appendDecorations(basePos, sourceCode, langHandler, out) {
756
if (!sourceCode) { return; }
762
out.push.apply(out, job.decorations);
765
/** Given triples of [style, pattern, context] returns a lexing function,
766
* The lexing function interprets the patterns to find token boundaries and
767
* returns a decoration list of the form
768
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
769
* where index_n is an index into the sourceCode, and style_n is a style
770
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
771
* all characters in sourceCode[index_n-1:index_n].
773
* The stylePatterns is a list whose elements have the form
774
* [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
776
* Style is a style constant like PR_PLAIN, or can be a string of the
777
* form 'lang-FOO', where FOO is a language extension describing the
778
* language of the portion of the token in $1 after pattern executes.
779
* E.g., if style is 'lang-lisp', and group 1 contains the text
780
* '(hello (world))', then that portion of the token will be passed to the
781
* registered lisp handler for formatting.
782
* The text before and after group 1 will be restyled using this decorator
783
* so decorators should take care that this doesn't result in infinite
784
* recursion. For example, the HTML lexer rule for SCRIPT elements looks
785
* something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
786
* '<script>foo()<\/script>', which would cause the current decorator to
787
* be called with '<script>' which would not match the same rule since
788
* group 1 must not be empty, so it would be instead styled as PR_TAG by
789
* the generic tag rule. The handler registered for the 'js' extension would
790
* then be called with 'foo()', and finally, the current decorator would
791
* be called with '<\/script>' which would not match the original rule and
792
* so the generic tag rule would identify it as a tag.
794
* Pattern must only match prefixes, and if it matches a prefix, then that
795
* match is considered a token with the same style.
797
* Context is applied to the last non-whitespace, non-comment token
800
* Shortcut is an optional string of characters, any of which, if the first
801
* character, gurantee that this pattern and only this pattern matches.
803
* @param {Array} shortcutStylePatterns patterns that always start with
804
* a known character. Must have a shortcut string.
805
* @param {Array} fallthroughStylePatterns patterns that will be tried in
806
* order if the shortcut ones fail. May have shortcuts.
808
* @return {function (Object)} a
809
* function that takes source code and returns a list of decorations.
811
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
815
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
818
for (var i = 0, n = allPatterns.length; i < n; ++i) {
819
var patternParts = allPatterns[i];
820
var shortcutChars = patternParts[3];
822
for (var c = shortcutChars.length; --c >= 0;) {
823
shortcuts[shortcutChars.charAt(c)] = patternParts;
826
var regex = patternParts[1];
828
if (!regexKeys.hasOwnProperty(k)) {
829
allRegexs.push(regex);
833
allRegexs.push(/[\0-\uffff]/);
834
tokenizer = combinePrefixPatterns(allRegexs);
837
var nPatterns = fallthroughStylePatterns.length;
841
* Lexes job.source and produces an output array job.decorations of style
842
* classes preceded by the position at which they start in job.source in
845
* @param {Object} job an object like {@code
846
* source: {string} sourceText plain text,
847
* basePos: {int} position of job.source in the larger chunk of
851
var decorate = function (job) {
852
var sourceCode = job.source, basePos = job.basePos;
853
/** Even entries are positions in source in ascending order. Odd enties
854
* are style markers (e.g., PR_COMMENT) that run from that position until
856
* @type {Array.<number|string>}
858
var decorations = [basePos, PR_PLAIN];
859
var pos = 0; // index into sourceCode
860
var tokens = sourceCode.match(tokenizer) || [];
863
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
864
var token = tokens[ti];
865
var style = styleCache[token];
869
if (typeof style === 'string') {
872
var patternParts = shortcuts[token.charAt(0)];
874
match = token.match(patternParts[1]);
875
style = patternParts[0];
877
for (var i = 0; i < nPatterns; ++i) {
878
patternParts = fallthroughStylePatterns[i];
879
match = token.match(patternParts[1]);
881
style = patternParts[0];
886
if (!match) { // make sure that we make progress
891
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
892
if (isEmbedded && !(match && typeof match[1] === 'string')) {
897
if (!isEmbedded) { styleCache[token] = style; }
900
var tokenStart = pos;
904
decorations.push(basePos + tokenStart, style);
905
} else { // Treat group 1 as an embedded block of source code.
906
var embeddedSource = match[1];
907
var embeddedSourceStart = token.indexOf(embeddedSource);
908
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
910
// If embeddedSource can be blank, then it would match at the
911
// beginning which would cause us to infinitely recurse on the
912
// entire token, so we catch the right context in match[2].
913
embeddedSourceEnd = token.length - match[2].length;
914
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
916
var lang = style.substring(5);
917
// Decorate the left of the embedded source
919
basePos + tokenStart,
920
token.substring(0, embeddedSourceStart),
921
decorate, decorations);
922
// Decorate the embedded source
924
basePos + tokenStart + embeddedSourceStart,
926
langHandlerForExtension(lang, embeddedSource),
928
// Decorate the right of the embedded section
930
basePos + tokenStart + embeddedSourceEnd,
931
token.substring(embeddedSourceEnd),
932
decorate, decorations);
935
job.decorations = decorations;
940
/** returns a function that produces a list of decorations from source text.
942
* This code treats ", ', and ` as string delimiters, and \ as a string
943
* escape. It does not recognize perl's qq() style strings.
944
* It has no special handling for double delimiter escapes as in basic, or
945
* the tripled delimiters used in python, but should work on those regardless
946
* although in those cases a single string literal may be broken up into
947
* multiple adjacent string literals.
949
* It recognizes C, C++, and shell style comments.
951
* @param {Object} options a set of optional parameters.
952
* @return {function (Object)} a function that examines the source code
953
* in the input job and builds the decoration list.
955
function sourceDecorator(options) {
956
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
957
if (options['tripleQuotedStrings']) {
958
// '''multi-line-string''', 'single-line-string', and double-quoted
959
shortcutStylePatterns.push(
960
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
962
} else if (options['multiLineStrings']) {
963
// 'multi-line-string', "multi-line-string"
964
shortcutStylePatterns.push(
965
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
968
// 'single-line-string', "single-line-string"
969
shortcutStylePatterns.push(
971
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
974
if (options['verbatimStrings']) {
975
// verbatim-string-literal production from the C# grammar. See issue 93.
976
fallthroughStylePatterns.push(
977
[PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
979
if (options['hashComments']) {
980
if (options['cStyleComments']) {
981
// Stop C preprocessor declarations at an unclosed open comment
982
shortcutStylePatterns.push(
983
[PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
985
fallthroughStylePatterns.push(
987
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,
990
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
993
if (options['cStyleComments']) {
994
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
995
fallthroughStylePatterns.push(
996
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
998
if (options['regexLiterals']) {
999
var REGEX_LITERAL = (
1000
// A regular expression literal starts with a slash that is
1001
// not followed by * or / so that it is not confused with
1004
// and then contains any number of raw characters,
1005
+ '(?:[^/\\x5B\\x5C]'
1006
// escape sequences (\x5C),
1008
// or non-nesting character sets (\x5B\x5D);
1009
+ '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
1010
// finally closed by a /.
1012
fallthroughStylePatterns.push(
1014
new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
1018
var keywords = options['keywords'].replace(/^\s+|\s+$/g, '');
1019
if (keywords.length) {
1020
fallthroughStylePatterns.push(
1022
new RegExp('^(?:' + keywords.replace(/\s+/g, '|') + ')\\b'), null]);
1025
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
1026
fallthroughStylePatterns.push(
1027
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
1028
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
1029
[PR_TYPE, /^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null],
1030
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
1036
// or an octal or decimal number,
1037
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
1038
// possibly in scientific notation
1039
+ '(?:e[+\\-]?\\d+)?'
1041
// with an optional modifier like UL for unsigned long
1043
null, '0123456789'],
1044
[PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#]*/, null]);
1046
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
1049
var decorateSource = sourceDecorator({
1050
'keywords': ALL_KEYWORDS,
1051
'hashComments': true,
1052
'cStyleComments': true,
1053
'multiLineStrings': true,
1054
'regexLiterals': true
1057
/** Breaks {@code job.source} around style boundaries in
1058
* {@code job.decorations} while re-interleaving {@code job.extractedTags},
1059
* and leaves the result in {@code job.prettyPrintedHtml}.
1060
* @param {Object} job like {
1061
* source: {string} source as plain text,
1062
* extractedTags: {Array.<number|string>} extractedTags chunks of raw
1063
* html preceded by their position in {@code job.source}
1065
* decorations: {Array.<number|string} an array of style classes preceded
1066
* by the position at which they start in job.source in order
1070
function recombineTagsAndDecorations(job) {
1071
var sourceText = job.source;
1072
var extractedTags = job.extractedTags;
1073
var decorations = job.decorations;
1076
// index past the last char in sourceText written to html
1079
var openDecoration = null;
1080
var currentDecoration = null;
1081
var tagPos = 0; // index into extractedTags
1082
var decPos = 0; // index into decorations
1083
var tabExpander = makeTabExpander(window['PR_TAB_WIDTH']);
1085
var adjacentSpaceRe = /([\r\n ]) /g;
1086
var startOrSpaceRe = /(^| ) /gm;
1087
var newlineRe = /\r\n?|\n/g;
1088
var trailingSpaceRe = /[ \r\n]$/;
1089
var lastWasSpace = true; // the last text chunk emitted ended with a space.
1091
// A helper function that is responsible for opening sections of decoration
1092
// and outputing properly escaped chunks of source
1093
function emitTextUpTo(sourceIdx) {
1094
if (sourceIdx > outputIdx) {
1095
if (openDecoration && openDecoration !== currentDecoration) {
1096
// Close the current decoration
1097
html.push('</span>');
1098
openDecoration = null;
1100
if (!openDecoration && currentDecoration) {
1101
openDecoration = currentDecoration;
1102
html.push('<span class="', openDecoration, '">');
1104
// This interacts badly with some wikis which introduces paragraph tags
1105
// into pre blocks for some strange reason.
1106
// It's necessary for IE though which seems to lose the preformattedness
1107
// of <pre> tags when their innerHTML is assigned.
1108
// http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
1109
// and it serves to undo the conversion of <br>s to newlines done in
1111
var htmlChunk = textToHtml(
1112
tabExpander(sourceText.substring(outputIdx, sourceIdx)))
1113
.replace(lastWasSpace
1115
: adjacentSpaceRe, '$1 ');
1116
// Keep track of whether we need to escape space at the beginning of the
1118
lastWasSpace = trailingSpaceRe.test(htmlChunk);
1119
// IE collapses multiple adjacient <br>s into 1 line break.
1120
// Prefix every <br> with ' ' can prevent such IE's behavior.
1121
var lineBreakHtml = window['_pr_isIE6']() ? ' <br />' : '<br />';
1122
html.push(htmlChunk.replace(newlineRe, lineBreakHtml));
1123
outputIdx = sourceIdx;
1128
// Determine if we're going to consume a tag this time around. Otherwise
1129
// we consume a decoration or exit.
1131
if (tagPos < extractedTags.length) {
1132
if (decPos < decorations.length) {
1133
// Pick one giving preference to extractedTags since we shouldn't open
1134
// a new style that we're going to have to immediately close in order
1136
outputTag = extractedTags[tagPos] <= decorations[decPos];
1143
// Consume either a decoration or a tag or exit.
1145
emitTextUpTo(extractedTags[tagPos]);
1146
if (openDecoration) {
1147
// Close the current decoration
1148
html.push('</span>');
1149
openDecoration = null;
1151
html.push(extractedTags[tagPos + 1]);
1153
} else if (decPos < decorations.length) {
1154
emitTextUpTo(decorations[decPos]);
1155
currentDecoration = decorations[decPos + 1];
1161
emitTextUpTo(sourceText.length);
1162
if (openDecoration) {
1163
html.push('</span>');
1165
job.prettyPrintedHtml = html.join('');
1168
/** Maps language-specific file extensions to handlers. */
1169
var langHandlerRegistry = {};
1170
/** Register a language handler for the given file extensions.
1171
* @param {function (Object)} handler a function from source code to a list
1172
* of decorations. Takes a single argument job which describes the
1173
* state of the computation. The single parameter has the form
1175
* source: {string} as plain text.
1176
* decorations: {Array.<number|string>} an array of style classes
1177
* preceded by the position at which they start in
1178
* job.source in order.
1179
* The language handler should assigned this field.
1180
* basePos: {int} the position of source in the larger source chunk.
1181
* All positions in the output decorations array are relative
1182
* to the larger source chunk.
1184
* @param {Array.<string>} fileExtensions
1186
function registerLangHandler(handler, fileExtensions) {
1187
for (var i = fileExtensions.length; --i >= 0;) {
1188
var ext = fileExtensions[i];
1189
if (!langHandlerRegistry.hasOwnProperty(ext)) {
1190
langHandlerRegistry[ext] = handler;
1191
} else if ('console' in window) {
1192
console.warn('cannot override language handler %s', ext);
1196
function langHandlerForExtension(extension, source) {
1197
if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
1198
// Treat it as markup if the first non whitespace character is a < and
1199
// the last non-whitespace character is a >.
1200
extension = /^\s*</.test(source)
1204
return langHandlerRegistry[extension];
1206
registerLangHandler(decorateSource, ['default-code']);
1207
registerLangHandler(
1211
[PR_PLAIN, /^[^<?]+/],
1212
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
1213
[PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
1214
// Unescaped content in an unknown language
1215
['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
1216
['lang-', /^<%([\s\S]+?)(?:%>|$)/],
1217
[PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
1218
['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
1219
// Unescaped content in javascript. (Or possibly vbscript).
1220
['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
1221
// Contains unescaped stylesheet content
1222
['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
1223
['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
1225
['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
1226
registerLangHandler(
1229
[PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
1230
[PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
1233
[PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
1234
[PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
1235
['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
1236
[PR_PUNCTUATION, /^[=<>\/]+/],
1237
['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
1238
['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
1239
['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
1240
['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
1241
['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
1242
['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
1245
registerLangHandler(
1246
createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
1247
registerLangHandler(sourceDecorator({
1248
'keywords': CPP_KEYWORDS,
1249
'hashComments': true,
1250
'cStyleComments': true
1251
}), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
1252
registerLangHandler(sourceDecorator({
1253
'keywords': 'null true false'
1255
registerLangHandler(sourceDecorator({
1256
'keywords': CSHARP_KEYWORDS,
1257
'hashComments': true,
1258
'cStyleComments': true,
1259
'verbatimStrings': true
1261
registerLangHandler(sourceDecorator({
1262
'keywords': JAVA_KEYWORDS,
1263
'cStyleComments': true
1265
registerLangHandler(sourceDecorator({
1266
'keywords': SH_KEYWORDS,
1267
'hashComments': true,
1268
'multiLineStrings': true
1269
}), ['bsh', 'csh', 'sh']);
1270
registerLangHandler(sourceDecorator({
1271
'keywords': PYTHON_KEYWORDS,
1272
'hashComments': true,
1273
'multiLineStrings': true,
1274
'tripleQuotedStrings': true
1276
registerLangHandler(sourceDecorator({
1277
'keywords': PERL_KEYWORDS,
1278
'hashComments': true,
1279
'multiLineStrings': true,
1280
'regexLiterals': true
1281
}), ['perl', 'pl', 'pm']);
1282
registerLangHandler(sourceDecorator({
1283
'keywords': RUBY_KEYWORDS,
1284
'hashComments': true,
1285
'multiLineStrings': true,
1286
'regexLiterals': true
1288
registerLangHandler(sourceDecorator({
1289
'keywords': JSCRIPT_KEYWORDS,
1290
'cStyleComments': true,
1291
'regexLiterals': true
1293
registerLangHandler(
1294
createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
1296
function applyDecorator(job) {
1297
var sourceCodeHtml = job.sourceCodeHtml;
1298
var opt_langExtension = job.langExtension;
1300
// Prepopulate output in case processing fails with an exception.
1301
job.prettyPrintedHtml = sourceCodeHtml;
1304
// Extract tags, and convert the source code to plain text.
1305
var sourceAndExtractedTags = extractTags(sourceCodeHtml);
1306
/** Plain text. @type {string} */
1307
var source = sourceAndExtractedTags.source;
1308
job.source = source;
1311
/** Even entries are positions in source in ascending order. Odd entries
1312
* are tags that were extracted at that position.
1313
* @type {Array.<number|string>}
1315
job.extractedTags = sourceAndExtractedTags.tags;
1317
// Apply the appropriate language handler
1318
langHandlerForExtension(opt_langExtension, source)(job);
1319
// Integrate the decorations and tags back into the source code to produce
1320
// a decorated html string which is left in job.prettyPrintedHtml.
1321
recombineTagsAndDecorations(job);
1323
if ('console' in window) {
1330
function prettyPrintOne(sourceCodeHtml, opt_langExtension) {
1332
sourceCodeHtml: sourceCodeHtml,
1333
langExtension: opt_langExtension
1335
applyDecorator(job);
1336
return job.prettyPrintedHtml;
1339
function prettyPrint(opt_whenDone) {
1340
var isIE678 = window['_pr_isIE6']();
1341
var ieNewline = isIE678 === 6 ? '\r\n' : '\r';
1342
// See bug 71 and http://stackoverflow.com/questions/136443/why-doesnt-ie7-
1344
// fetch a list of nodes to rewrite
1345
var codeSegments = [
1346
document.getElementsByTagName('pre'),
1347
document.getElementsByTagName('code'),
1348
document.getElementsByTagName('td'), /* ND Change: Add tables to support prototypes. */
1349
document.getElementsByTagName('xmp') ];
1351
for (var i = 0; i < codeSegments.length; ++i) {
1352
for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
1353
elements.push(codeSegments[i][j]);
1356
codeSegments = null;
1359
if (!clock['now']) {
1360
clock = { 'now': function () { return (new Date).getTime(); } };
1363
// The loop is broken into a series of continuations to make sure that we
1364
// don't make the browser unresponsive when rewriting a large page.
1366
var prettyPrintingJob;
1369
var endTime = (window['PR_SHOULD_USE_CONTINUATION'] ?
1370
clock.now() + 250 /* ms */ :
1372
for (; k < elements.length && clock.now() < endTime; k++) {
1373
var cs = elements[k];
1374
if (cs.className && cs.className.indexOf('prettyprint') >= 0) {
1375
// If the classes includes a language extensions, use it.
1376
// Language extensions can be specified like
1377
// <pre class="prettyprint lang-cpp">
1378
// the language extension "cpp" is used to find a language handler as
1379
// passed to PR_registerLangHandler.
1380
var langExtension = cs.className.match(/\blang-(\w+)\b/);
1381
if (langExtension) { langExtension = langExtension[1]; }
1383
// make sure this is not nested in an already prettified element
1385
for (var p = cs.parentNode; p; p = p.parentNode) {
1386
if ((p.tagName === 'pre' || p.tagName === 'code' ||
1387
p.tagName === 'xmp' || p.tagName === 'td') && /* ND Change: Add tables to support prototypes */
1388
p.className && p.className.indexOf('prettyprint') >= 0) {
1394
// fetch the content as a snippet of properly escaped HTML.
1395
// Firefox adds newlines at the end.
1396
var content = getInnerHtml(cs);
1397
content = content.replace(/(?:\r\n?|\n)$/, '');
1399
/* ND Change: we need to preserve s so change them to a special character instead of a space. */
1400
content = content.replace(/ /g, '\x11');
1402
// do the pretty printing
1403
prettyPrintingJob = {
1404
sourceCodeHtml: content,
1405
langExtension: langExtension,
1408
applyDecorator(prettyPrintingJob);
1409
replaceWithPrettyPrintedHtml();
1413
if (k < elements.length) {
1414
// finish up in a continuation
1415
setTimeout(doWork, 250);
1416
} else if (opt_whenDone) {
1421
function replaceWithPrettyPrintedHtml() {
1422
var newContent = prettyPrintingJob.prettyPrintedHtml;
1423
if (!newContent) { return; }
1425
/* ND Change: Restore the preserved s. */
1426
newContent = newContent.replace(/\x11/g, ' ');
1428
var cs = prettyPrintingJob.sourceNode;
1430
// push the prettified html back into the tag.
1431
if (!isRawContent(cs)) {
1432
// just replace the old html with the new
1433
cs.innerHTML = newContent;
1435
// we need to change the tag to a <pre> since <xmp>s do not allow
1436
// embedded tags such as the span tags used to attach styles to
1437
// sections of source code.
1438
var pre = document.createElement('PRE');
1439
for (var i = 0; i < cs.attributes.length; ++i) {
1440
var a = cs.attributes[i];
1442
var aname = a.name.toLowerCase();
1443
if (aname === 'class') {
1444
pre.className = a.value; // For IE 6
1446
pre.setAttribute(a.name, a.value);
1450
pre.innerHTML = newContent;
1453
cs.parentNode.replaceChild(pre, cs);
1457
// Replace <br>s with line-feeds so that copying and pasting works
1459
// Doing this on other browsers breaks lots of stuff since \r\n is
1460
// treated as two newlines on Firefox, and doing this also slows
1462
if (isIE678 && cs.tagName === 'PRE') {
1463
var lineBreaks = cs.getElementsByTagName('br');
1464
for (var j = lineBreaks.length; --j >= 0;) {
1465
var lineBreak = lineBreaks[j];
1466
lineBreak.parentNode.replaceChild(
1467
document.createTextNode(ieNewline), lineBreak);
1475
window['PR_normalizedHtml'] = normalizedHtml;
1476
window['prettyPrintOne'] = prettyPrintOne;
1477
window['prettyPrint'] = prettyPrint;
1479
'combinePrefixPatterns': combinePrefixPatterns,
1480
'createSimpleLexer': createSimpleLexer,
1481
'registerLangHandler': registerLangHandler,
1482
'sourceDecorator': sourceDecorator,
1483
'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
1484
'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
1485
'PR_COMMENT': PR_COMMENT,
1486
'PR_DECLARATION': PR_DECLARATION,
1487
'PR_KEYWORD': PR_KEYWORD,
1488
'PR_LITERAL': PR_LITERAL,
1489
'PR_NOCODE': PR_NOCODE,
1490
'PR_PLAIN': PR_PLAIN,
1491
'PR_PUNCTUATION': PR_PUNCTUATION,
1492
'PR_SOURCE': PR_SOURCE,
1493
'PR_STRING': PR_STRING,
1500
// ____________________________________________________________________________
1506
PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0]+/,null,' \n\r \xa0'],[PR.PR_STRING,/^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/,null,'\"\'']],[[PR.PR_COMMENT,/^--(?:\[(=*)\[[\s\S]*?(?:\]\1\]|$)|[^\r\n]*)/],[PR.PR_STRING,/^\[(=*)\[[\s\S]*?(?:\]\1\]|$)/],[PR.PR_KEYWORD,/^(?:and|break|do|else|elseif|end|false|for|function|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,null],[PR.PR_LITERAL,/^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],[PR.PR_PLAIN,/^[a-z_]\w*/i],[PR.PR_PUNCTUATION,/^[^\w\t\n\r \xA0][^\w\t\n\r \xA0\"\'\-\+=]*/]]),['lua'])
1509
// Haskell extension
1511
PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\x0B\x0C\r ]+/,null,' \n\r '],[PR.PR_STRING,/^\"(?:[^\"\\\n\x0C\r]|\\[\s\S])*(?:\"|$)/,null,'\"'],[PR.PR_STRING,/^\'(?:[^\'\\\n\x0C\r]|\\[^&])\'?/,null,'\''],[PR.PR_LITERAL,/^(?:0o[0-7]+|0x[\da-f]+|\d+(?:\.\d+)?(?:e[+\-]?\d+)?)/i,null,'0123456789']],[[PR.PR_COMMENT,/^(?:(?:--+(?:[^\r\n\x0C]*)?)|(?:\{-(?:[^-]|-+[^-\}])*-\}))/],[PR.PR_KEYWORD,/^(?:case|class|data|default|deriving|do|else|if|import|in|infix|infixl|infixr|instance|let|module|newtype|of|then|type|where|_)(?=[^a-zA-Z0-9\']|$)/,null],[PR.PR_PLAIN,/^(?:[A-Z][\w\']*\.)*[a-zA-Z][\w\']*/],[PR.PR_PUNCTUATION,/^[^\t\n\x0B\x0C\r a-zA-Z0-9\'\"]+/]]),['hs'])
1516
PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0]+/,null,' \n\r \xa0'],[PR.PR_COMMENT,/^#(?:if[\t\n\r \xA0]+(?:[a-z_$][\w\']*|``[^\r\n\t`]*(?:``|$))|else|endif|light)/i,null,'#'],[PR.PR_STRING,/^(?:\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)|\'(?:[^\'\\]|\\[\s\S])*(?:\'|$))/,null,'\"\'']],[[PR.PR_COMMENT,/^(?:\/\/[^\r\n]*|\(\*[\s\S]*?\*\))/],[PR.PR_KEYWORD,/^(?:abstract|and|as|assert|begin|class|default|delegate|do|done|downcast|downto|elif|else|end|exception|extern|false|finally|for|fun|function|if|in|inherit|inline|interface|internal|lazy|let|match|member|module|mutable|namespace|new|null|of|open|or|override|private|public|rec|return|static|struct|then|to|true|try|type|upcast|use|val|void|when|while|with|yield|asr|land|lor|lsl|lsr|lxor|mod|sig|atomic|break|checked|component|const|constraint|constructor|continue|eager|event|external|fixed|functor|global|include|method|mixin|object|parallel|process|protected|pure|sealed|trait|virtual|volatile)\b/],[PR.PR_LITERAL,/^[+\-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],[PR.PR_PLAIN,/^(?:[a-z_]\w*[!?#]?|``[^\r\n\t`]*(?:``|$))/i],[PR.PR_PUNCTUATION,/^[^\t\n\r \xA0\"\'\w]+/]]),['fs','ml'])
1521
PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0]+/,null,' \n\r \xa0'],[PR.PR_STRING,/^(?:"(?:[^\"\\]|\\.)*"|'(?:[^\'\\]|\\.)*')/,null,'\"\'']],[[PR.PR_COMMENT,/^(?:--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$))/],[PR.PR_KEYWORD,/^(?:ADD|ALL|ALTER|AND|ANY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\w-]|$)/i,null],[PR.PR_LITERAL,/^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],[PR.PR_PLAIN,/^[a-z_][\w-]*/i],[PR.PR_PUNCTUATION,/^[^\w\t\n\r \xA0\"\'][^\w\t\n\r \xA0+\-\"\']*/]]),['sql'])
1526
PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[\t\n\r \xA0\u2028\u2029]+/,null,' \n\r \xa0\u2028\u2029'],[PR.PR_STRING,/^(?:[\"\u201C\u201D](?:[^\"\u201C\u201D]|[\"\u201C\u201D]{2})(?:[\"\u201C\u201D]c|$)|[\"\u201C\u201D](?:[^\"\u201C\u201D]|[\"\u201C\u201D]{2})*(?:[\"\u201C\u201D]|$))/i,null,'\"\u201c\u201d'],[PR.PR_COMMENT,/^[\'\u2018\u2019][^\r\n\u2028\u2029]*/,null,'\'\u2018\u2019']],[[PR.PR_KEYWORD,/^(?:AddHandler|AddressOf|Alias|And|AndAlso|Ansi|As|Assembly|Auto|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|CDbl|CDec|Char|CInt|Class|CLng|CObj|Const|CShort|CSng|CStr|CType|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|EndIf|Enum|Erase|Error|Event|Exit|Finally|For|Friend|Function|Get|GetType|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|Let|Lib|Like|Long|Loop|Me|Mod|Module|MustInherit|MustOverride|MyBase|MyClass|Namespace|New|Next|Not|NotInheritable|NotOverridable|Object|On|Option|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Preserve|Private|Property|Protected|Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|Return|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop|String|Structure|Sub|SyncLock|Then|Throw|To|Try|TypeOf|Unicode|Until|Variant|Wend|When|While|With|WithEvents|WriteOnly|Xor|EndIf|GoSub|Let|Variant|Wend)\b/i,null],[PR.PR_COMMENT,/^REM[^\r\n\u2028\u2029]*/i],[PR.PR_LITERAL,/^(?:True\b|False\b|Nothing\b|\d+(?:E[+\-]?\d+[FRD]?|[FRDSIL])?|(?:&H[0-9A-F]+|&O[0-7]+)[SIL]?|\d*\.\d+(?:E[+\-]?\d+)?[FRD]?|#\s+(?:\d+[\-\/]\d+[\-\/]\d+(?:\s+\d+:\d+(?::\d+)?(\s*(?:AM|PM))?)?|\d+:\d+(?::\d+)?(\s*(?:AM|PM))?)\s+#)/i],[PR.PR_PLAIN,/^(?:(?:[a-z]|_\w)\w*|\[(?:[a-z]|_\w)\w*\])/i],[PR.PR_PUNCTUATION,/^[^\w\t\n\r \"\'\[\]\xA0\u2018\u2019\u201C\u201D\u2028\u2029]+/],[PR.PR_PUNCTUATION,/^(?:\[|\])/]]),['vb','vbs'])