gkss-rails 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1742 @@
1
+ /**
2
+ * @license
3
+ * Copyright (C) 2006 Google Inc.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * @fileoverview
20
+ * some functions for browser-side pretty printing of code contained in html.
21
+ *
22
+ * <p>
23
+ * For a fairly comprehensive set of languages see the
24
+ * <a href="https://github.com/google/code-prettify#for-which-languages-does-it-work">README</a>
25
+ * file that came with this source. At a minimum, the lexer should work on a
26
+ * number of languages including C and friends, Java, Python, Bash, SQL, HTML,
27
+ * XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
28
+ * and a subset of Perl, but, because of commenting conventions, doesn't work on
29
+ * Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
30
+ * <p>
31
+ * Usage: <ol>
32
+ * <li> include this source file in an html page via
33
+ * {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
34
+ * <li> define style rules. See the example page for examples.
35
+ * <li> mark the {@code <pre>} and {@code <code>} tags in your source with
36
+ * {@code class=prettyprint.}
37
+ * You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
38
+ * printer needs to do more substantial DOM manipulations to support that, so
39
+ * some css styles may not be preserved.
40
+ * </ol>
41
+ * That's it. I wanted to keep the API as simple as possible, so there's no
42
+ * need to specify which language the code is in, but if you wish, you can add
43
+ * another class to the {@code <pre>} or {@code <code>} element to specify the
44
+ * language, as in {@code <pre class="prettyprint lang-java">}. Any class that
45
+ * starts with "lang-" followed by a file extension, specifies the file type.
46
+ * See the "lang-*.js" files in this directory for code that implements
47
+ * per-language file handlers.
48
+ * <p>
49
+ * Change log:<br>
50
+ * cbeust, 2006/08/22
51
+ * <blockquote>
52
+ * Java annotations (start with "@") are now captured as literals ("lit")
53
+ * </blockquote>
54
+ * @requires console
55
+ */
56
+
57
+ // JSLint declarations
58
+ /*global console, document, navigator, setTimeout, window, define */
59
+
60
+
61
+ /**
62
+ * @typedef {!Array.<number|string>}
63
+ * Alternating indices and the decorations that should be inserted there.
64
+ * The indices are monotonically increasing.
65
+ */
66
+ var DecorationsT;
67
+
68
+ /**
69
+ * @typedef {!{
70
+ * sourceNode: !Element,
71
+ * pre: !(number|boolean),
72
+ * langExtension: ?string,
73
+ * numberLines: ?(number|boolean),
74
+ * sourceCode: ?string,
75
+ * spans: ?(Array.<number|Node>),
76
+ * basePos: ?number,
77
+ * decorations: ?DecorationsT
78
+ * }}
79
+ * <dl>
80
+ * <dt>sourceNode<dd>the element containing the source
81
+ * <dt>sourceCode<dd>source as plain text
82
+ * <dt>pre<dd>truthy if white-space in text nodes
83
+ * should be considered significant.
84
+ * <dt>spans<dd> alternating span start indices into source
85
+ * and the text node or element (e.g. {@code <BR>}) corresponding to that
86
+ * span.
87
+ * <dt>decorations<dd>an array of style classes preceded
88
+ * by the position at which they start in job.sourceCode in order
89
+ * <dt>basePos<dd>integer position of this.sourceCode in the larger chunk of
90
+ * source.
91
+ * </dl>
92
+ */
93
+ var JobT;
94
+
95
+ /**
96
+ * @typedef {!{
97
+ * sourceCode: string,
98
+ * spans: !(Array.<number|Node>)
99
+ * }}
100
+ * <dl>
101
+ * <dt>sourceCode<dd>source as plain text
102
+ * <dt>spans<dd> alternating span start indices into source
103
+ * and the text node or element (e.g. {@code <BR>}) corresponding to that
104
+ * span.
105
+ * </dl>
106
+ */
107
+ var SourceSpansT;
108
+
109
+ /** @define {boolean} */
110
+ var IN_GLOBAL_SCOPE = false;
111
+
112
+ var HACK_TO_FIX_JS_INCLUDE_PL;
113
+
114
+ /**
115
+ * {@type !{
116
+ * 'createSimpleLexer': function (Array, Array): (function (JobT)),
117
+ * 'registerLangHandler': function (function (JobT), Array.<string>),
118
+ * 'PR_ATTRIB_NAME': string,
119
+ * 'PR_ATTRIB_NAME': string,
120
+ * 'PR_ATTRIB_VALUE': string,
121
+ * 'PR_COMMENT': string,
122
+ * 'PR_DECLARATION': string,
123
+ * 'PR_KEYWORD': string,
124
+ * 'PR_LITERAL': string,
125
+ * 'PR_NOCODE': string,
126
+ * 'PR_PLAIN': string,
127
+ * 'PR_PUNCTUATION': string,
128
+ * 'PR_SOURCE': string,
129
+ * 'PR_STRING': string,
130
+ * 'PR_TAG': string,
131
+ * 'PR_TYPE': string,
132
+ * 'prettyPrintOne': function (string, string, number|boolean),
133
+ * 'prettyPrint': function (?function, ?(HTMLElement|HTMLDocument))
134
+ * }}
135
+ * @const
136
+ */
137
+ var PR;
138
+
139
+ /**
140
+ * Split {@code prettyPrint} into multiple timeouts so as not to interfere with
141
+ * UI events.
142
+ * If set to {@code false}, {@code prettyPrint()} is synchronous.
143
+ */
144
+ window['PR_SHOULD_USE_CONTINUATION'] = true;
145
+
146
+ /**
147
+ * Pretty print a chunk of code.
148
+ * @param {string} sourceCodeHtml The HTML to pretty print.
149
+ * @param {string} opt_langExtension The language name to use.
150
+ * Typically, a filename extension like 'cpp' or 'java'.
151
+ * @param {number|boolean} opt_numberLines True to number lines,
152
+ * or the 1-indexed number of the first line in sourceCodeHtml.
153
+ * @return {string} code as html, but prettier
154
+ */
155
+ var prettyPrintOne;
156
+ /**
157
+ * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
158
+ * {@code class=prettyprint} and prettify them.
159
+ *
160
+ * @param {Function} opt_whenDone called when prettifying is done.
161
+ * @param {HTMLElement|HTMLDocument} opt_root an element or document
162
+ * containing all the elements to pretty print.
163
+ * Defaults to {@code document.body}.
164
+ */
165
+ var prettyPrint;
166
+
167
+
168
+ (function () {
169
+ var win = window;
170
+ // Keyword lists for various languages.
171
+ // We use things that coerce to strings to make them compact when minified
172
+ // and to defeat aggressive optimizers that fold large string constants.
173
+ var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
174
+ var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
175
+ "double,enum,extern,float,goto,inline,int,long,register,restrict,short,signed," +
176
+ "sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];
177
+ var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
178
+ "new,operator,private,protected,public,this,throw,true,try,typeof"];
179
+ var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignas,alignof,align_union,asm,axiom,bool," +
180
+ "concept,concept_map,const_cast,constexpr,decltype,delegate," +
181
+ "dynamic_cast,explicit,export,friend,generic,late_check," +
182
+ "mutable,namespace,noexcept,noreturn,nullptr,property,reinterpret_cast,static_assert," +
183
+ "static_cast,template,typeid,typename,using,virtual,where"];
184
+ var JAVA_KEYWORDS = [COMMON_KEYWORDS,
185
+ "abstract,assert,boolean,byte,extends,finally,final,implements,import," +
186
+ "instanceof,interface,null,native,package,strictfp,super,synchronized," +
187
+ "throws,transient"];
188
+ var CSHARP_KEYWORDS = [COMMON_KEYWORDS,
189
+ "abstract,add,alias,as,ascending,async,await,base,bool,by,byte,checked,decimal,delegate,descending," +
190
+ "dynamic,event,finally,fixed,foreach,from,get,global,group,implicit,in,interface," +
191
+ "internal,into,is,join,let,lock,null,object,out,override,orderby,params," +
192
+ "partial,readonly,ref,remove,sbyte,sealed,select,set,stackalloc,string,select,uint,ulong," +
193
+ "unchecked,unsafe,ushort,value,var,virtual,where,yield"];
194
+ var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
195
+ "for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
196
+ "throw,true,try,unless,until,when,while,yes";
197
+ var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
198
+ "abstract,async,await,constructor,debugger,enum,eval,export,function," +
199
+ "get,implements,instanceof,interface,let,null,set,undefined,var,with," +
200
+ "yield,Infinity,NaN"];
201
+ var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
202
+ "goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
203
+ "sub,undef,unless,until,use,wantarray,while,BEGIN,END";
204
+ var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
205
+ "elif,except,exec,finally,from,global,import,in,is,lambda," +
206
+ "nonlocal,not,or,pass,print,raise,try,with,yield," +
207
+ "False,True,None"];
208
+ var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
209
+ "def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
210
+ "rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
211
+ "BEGIN,END"];
212
+ var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
213
+ "function,in,local,set,then,until"];
214
+ var ALL_KEYWORDS = [
215
+ CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_KEYWORDS, JSCRIPT_KEYWORDS,
216
+ PERL_KEYWORDS, PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
217
+ var C_TYPES = /^(DIR|FILE|array|vector|(de|priority_)?queue|(forward_)?list|stack|(const_)?(reverse_)?iterator|(unordered_)?(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
218
+
219
+ // token style names. correspond to css classes
220
+ /**
221
+ * token style for a string literal
222
+ * @const
223
+ */
224
+ var PR_STRING = 'str';
225
+ /**
226
+ * token style for a keyword
227
+ * @const
228
+ */
229
+ var PR_KEYWORD = 'kwd';
230
+ /**
231
+ * token style for a comment
232
+ * @const
233
+ */
234
+ var PR_COMMENT = 'com';
235
+ /**
236
+ * token style for a type
237
+ * @const
238
+ */
239
+ var PR_TYPE = 'typ';
240
+ /**
241
+ * token style for a literal value. e.g. 1, null, true.
242
+ * @const
243
+ */
244
+ var PR_LITERAL = 'lit';
245
+ /**
246
+ * token style for a punctuation string.
247
+ * @const
248
+ */
249
+ var PR_PUNCTUATION = 'pun';
250
+ /**
251
+ * token style for plain text.
252
+ * @const
253
+ */
254
+ var PR_PLAIN = 'pln';
255
+
256
+ /**
257
+ * token style for an sgml tag.
258
+ * @const
259
+ */
260
+ var PR_TAG = 'tag';
261
+ /**
262
+ * token style for a markup declaration such as a DOCTYPE.
263
+ * @const
264
+ */
265
+ var PR_DECLARATION = 'dec';
266
+ /**
267
+ * token style for embedded source.
268
+ * @const
269
+ */
270
+ var PR_SOURCE = 'src';
271
+ /**
272
+ * token style for an sgml attribute name.
273
+ * @const
274
+ */
275
+ var PR_ATTRIB_NAME = 'atn';
276
+ /**
277
+ * token style for an sgml attribute value.
278
+ * @const
279
+ */
280
+ var PR_ATTRIB_VALUE = 'atv';
281
+
282
+ /**
283
+ * A class that indicates a section of markup that is not code, e.g. to allow
284
+ * embedding of line numbers within code listings.
285
+ * @const
286
+ */
287
+ var PR_NOCODE = 'nocode';
288
+
289
+
290
+
291
+ /**
292
+ * A set of tokens that can precede a regular expression literal in
293
+ * javascript
294
+ * http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
295
+ * has the full list, but I've removed ones that might be problematic when
296
+ * seen in languages that don't support regular expression literals.
297
+ *
298
+ * <p>Specifically, I've removed any keywords that can't precede a regexp
299
+ * literal in a syntactically legal javascript program, and I've removed the
300
+ * "in" keyword since it's not a keyword in many languages, and might be used
301
+ * as a count of inches.
302
+ *
303
+ * <p>The link above does not accurately describe EcmaScript rules since
304
+ * it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
305
+ * very well in practice.
306
+ *
307
+ * @private
308
+ * @const
309
+ */
310
+ var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
311
+
312
+ // CAVEAT: this does not properly handle the case where a regular
313
+ // expression immediately follows another since a regular expression may
314
+ // have flags for case-sensitivity and the like. Having regexp tokens
315
+ // adjacent is not valid in any language I'm aware of, so I'm punting.
316
+ // TODO: maybe style special characters inside a regexp as punctuation.
317
+
318
+ /**
319
+ * Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
320
+ * matches the union of the sets of strings matched by the input RegExp.
321
+ * Since it matches globally, if the input strings have a start-of-input
322
+ * anchor (/^.../), it is ignored for the purposes of unioning.
323
+ * @param {Array.<RegExp>} regexs non multiline, non-global regexs.
324
+ * @return {RegExp} a global regex.
325
+ */
326
+ function combinePrefixPatterns(regexs) {
327
+ var capturedGroupIndex = 0;
328
+
329
+ var needToFoldCase = false;
330
+ var ignoreCase = false;
331
+ for (var i = 0, n = regexs.length; i < n; ++i) {
332
+ var regex = regexs[i];
333
+ if (regex.ignoreCase) {
334
+ ignoreCase = true;
335
+ } else if (/[a-z]/i.test(regex.source.replace(
336
+ /\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
337
+ needToFoldCase = true;
338
+ ignoreCase = false;
339
+ break;
340
+ }
341
+ }
342
+
343
+ var escapeCharToCodeUnit = {
344
+ 'b': 8,
345
+ 't': 9,
346
+ 'n': 0xa,
347
+ 'v': 0xb,
348
+ 'f': 0xc,
349
+ 'r': 0xd
350
+ };
351
+
352
+ function decodeEscape(charsetPart) {
353
+ var cc0 = charsetPart.charCodeAt(0);
354
+ if (cc0 !== 92 /* \\ */) {
355
+ return cc0;
356
+ }
357
+ var c1 = charsetPart.charAt(1);
358
+ cc0 = escapeCharToCodeUnit[c1];
359
+ if (cc0) {
360
+ return cc0;
361
+ } else if ('0' <= c1 && c1 <= '7') {
362
+ return parseInt(charsetPart.substring(1), 8);
363
+ } else if (c1 === 'u' || c1 === 'x') {
364
+ return parseInt(charsetPart.substring(2), 16);
365
+ } else {
366
+ return charsetPart.charCodeAt(1);
367
+ }
368
+ }
369
+
370
+ function encodeEscape(charCode) {
371
+ if (charCode < 0x20) {
372
+ return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
373
+ }
374
+ var ch = String.fromCharCode(charCode);
375
+ return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
376
+ ? "\\" + ch : ch;
377
+ }
378
+
379
+ function caseFoldCharset(charSet) {
380
+ var charsetParts = charSet.substring(1, charSet.length - 1).match(
381
+ new RegExp(
382
+ '\\\\u[0-9A-Fa-f]{4}'
383
+ + '|\\\\x[0-9A-Fa-f]{2}'
384
+ + '|\\\\[0-3][0-7]{0,2}'
385
+ + '|\\\\[0-7]{1,2}'
386
+ + '|\\\\[\\s\\S]'
387
+ + '|-'
388
+ + '|[^-\\\\]',
389
+ 'g'));
390
+ var ranges = [];
391
+ var inverse = charsetParts[0] === '^';
392
+
393
+ var out = ['['];
394
+ if (inverse) { out.push('^'); }
395
+
396
+ for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
397
+ var p = charsetParts[i];
398
+ if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups.
399
+ out.push(p);
400
+ } else {
401
+ var start = decodeEscape(p);
402
+ var end;
403
+ if (i + 2 < n && '-' === charsetParts[i + 1]) {
404
+ end = decodeEscape(charsetParts[i + 2]);
405
+ i += 2;
406
+ } else {
407
+ end = start;
408
+ }
409
+ ranges.push([start, end]);
410
+ // If the range might intersect letters, then expand it.
411
+ // This case handling is too simplistic.
412
+ // It does not deal with non-latin case folding.
413
+ // It works for latin source code identifiers though.
414
+ if (!(end < 65 || start > 122)) {
415
+ if (!(end < 65 || start > 90)) {
416
+ ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
417
+ }
418
+ if (!(end < 97 || start > 122)) {
419
+ ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
420
+ }
421
+ }
422
+ }
423
+ }
424
+
425
+ // [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
426
+ // -> [[1, 12], [14, 14], [16, 17]]
427
+ ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
428
+ var consolidatedRanges = [];
429
+ var lastRange = [];
430
+ for (var i = 0; i < ranges.length; ++i) {
431
+ var range = ranges[i];
432
+ if (range[0] <= lastRange[1] + 1) {
433
+ lastRange[1] = Math.max(lastRange[1], range[1]);
434
+ } else {
435
+ consolidatedRanges.push(lastRange = range);
436
+ }
437
+ }
438
+
439
+ for (var i = 0; i < consolidatedRanges.length; ++i) {
440
+ var range = consolidatedRanges[i];
441
+ out.push(encodeEscape(range[0]));
442
+ if (range[1] > range[0]) {
443
+ if (range[1] + 1 > range[0]) { out.push('-'); }
444
+ out.push(encodeEscape(range[1]));
445
+ }
446
+ }
447
+ out.push(']');
448
+ return out.join('');
449
+ }
450
+
451
+ function allowAnywhereFoldCaseAndRenumberGroups(regex) {
452
+ // Split into character sets, escape sequences, punctuation strings
453
+ // like ('(', '(?:', ')', '^'), and runs of characters that do not
454
+ // include any of the above.
455
+ var parts = regex.source.match(
456
+ new RegExp(
457
+ '(?:'
458
+ + '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
459
+ + '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
460
+ + '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
461
+ + '|\\\\[0-9]+' // a back-reference or octal escape
462
+ + '|\\\\[^ux0-9]' // other escape sequence
463
+ + '|\\(\\?[:!=]' // start of a non-capturing group
464
+ + '|[\\(\\)\\^]' // start/end of a group, or line start
465
+ + '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
466
+ + ')',
467
+ 'g'));
468
+ var n = parts.length;
469
+
470
+ // Maps captured group numbers to the number they will occupy in
471
+ // the output or to -1 if that has not been determined, or to
472
+ // undefined if they need not be capturing in the output.
473
+ var capturedGroups = [];
474
+
475
+ // Walk over and identify back references to build the capturedGroups
476
+ // mapping.
477
+ for (var i = 0, groupIndex = 0; i < n; ++i) {
478
+ var p = parts[i];
479
+ if (p === '(') {
480
+ // groups are 1-indexed, so max group index is count of '('
481
+ ++groupIndex;
482
+ } else if ('\\' === p.charAt(0)) {
483
+ var decimalValue = +p.substring(1);
484
+ if (decimalValue) {
485
+ if (decimalValue <= groupIndex) {
486
+ capturedGroups[decimalValue] = -1;
487
+ } else {
488
+ // Replace with an unambiguous escape sequence so that
489
+ // an octal escape sequence does not turn into a backreference
490
+ // to a capturing group from an earlier regex.
491
+ parts[i] = encodeEscape(decimalValue);
492
+ }
493
+ }
494
+ }
495
+ }
496
+
497
+ // Renumber groups and reduce capturing groups to non-capturing groups
498
+ // where possible.
499
+ for (var i = 1; i < capturedGroups.length; ++i) {
500
+ if (-1 === capturedGroups[i]) {
501
+ capturedGroups[i] = ++capturedGroupIndex;
502
+ }
503
+ }
504
+ for (var i = 0, groupIndex = 0; i < n; ++i) {
505
+ var p = parts[i];
506
+ if (p === '(') {
507
+ ++groupIndex;
508
+ if (!capturedGroups[groupIndex]) {
509
+ parts[i] = '(?:';
510
+ }
511
+ } else if ('\\' === p.charAt(0)) {
512
+ var decimalValue = +p.substring(1);
513
+ if (decimalValue && decimalValue <= groupIndex) {
514
+ parts[i] = '\\' + capturedGroups[decimalValue];
515
+ }
516
+ }
517
+ }
518
+
519
+ // Remove any prefix anchors so that the output will match anywhere.
520
+ // ^^ really does mean an anchored match though.
521
+ for (var i = 0; i < n; ++i) {
522
+ if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
523
+ }
524
+
525
+ // Expand letters to groups to handle mixing of case-sensitive and
526
+ // case-insensitive patterns if necessary.
527
+ if (regex.ignoreCase && needToFoldCase) {
528
+ for (var i = 0; i < n; ++i) {
529
+ var p = parts[i];
530
+ var ch0 = p.charAt(0);
531
+ if (p.length >= 2 && ch0 === '[') {
532
+ parts[i] = caseFoldCharset(p);
533
+ } else if (ch0 !== '\\') {
534
+ // TODO: handle letters in numeric escapes.
535
+ parts[i] = p.replace(
536
+ /[a-zA-Z]/g,
537
+ function (ch) {
538
+ var cc = ch.charCodeAt(0);
539
+ return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
540
+ });
541
+ }
542
+ }
543
+ }
544
+
545
+ return parts.join('');
546
+ }
547
+
548
+ var rewritten = [];
549
+ for (var i = 0, n = regexs.length; i < n; ++i) {
550
+ var regex = regexs[i];
551
+ if (regex.global || regex.multiline) { throw new Error('' + regex); }
552
+ rewritten.push(
553
+ '(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
554
+ }
555
+
556
+ return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
557
+ }
558
+
559
+ /**
560
+ * Split markup into a string of source code and an array mapping ranges in
561
+ * that string to the text nodes in which they appear.
562
+ *
563
+ * <p>
564
+ * The HTML DOM structure:</p>
565
+ * <pre>
566
+ * (Element "p"
567
+ * (Element "b"
568
+ * (Text "print ")) ; #1
569
+ * (Text "'Hello '") ; #2
570
+ * (Element "br") ; #3
571
+ * (Text " + 'World';")) ; #4
572
+ * </pre>
573
+ * <p>
574
+ * corresponds to the HTML
575
+ * {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p>
576
+ *
577
+ * <p>
578
+ * It will produce the output:</p>
579
+ * <pre>
580
+ * {
581
+ * sourceCode: "print 'Hello '\n + 'World';",
582
+ * // 1 2
583
+ * // 012345678901234 5678901234567
584
+ * spans: [0, #1, 6, #2, 14, #3, 15, #4]
585
+ * }
586
+ * </pre>
587
+ * <p>
588
+ * where #1 is a reference to the {@code "print "} text node above, and so
589
+ * on for the other text nodes.
590
+ * </p>
591
+ *
592
+ * <p>
593
+ * The {@code} spans array is an array of pairs. Even elements are the start
594
+ * indices of substrings, and odd elements are the text nodes (or BR elements)
595
+ * that contain the text for those substrings.
596
+ * Substrings continue until the next index or the end of the source.
597
+ * </p>
598
+ *
599
+ * @param {Node} node an HTML DOM subtree containing source-code.
600
+ * @param {boolean|number} isPreformatted truthy if white-space in
601
+ * text nodes should be considered significant.
602
+ * @return {SourceSpansT} source code and the nodes in which they occur.
603
+ */
604
+ function extractSourceSpans(node, isPreformatted) {
605
+ var nocode = /(?:^|\s)nocode(?:\s|$)/;
606
+
607
+ var chunks = [];
608
+ var length = 0;
609
+ var spans = [];
610
+ var k = 0;
611
+
612
+ function walk(node) {
613
+ var type = node.nodeType;
614
+ if (type == 1) { // Element
615
+ if (nocode.test(node.className)) { return; }
616
+ for (var child = node.firstChild; child; child = child.nextSibling) {
617
+ walk(child);
618
+ }
619
+ var nodeName = node.nodeName.toLowerCase();
620
+ if ('br' === nodeName || 'li' === nodeName) {
621
+ chunks[k] = '\n';
622
+ spans[k << 1] = length++;
623
+ spans[(k++ << 1) | 1] = node;
624
+ }
625
+ } else if (type == 3 || type == 4) { // Text
626
+ var text = node.nodeValue;
627
+ if (text.length) {
628
+ if (!isPreformatted) {
629
+ text = text.replace(/[ \t\r\n]+/g, ' ');
630
+ } else {
631
+ text = text.replace(/\r\n?/g, '\n'); // Normalize newlines.
632
+ }
633
+ // TODO: handle tabs here?
634
+ chunks[k] = text;
635
+ spans[k << 1] = length;
636
+ length += text.length;
637
+ spans[(k++ << 1) | 1] = node;
638
+ }
639
+ }
640
+ }
641
+
642
+ walk(node);
643
+
644
+ return {
645
+ sourceCode: chunks.join('').replace(/\n$/, ''),
646
+ spans: spans
647
+ };
648
+ }
649
+
650
+ /**
651
+ * Apply the given language handler to sourceCode and add the resulting
652
+ * decorations to out.
653
+ * @param {!Element} sourceNode
654
+ * @param {number} basePos the index of sourceCode within the chunk of source
655
+ * whose decorations are already present on out.
656
+ * @param {string} sourceCode
657
+ * @param {function(JobT)} langHandler
658
+ * @param {DecorationsT} out
659
+ */
660
+ function appendDecorations(
661
+ sourceNode, basePos, sourceCode, langHandler, out) {
662
+ if (!sourceCode) { return; }
663
+ /** @type {JobT} */
664
+ var job = {
665
+ sourceNode: sourceNode,
666
+ pre: 1,
667
+ langExtension: null,
668
+ numberLines: null,
669
+ sourceCode: sourceCode,
670
+ spans: null,
671
+ basePos: basePos,
672
+ decorations: null
673
+ };
674
+ langHandler(job);
675
+ out.push.apply(out, job.decorations);
676
+ }
677
+
678
+ var notWs = /\S/;
679
+
680
+ /**
681
+ * Given an element, if it contains only one child element and any text nodes
682
+ * it contains contain only space characters, return the sole child element.
683
+ * Otherwise returns undefined.
684
+ * <p>
685
+ * This is meant to return the CODE element in {@code <pre><code ...>} when
686
+ * there is a single child element that contains all the non-space textual
687
+ * content, but not to return anything where there are multiple child elements
688
+ * as in {@code <pre><code>...</code><code>...</code></pre>} or when there
689
+ * is textual content.
690
+ */
691
+ function childContentWrapper(element) {
692
+ var wrapper = undefined;
693
+ for (var c = element.firstChild; c; c = c.nextSibling) {
694
+ var type = c.nodeType;
695
+ wrapper = (type === 1) // Element Node
696
+ ? (wrapper ? element : c)
697
+ : (type === 3) // Text Node
698
+ ? (notWs.test(c.nodeValue) ? element : wrapper)
699
+ : wrapper;
700
+ }
701
+ return wrapper === element ? undefined : wrapper;
702
+ }
703
+
704
+ /** Given triples of [style, pattern, context] returns a lexing function,
705
+ * The lexing function interprets the patterns to find token boundaries and
706
+ * returns a decoration list of the form
707
+ * [index_0, style_0, index_1, style_1, ..., index_n, style_n]
708
+ * where index_n is an index into the sourceCode, and style_n is a style
709
+ * constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
710
+ * all characters in sourceCode[index_n-1:index_n].
711
+ *
712
+ * The stylePatterns is a list whose elements have the form
713
+ * [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
714
+ *
715
+ * Style is a style constant like PR_PLAIN, or can be a string of the
716
+ * form 'lang-FOO', where FOO is a language extension describing the
717
+ * language of the portion of the token in $1 after pattern executes.
718
+ * E.g., if style is 'lang-lisp', and group 1 contains the text
719
+ * '(hello (world))', then that portion of the token will be passed to the
720
+ * registered lisp handler for formatting.
721
+ * The text before and after group 1 will be restyled using this decorator
722
+ * so decorators should take care that this doesn't result in infinite
723
+ * recursion. For example, the HTML lexer rule for SCRIPT elements looks
724
+ * something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
725
+ * '<script>foo()<\/script>', which would cause the current decorator to
726
+ * be called with '<script>' which would not match the same rule since
727
+ * group 1 must not be empty, so it would be instead styled as PR_TAG by
728
+ * the generic tag rule. The handler registered for the 'js' extension would
729
+ * then be called with 'foo()', and finally, the current decorator would
730
+ * be called with '<\/script>' which would not match the original rule and
731
+ * so the generic tag rule would identify it as a tag.
732
+ *
733
+ * Pattern must only match prefixes, and if it matches a prefix, then that
734
+ * match is considered a token with the same style.
735
+ *
736
+ * Context is applied to the last non-whitespace, non-comment token
737
+ * recognized.
738
+ *
739
+ * Shortcut is an optional string of characters, any of which, if the first
740
+ * character, gurantee that this pattern and only this pattern matches.
741
+ *
742
+ * @param {Array} shortcutStylePatterns patterns that always start with
743
+ * a known character. Must have a shortcut string.
744
+ * @param {Array} fallthroughStylePatterns patterns that will be tried in
745
+ * order if the shortcut ones fail. May have shortcuts.
746
+ *
747
+ * @return {function (JobT)} a function that takes an undecorated job and
748
+ * attaches a list of decorations.
749
+ */
750
+ function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
751
+ var shortcuts = {};
752
+ var tokenizer;
753
+ (function () {
754
+ var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
755
+ var allRegexs = [];
756
+ var regexKeys = {};
757
+ for (var i = 0, n = allPatterns.length; i < n; ++i) {
758
+ var patternParts = allPatterns[i];
759
+ var shortcutChars = patternParts[3];
760
+ if (shortcutChars) {
761
+ for (var c = shortcutChars.length; --c >= 0;) {
762
+ shortcuts[shortcutChars.charAt(c)] = patternParts;
763
+ }
764
+ }
765
+ var regex = patternParts[1];
766
+ var k = '' + regex;
767
+ if (!regexKeys.hasOwnProperty(k)) {
768
+ allRegexs.push(regex);
769
+ regexKeys[k] = null;
770
+ }
771
+ }
772
+ allRegexs.push(/[\0-\uffff]/);
773
+ tokenizer = combinePrefixPatterns(allRegexs);
774
+ })();
775
+
776
+ var nPatterns = fallthroughStylePatterns.length;
777
+
778
+ /**
779
+ * Lexes job.sourceCode and attaches an output array job.decorations of
780
+ * style classes preceded by the position at which they start in
781
+ * job.sourceCode in order.
782
+ *
783
+ * @type{function (JobT)}
784
+ */
785
+ var decorate = function (job) {
786
+ var sourceCode = job.sourceCode, basePos = job.basePos;
787
+ var sourceNode = job.sourceNode;
788
+ /** Even entries are positions in source in ascending order. Odd enties
789
+ * are style markers (e.g., PR_COMMENT) that run from that position until
790
+ * the end.
791
+ * @type {DecorationsT}
792
+ */
793
+ var decorations = [basePos, PR_PLAIN];
794
+ var pos = 0; // index into sourceCode
795
+ var tokens = sourceCode.match(tokenizer) || [];
796
+ var styleCache = {};
797
+
798
+ for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
799
+ var token = tokens[ti];
800
+ var style = styleCache[token];
801
+ var match = void 0;
802
+
803
+ var isEmbedded;
804
+ if (typeof style === 'string') {
805
+ isEmbedded = false;
806
+ } else {
807
+ var patternParts = shortcuts[token.charAt(0)];
808
+ if (patternParts) {
809
+ match = token.match(patternParts[1]);
810
+ style = patternParts[0];
811
+ } else {
812
+ for (var i = 0; i < nPatterns; ++i) {
813
+ patternParts = fallthroughStylePatterns[i];
814
+ match = token.match(patternParts[1]);
815
+ if (match) {
816
+ style = patternParts[0];
817
+ break;
818
+ }
819
+ }
820
+
821
+ if (!match) { // make sure that we make progress
822
+ style = PR_PLAIN;
823
+ }
824
+ }
825
+
826
+ isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
827
+ if (isEmbedded && !(match && typeof match[1] === 'string')) {
828
+ isEmbedded = false;
829
+ style = PR_SOURCE;
830
+ }
831
+
832
+ if (!isEmbedded) { styleCache[token] = style; }
833
+ }
834
+
835
+ var tokenStart = pos;
836
+ pos += token.length;
837
+
838
+ if (!isEmbedded) {
839
+ decorations.push(basePos + tokenStart, style);
840
+ } else { // Treat group 1 as an embedded block of source code.
841
+ var embeddedSource = match[1];
842
+ var embeddedSourceStart = token.indexOf(embeddedSource);
843
+ var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
844
+ if (match[2]) {
845
+ // If embeddedSource can be blank, then it would match at the
846
+ // beginning which would cause us to infinitely recurse on the
847
+ // entire token, so we catch the right context in match[2].
848
+ embeddedSourceEnd = token.length - match[2].length;
849
+ embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
850
+ }
851
+ var lang = style.substring(5);
852
+ // Decorate the left of the embedded source
853
+ appendDecorations(
854
+ sourceNode,
855
+ basePos + tokenStart,
856
+ token.substring(0, embeddedSourceStart),
857
+ decorate, decorations);
858
+ // Decorate the embedded source
859
+ appendDecorations(
860
+ sourceNode,
861
+ basePos + tokenStart + embeddedSourceStart,
862
+ embeddedSource,
863
+ langHandlerForExtension(lang, embeddedSource),
864
+ decorations);
865
+ // Decorate the right of the embedded section
866
+ appendDecorations(
867
+ sourceNode,
868
+ basePos + tokenStart + embeddedSourceEnd,
869
+ token.substring(embeddedSourceEnd),
870
+ decorate, decorations);
871
+ }
872
+ }
873
+ job.decorations = decorations;
874
+ };
875
+ return decorate;
876
+ }
877
+
878
+ /** returns a function that produces a list of decorations from source text.
879
+ *
880
+ * This code treats ", ', and ` as string delimiters, and \ as a string
881
+ * escape. It does not recognize perl's qq() style strings.
882
+ * It has no special handling for double delimiter escapes as in basic, or
883
+ * the tripled delimiters used in python, but should work on those regardless
884
+ * although in those cases a single string literal may be broken up into
885
+ * multiple adjacent string literals.
886
+ *
887
+ * It recognizes C, C++, and shell style comments.
888
+ *
889
+ * @param {Object} options a set of optional parameters.
890
+ * @return {function (JobT)} a function that examines the source code
891
+ * in the input job and builds a decoration list which it attaches to
892
+ * the job.
893
+ */
894
+ function sourceDecorator(options) {
895
+ var shortcutStylePatterns = [], fallthroughStylePatterns = [];
896
+ if (options['tripleQuotedStrings']) {
897
+ // '''multi-line-string''', 'single-line-string', and double-quoted
898
+ shortcutStylePatterns.push(
899
+ [PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
900
+ null, '\'"']);
901
+ } else if (options['multiLineStrings']) {
902
+ // 'multi-line-string', "multi-line-string"
903
+ shortcutStylePatterns.push(
904
+ [PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
905
+ null, '\'"`']);
906
+ } else {
907
+ // 'single-line-string', "single-line-string"
908
+ shortcutStylePatterns.push(
909
+ [PR_STRING,
910
+ /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
911
+ null, '"\'']);
912
+ }
913
+ if (options['verbatimStrings']) {
914
+ // verbatim-string-literal production from the C# grammar. See issue 93.
915
+ fallthroughStylePatterns.push(
916
+ [PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
917
+ }
918
+ var hc = options['hashComments'];
919
+ if (hc) {
920
+ if (options['cStyleComments']) {
921
+ if (hc > 1) { // multiline hash comments
922
+ shortcutStylePatterns.push(
923
+ [PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
924
+ } else {
925
+ // Stop C preprocessor declarations at an unclosed open comment
926
+ shortcutStylePatterns.push(
927
+ [PR_COMMENT, /^#(?:(?:define|e(?:l|nd)if|else|error|ifn?def|include|line|pragma|undef|warning)\b|[^\r\n]*)/,
928
+ null, '#']);
929
+ }
930
+ // #include <stdio.h>
931
+ fallthroughStylePatterns.push(
932
+ [PR_STRING,
933
+ /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
934
+ null]);
935
+ } else {
936
+ shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
937
+ }
938
+ }
939
+ if (options['cStyleComments']) {
940
+ fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
941
+ fallthroughStylePatterns.push(
942
+ [PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
943
+ }
944
+ var regexLiterals = options['regexLiterals'];
945
+ if (regexLiterals) {
946
+ /**
947
+ * @const
948
+ */
949
+ var regexExcls = regexLiterals > 1
950
+ ? '' // Multiline regex literals
951
+ : '\n\r';
952
+ /**
953
+ * @const
954
+ */
955
+ var regexAny = regexExcls ? '.' : '[\\S\\s]';
956
+ /**
957
+ * @const
958
+ */
959
+ var REGEX_LITERAL = (
960
+ // A regular expression literal starts with a slash that is
961
+ // not followed by * or / so that it is not confused with
962
+ // comments.
963
+ '/(?=[^/*' + regexExcls + '])'
964
+ // and then contains any number of raw characters,
965
+ + '(?:[^/\\x5B\\x5C' + regexExcls + ']'
966
+ // escape sequences (\x5C),
967
+ + '|\\x5C' + regexAny
968
+ // or non-nesting character sets (\x5B\x5D);
969
+ + '|\\x5B(?:[^\\x5C\\x5D' + regexExcls + ']'
970
+ + '|\\x5C' + regexAny + ')*(?:\\x5D|$))+'
971
+ // finally closed by a /.
972
+ + '/');
973
+ fallthroughStylePatterns.push(
974
+ ['lang-regex',
975
+ RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
976
+ ]);
977
+ }
978
+
979
+ var types = options['types'];
980
+ if (types) {
981
+ fallthroughStylePatterns.push([PR_TYPE, types]);
982
+ }
983
+
984
+ var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
985
+ if (keywords.length) {
986
+ fallthroughStylePatterns.push(
987
+ [PR_KEYWORD,
988
+ new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
989
+ null]);
990
+ }
991
+
992
+ shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
993
+
994
+ var punctuation =
995
+ // The Bash man page says
996
+
997
+ // A word is a sequence of characters considered as a single
998
+ // unit by GRUB. Words are separated by metacharacters,
999
+ // which are the following plus space, tab, and newline: { }
1000
+ // | & $ ; < >
1001
+ // ...
1002
+
1003
+ // A word beginning with # causes that word and all remaining
1004
+ // characters on that line to be ignored.
1005
+
1006
+ // which means that only a '#' after /(?:^|[{}|&$;<>\s])/ starts a
1007
+ // comment but empirically
1008
+ // $ echo {#}
1009
+ // {#}
1010
+ // $ echo \$#
1011
+ // $#
1012
+ // $ echo }#
1013
+ // }#
1014
+
1015
+ // so /(?:^|[|&;<>\s])/ is more appropriate.
1016
+
1017
+ // http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC3
1018
+ // suggests that this definition is compatible with a
1019
+ // default mode that tries to use a single token definition
1020
+ // to recognize both bash/python style comments and C
1021
+ // preprocessor directives.
1022
+
1023
+ // This definition of punctuation does not include # in the list of
1024
+ // follow-on exclusions, so # will not be broken before if preceeded
1025
+ // by a punctuation character. We could try to exclude # after
1026
+ // [|&;<>] but that doesn't seem to cause many major problems.
1027
+ // If that does turn out to be a problem, we should change the below
1028
+ // when hc is truthy to include # in the run of punctuation characters
1029
+ // only when not followint [|&;<>].
1030
+ '^.[^\\s\\w.$@\'"`/\\\\]*';
1031
+ if (options['regexLiterals']) {
1032
+ punctuation += '(?!\s*\/)';
1033
+ }
1034
+
1035
+ fallthroughStylePatterns.push(
1036
+ // TODO(mikesamuel): recognize non-latin letters and numerals in idents
1037
+ [PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
1038
+ [PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
1039
+ [PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
1040
+ [PR_LITERAL,
1041
+ new RegExp(
1042
+ '^(?:'
1043
+ // A hex number
1044
+ + '0x[a-f0-9]+'
1045
+ // or an octal or decimal number,
1046
+ + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
1047
+ // possibly in scientific notation
1048
+ + '(?:e[+\\-]?\\d+)?'
1049
+ + ')'
1050
+ // with an optional modifier like UL for unsigned long
1051
+ + '[a-z]*', 'i'),
1052
+ null, '0123456789'],
1053
+ // Don't treat escaped quotes in bash as starting strings.
1054
+ // See issue 144.
1055
+ [PR_PLAIN, /^\\[\s\S]?/, null],
1056
+ [PR_PUNCTUATION, new RegExp(punctuation), null]);
1057
+
1058
+ return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
1059
+ }
1060
+
1061
+ var decorateSource = sourceDecorator({
1062
+ 'keywords': ALL_KEYWORDS,
1063
+ 'hashComments': true,
1064
+ 'cStyleComments': true,
1065
+ 'multiLineStrings': true,
1066
+ 'regexLiterals': true
1067
+ });
1068
+
1069
+ /**
1070
+ * Given a DOM subtree, wraps it in a list, and puts each line into its own
1071
+ * list item.
1072
+ *
1073
+ * @param {Node} node modified in place. Its content is pulled into an
1074
+ * HTMLOListElement, and each line is moved into a separate list item.
1075
+ * This requires cloning elements, so the input might not have unique
1076
+ * IDs after numbering.
1077
+ * @param {number|null|boolean} startLineNum
1078
+ * If truthy, coerced to an integer which is the 1-indexed line number
1079
+ * of the first line of code. The number of the first line will be
1080
+ * attached to the list.
1081
+ * @param {boolean} isPreformatted true iff white-space in text nodes should
1082
+ * be treated as significant.
1083
+ */
1084
+ function numberLines(node, startLineNum, isPreformatted) {
1085
+ var nocode = /(?:^|\s)nocode(?:\s|$)/;
1086
+ var lineBreak = /\r\n?|\n/;
1087
+
1088
+ var document = node.ownerDocument;
1089
+
1090
+ var li = document.createElement('li');
1091
+ while (node.firstChild) {
1092
+ li.appendChild(node.firstChild);
1093
+ }
1094
+ // An array of lines. We split below, so this is initialized to one
1095
+ // un-split line.
1096
+ var listItems = [li];
1097
+
1098
+ function walk(node) {
1099
+ var type = node.nodeType;
1100
+ if (type == 1 && !nocode.test(node.className)) { // Element
1101
+ if ('br' === node.nodeName) {
1102
+ breakAfter(node);
1103
+ // Discard the <BR> since it is now flush against a </LI>.
1104
+ if (node.parentNode) {
1105
+ node.parentNode.removeChild(node);
1106
+ }
1107
+ } else {
1108
+ for (var child = node.firstChild; child; child = child.nextSibling) {
1109
+ walk(child);
1110
+ }
1111
+ }
1112
+ } else if ((type == 3 || type == 4) && isPreformatted) { // Text
1113
+ var text = node.nodeValue;
1114
+ var match = text.match(lineBreak);
1115
+ if (match) {
1116
+ var firstLine = text.substring(0, match.index);
1117
+ node.nodeValue = firstLine;
1118
+ var tail = text.substring(match.index + match[0].length);
1119
+ if (tail) {
1120
+ var parent = node.parentNode;
1121
+ parent.insertBefore(
1122
+ document.createTextNode(tail), node.nextSibling);
1123
+ }
1124
+ breakAfter(node);
1125
+ if (!firstLine) {
1126
+ // Don't leave blank text nodes in the DOM.
1127
+ node.parentNode.removeChild(node);
1128
+ }
1129
+ }
1130
+ }
1131
+ }
1132
+
1133
+ // Split a line after the given node.
1134
+ function breakAfter(lineEndNode) {
1135
+ // If there's nothing to the right, then we can skip ending the line
1136
+ // here, and move root-wards since splitting just before an end-tag
1137
+ // would require us to create a bunch of empty copies.
1138
+ while (!lineEndNode.nextSibling) {
1139
+ lineEndNode = lineEndNode.parentNode;
1140
+ if (!lineEndNode) { return; }
1141
+ }
1142
+
1143
+ function breakLeftOf(limit, copy) {
1144
+ // Clone shallowly if this node needs to be on both sides of the break.
1145
+ var rightSide = copy ? limit.cloneNode(false) : limit;
1146
+ var parent = limit.parentNode;
1147
+ if (parent) {
1148
+ // We clone the parent chain.
1149
+ // This helps us resurrect important styling elements that cross lines.
1150
+ // E.g. in <i>Foo<br>Bar</i>
1151
+ // should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
1152
+ var parentClone = breakLeftOf(parent, 1);
1153
+ // Move the clone and everything to the right of the original
1154
+ // onto the cloned parent.
1155
+ var next = limit.nextSibling;
1156
+ parentClone.appendChild(rightSide);
1157
+ for (var sibling = next; sibling; sibling = next) {
1158
+ next = sibling.nextSibling;
1159
+ parentClone.appendChild(sibling);
1160
+ }
1161
+ }
1162
+ return rightSide;
1163
+ }
1164
+
1165
+ var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
1166
+
1167
+ // Walk the parent chain until we reach an unattached LI.
1168
+ for (var parent;
1169
+ // Check nodeType since IE invents document fragments.
1170
+ (parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
1171
+ copiedListItem = parent;
1172
+ }
1173
+ // Put it on the list of lines for later processing.
1174
+ listItems.push(copiedListItem);
1175
+ }
1176
+
1177
+ // Split lines while there are lines left to split.
1178
+ for (var i = 0; // Number of lines that have been split so far.
1179
+ i < listItems.length; // length updated by breakAfter calls.
1180
+ ++i) {
1181
+ walk(listItems[i]);
1182
+ }
1183
+
1184
+ // Make sure numeric indices show correctly.
1185
+ if (startLineNum === (startLineNum|0)) {
1186
+ listItems[0].setAttribute('value', startLineNum);
1187
+ }
1188
+
1189
+ var ol = document.createElement('ol');
1190
+ ol.className = 'linenums';
1191
+ var offset = Math.max(0, ((startLineNum - 1 /* zero index */)) | 0) || 0;
1192
+ for (var i = 0, n = listItems.length; i < n; ++i) {
1193
+ li = listItems[i];
1194
+ // Stick a class on the LIs so that stylesheets can
1195
+ // color odd/even rows, or any other row pattern that
1196
+ // is co-prime with 10.
1197
+ li.className = 'L' + ((i + offset) % 10);
1198
+ if (!li.firstChild) {
1199
+ li.appendChild(document.createTextNode('\xA0'));
1200
+ }
1201
+ ol.appendChild(li);
1202
+ }
1203
+
1204
+ node.appendChild(ol);
1205
+ }
1206
+
1207
+ /**
1208
+ * Breaks {@code job.sourceCode} around style boundaries in
1209
+ * {@code job.decorations} and modifies {@code job.sourceNode} in place.
1210
+ * @param {JobT} job
1211
+ * @private
1212
+ */
1213
+ function recombineTagsAndDecorations(job) {
1214
+ var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
1215
+ isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
1216
+ var newlineRe = /\n/g;
1217
+
1218
+ var source = job.sourceCode;
1219
+ var sourceLength = source.length;
1220
+ // Index into source after the last code-unit recombined.
1221
+ var sourceIndex = 0;
1222
+
1223
+ var spans = job.spans;
1224
+ var nSpans = spans.length;
1225
+ // Index into spans after the last span which ends at or before sourceIndex.
1226
+ var spanIndex = 0;
1227
+
1228
+ var decorations = job.decorations;
1229
+ var nDecorations = decorations.length;
1230
+ // Index into decorations after the last decoration which ends at or before
1231
+ // sourceIndex.
1232
+ var decorationIndex = 0;
1233
+
1234
+ // Remove all zero-length decorations.
1235
+ decorations[nDecorations] = sourceLength;
1236
+ var decPos, i;
1237
+ for (i = decPos = 0; i < nDecorations;) {
1238
+ if (decorations[i] !== decorations[i + 2]) {
1239
+ decorations[decPos++] = decorations[i++];
1240
+ decorations[decPos++] = decorations[i++];
1241
+ } else {
1242
+ i += 2;
1243
+ }
1244
+ }
1245
+ nDecorations = decPos;
1246
+
1247
+ // Simplify decorations.
1248
+ for (i = decPos = 0; i < nDecorations;) {
1249
+ var startPos = decorations[i];
1250
+ // Conflate all adjacent decorations that use the same style.
1251
+ var startDec = decorations[i + 1];
1252
+ var end = i + 2;
1253
+ while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
1254
+ end += 2;
1255
+ }
1256
+ decorations[decPos++] = startPos;
1257
+ decorations[decPos++] = startDec;
1258
+ i = end;
1259
+ }
1260
+
1261
+ nDecorations = decorations.length = decPos;
1262
+
1263
+ var sourceNode = job.sourceNode;
1264
+ var oldDisplay = "";
1265
+ if (sourceNode) {
1266
+ oldDisplay = sourceNode.style.display;
1267
+ sourceNode.style.display = 'none';
1268
+ }
1269
+ try {
1270
+ var decoration = null;
1271
+ while (spanIndex < nSpans) {
1272
+ var spanStart = spans[spanIndex];
1273
+ var spanEnd = /** @type{number} */ (spans[spanIndex + 2])
1274
+ || sourceLength;
1275
+
1276
+ var decEnd = decorations[decorationIndex + 2] || sourceLength;
1277
+
1278
+ var end = Math.min(spanEnd, decEnd);
1279
+
1280
+ var textNode = /** @type{Node} */ (spans[spanIndex + 1]);
1281
+ var styledText;
1282
+ if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s
1283
+ // Don't introduce spans around empty text nodes.
1284
+ && (styledText = source.substring(sourceIndex, end))) {
1285
+ // This may seem bizarre, and it is. Emitting LF on IE causes the
1286
+ // code to display with spaces instead of line breaks.
1287
+ // Emitting Windows standard issue linebreaks (CRLF) causes a blank
1288
+ // space to appear at the beginning of every line but the first.
1289
+ // Emitting an old Mac OS 9 line separator makes everything spiffy.
1290
+ if (isIE8OrEarlier) {
1291
+ styledText = styledText.replace(newlineRe, '\r');
1292
+ }
1293
+ textNode.nodeValue = styledText;
1294
+ var document = textNode.ownerDocument;
1295
+ var span = document.createElement('span');
1296
+ span.className = decorations[decorationIndex + 1];
1297
+ var parentNode = textNode.parentNode;
1298
+ parentNode.replaceChild(span, textNode);
1299
+ span.appendChild(textNode);
1300
+ if (sourceIndex < spanEnd) { // Split off a text node.
1301
+ spans[spanIndex + 1] = textNode
1302
+ // TODO: Possibly optimize by using '' if there's no flicker.
1303
+ = document.createTextNode(source.substring(end, spanEnd));
1304
+ parentNode.insertBefore(textNode, span.nextSibling);
1305
+ }
1306
+ }
1307
+
1308
+ sourceIndex = end;
1309
+
1310
+ if (sourceIndex >= spanEnd) {
1311
+ spanIndex += 2;
1312
+ }
1313
+ if (sourceIndex >= decEnd) {
1314
+ decorationIndex += 2;
1315
+ }
1316
+ }
1317
+ } finally {
1318
+ if (sourceNode) {
1319
+ sourceNode.style.display = oldDisplay;
1320
+ }
1321
+ }
1322
+ }
1323
+
1324
+ /** Maps language-specific file extensions to handlers. */
1325
+ var langHandlerRegistry = {};
1326
+ /** Register a language handler for the given file extensions.
1327
+ * @param {function (JobT)} handler a function from source code to a list
1328
+ * of decorations. Takes a single argument job which describes the
1329
+ * state of the computation and attaches the decorations to it.
1330
+ * @param {Array.<string>} fileExtensions
1331
+ */
1332
+ function registerLangHandler(handler, fileExtensions) {
1333
+ for (var i = fileExtensions.length; --i >= 0;) {
1334
+ var ext = fileExtensions[i];
1335
+ if (!langHandlerRegistry.hasOwnProperty(ext)) {
1336
+ langHandlerRegistry[ext] = handler;
1337
+ } else if (win['console']) {
1338
+ console['warn']('cannot override language handler %s', ext);
1339
+ }
1340
+ }
1341
+ }
1342
+ function langHandlerForExtension(extension, source) {
1343
+ if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
1344
+ // Treat it as markup if the first non whitespace character is a < and
1345
+ // the last non-whitespace character is a >.
1346
+ extension = /^\s*</.test(source)
1347
+ ? 'default-markup'
1348
+ : 'default-code';
1349
+ }
1350
+ return langHandlerRegistry[extension];
1351
+ }
1352
+ registerLangHandler(decorateSource, ['default-code']);
1353
+ registerLangHandler(
1354
+ createSimpleLexer(
1355
+ [],
1356
+ [
1357
+ [PR_PLAIN, /^[^<?]+/],
1358
+ [PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
1359
+ [PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
1360
+ // Unescaped content in an unknown language
1361
+ ['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
1362
+ ['lang-', /^<%([\s\S]+?)(?:%>|$)/],
1363
+ [PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
1364
+ ['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
1365
+ // Unescaped content in javascript. (Or possibly vbscript).
1366
+ ['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
1367
+ // Contains unescaped stylesheet content
1368
+ ['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
1369
+ ['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
1370
+ ]),
1371
+ ['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
1372
+ registerLangHandler(
1373
+ createSimpleLexer(
1374
+ [
1375
+ [PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
1376
+ [PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
1377
+ ],
1378
+ [
1379
+ [PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
1380
+ [PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
1381
+ ['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
1382
+ [PR_PUNCTUATION, /^[=<>\/]+/],
1383
+ ['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
1384
+ ['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
1385
+ ['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
1386
+ ['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
1387
+ ['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
1388
+ ['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
1389
+ ]),
1390
+ ['in.tag']);
1391
+ registerLangHandler(
1392
+ createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
1393
+ registerLangHandler(sourceDecorator({
1394
+ 'keywords': CPP_KEYWORDS,
1395
+ 'hashComments': true,
1396
+ 'cStyleComments': true,
1397
+ 'types': C_TYPES
1398
+ }), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
1399
+ registerLangHandler(sourceDecorator({
1400
+ 'keywords': 'null,true,false'
1401
+ }), ['json']);
1402
+ registerLangHandler(sourceDecorator({
1403
+ 'keywords': CSHARP_KEYWORDS,
1404
+ 'hashComments': true,
1405
+ 'cStyleComments': true,
1406
+ 'verbatimStrings': true,
1407
+ 'types': C_TYPES
1408
+ }), ['cs']);
1409
+ registerLangHandler(sourceDecorator({
1410
+ 'keywords': JAVA_KEYWORDS,
1411
+ 'cStyleComments': true
1412
+ }), ['java']);
1413
+ registerLangHandler(sourceDecorator({
1414
+ 'keywords': SH_KEYWORDS,
1415
+ 'hashComments': true,
1416
+ 'multiLineStrings': true
1417
+ }), ['bash', 'bsh', 'csh', 'sh']);
1418
+ registerLangHandler(sourceDecorator({
1419
+ 'keywords': PYTHON_KEYWORDS,
1420
+ 'hashComments': true,
1421
+ 'multiLineStrings': true,
1422
+ 'tripleQuotedStrings': true
1423
+ }), ['cv', 'py', 'python']);
1424
+ registerLangHandler(sourceDecorator({
1425
+ 'keywords': PERL_KEYWORDS,
1426
+ 'hashComments': true,
1427
+ 'multiLineStrings': true,
1428
+ 'regexLiterals': 2 // multiline regex literals
1429
+ }), ['perl', 'pl', 'pm']);
1430
+ registerLangHandler(sourceDecorator({
1431
+ 'keywords': RUBY_KEYWORDS,
1432
+ 'hashComments': true,
1433
+ 'multiLineStrings': true,
1434
+ 'regexLiterals': true
1435
+ }), ['rb', 'ruby']);
1436
+ registerLangHandler(sourceDecorator({
1437
+ 'keywords': JSCRIPT_KEYWORDS,
1438
+ 'cStyleComments': true,
1439
+ 'regexLiterals': true
1440
+ }), ['javascript', 'js', 'ts', 'typescript']);
1441
+ registerLangHandler(sourceDecorator({
1442
+ 'keywords': COFFEE_KEYWORDS,
1443
+ 'hashComments': 3, // ### style block comments
1444
+ 'cStyleComments': true,
1445
+ 'multilineStrings': true,
1446
+ 'tripleQuotedStrings': true,
1447
+ 'regexLiterals': true
1448
+ }), ['coffee']);
1449
+ registerLangHandler(
1450
+ createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
1451
+
1452
+ /** @param {JobT} job */
1453
+ function applyDecorator(job) {
1454
+ var opt_langExtension = job.langExtension;
1455
+
1456
+ try {
1457
+ // Extract tags, and convert the source code to plain text.
1458
+ var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
1459
+ /** Plain text. @type {string} */
1460
+ var source = sourceAndSpans.sourceCode;
1461
+ job.sourceCode = source;
1462
+ job.spans = sourceAndSpans.spans;
1463
+ job.basePos = 0;
1464
+
1465
+ // Apply the appropriate language handler
1466
+ langHandlerForExtension(opt_langExtension, source)(job);
1467
+
1468
+ // Integrate the decorations and tags back into the source code,
1469
+ // modifying the sourceNode in place.
1470
+ recombineTagsAndDecorations(job);
1471
+ } catch (e) {
1472
+ if (win['console']) {
1473
+ console['log'](e && e['stack'] || e);
1474
+ }
1475
+ }
1476
+ }
1477
+
1478
+ /**
1479
+ * Pretty print a chunk of code.
1480
+ * @param sourceCodeHtml {string} The HTML to pretty print.
1481
+ * @param opt_langExtension {string} The language name to use.
1482
+ * Typically, a filename extension like 'cpp' or 'java'.
1483
+ * @param opt_numberLines {number|boolean} True to number lines,
1484
+ * or the 1-indexed number of the first line in sourceCodeHtml.
1485
+ */
1486
+ function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
1487
+ /** @type{number|boolean} */
1488
+ var nl = opt_numberLines || false;
1489
+ /** @type{string|null} */
1490
+ var langExtension = opt_langExtension || null;
1491
+ /** @type{!Element} */
1492
+ var container = document.createElement('div');
1493
+ // This could cause images to load and onload listeners to fire.
1494
+ // E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
1495
+ // We assume that the inner HTML is from a trusted source.
1496
+ // The pre-tag is required for IE8 which strips newlines from innerHTML
1497
+ // when it is injected into a <pre> tag.
1498
+ // http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
1499
+ // http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
1500
+ container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
1501
+ container = /** @type{!Element} */(container.firstChild);
1502
+ if (nl) {
1503
+ numberLines(container, nl, true);
1504
+ }
1505
+
1506
+ /** @type{JobT} */
1507
+ var job = {
1508
+ langExtension: langExtension,
1509
+ numberLines: nl,
1510
+ sourceNode: container,
1511
+ pre: 1,
1512
+ sourceCode: null,
1513
+ basePos: null,
1514
+ spans: null,
1515
+ decorations: null
1516
+ };
1517
+ applyDecorator(job);
1518
+ return container.innerHTML;
1519
+ }
1520
+
1521
+ /**
1522
+ * Find all the {@code <pre>} and {@code <code>} tags in the DOM with
1523
+ * {@code class=prettyprint} and prettify them.
1524
+ *
1525
+ * @param {Function} opt_whenDone called when prettifying is done.
1526
+ * @param {HTMLElement|HTMLDocument} opt_root an element or document
1527
+ * containing all the elements to pretty print.
1528
+ * Defaults to {@code document.body}.
1529
+ */
1530
+ function $prettyPrint(opt_whenDone, opt_root) {
1531
+ var root = opt_root || document.body;
1532
+ var doc = root.ownerDocument || document;
1533
+ function byTagName(tn) { return root.getElementsByTagName(tn); }
1534
+ // fetch a list of nodes to rewrite
1535
+ var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
1536
+ var elements = [];
1537
+ for (var i = 0; i < codeSegments.length; ++i) {
1538
+ for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
1539
+ elements.push(codeSegments[i][j]);
1540
+ }
1541
+ }
1542
+ codeSegments = null;
1543
+
1544
+ var clock = Date;
1545
+ if (!clock['now']) {
1546
+ clock = { 'now': function () { return +(new Date); } };
1547
+ }
1548
+
1549
+ // The loop is broken into a series of continuations to make sure that we
1550
+ // don't make the browser unresponsive when rewriting a large page.
1551
+ var k = 0;
1552
+
1553
+ var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
1554
+ var prettyPrintRe = /\bprettyprint\b/;
1555
+ var prettyPrintedRe = /\bprettyprinted\b/;
1556
+ var preformattedTagNameRe = /pre|xmp/i;
1557
+ var codeRe = /^code$/i;
1558
+ var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
1559
+ var EMPTY = {};
1560
+
1561
+ function doWork() {
1562
+ var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
1563
+ clock['now']() + 250 /* ms */ :
1564
+ Infinity);
1565
+ for (; k < elements.length && clock['now']() < endTime; k++) {
1566
+ var cs = elements[k];
1567
+
1568
+ // Look for a preceding comment like
1569
+ // <?prettify lang="..." linenums="..."?>
1570
+ var attrs = EMPTY;
1571
+ {
1572
+ for (var preceder = cs; (preceder = preceder.previousSibling);) {
1573
+ var nt = preceder.nodeType;
1574
+ // <?foo?> is parsed by HTML 5 to a comment node (8)
1575
+ // like <!--?foo?-->, but in XML is a processing instruction
1576
+ var value = (nt === 7 || nt === 8) && preceder.nodeValue;
1577
+ if (value
1578
+ ? !/^\??prettify\b/.test(value)
1579
+ : (nt !== 3 || /\S/.test(preceder.nodeValue))) {
1580
+ // Skip over white-space text nodes but not others.
1581
+ break;
1582
+ }
1583
+ if (value) {
1584
+ attrs = {};
1585
+ value.replace(
1586
+ /\b(\w+)=([\w:.%+-]+)/g,
1587
+ function (_, name, value) { attrs[name] = value; });
1588
+ break;
1589
+ }
1590
+ }
1591
+ }
1592
+
1593
+ var className = cs.className;
1594
+ if ((attrs !== EMPTY || prettyPrintRe.test(className))
1595
+ // Don't redo this if we've already done it.
1596
+ // This allows recalling pretty print to just prettyprint elements
1597
+ // that have been added to the page since last call.
1598
+ && !prettyPrintedRe.test(className)) {
1599
+
1600
+ // make sure this is not nested in an already prettified element
1601
+ var nested = false;
1602
+ for (var p = cs.parentNode; p; p = p.parentNode) {
1603
+ var tn = p.tagName;
1604
+ if (preCodeXmpRe.test(tn)
1605
+ && p.className && prettyPrintRe.test(p.className)) {
1606
+ nested = true;
1607
+ break;
1608
+ }
1609
+ }
1610
+ if (!nested) {
1611
+ // Mark done. If we fail to prettyprint for whatever reason,
1612
+ // we shouldn't try again.
1613
+ cs.className += ' prettyprinted';
1614
+
1615
+ // If the classes includes a language extensions, use it.
1616
+ // Language extensions can be specified like
1617
+ // <pre class="prettyprint lang-cpp">
1618
+ // the language extension "cpp" is used to find a language handler
1619
+ // as passed to PR.registerLangHandler.
1620
+ // HTML5 recommends that a language be specified using "language-"
1621
+ // as the prefix instead. Google Code Prettify supports both.
1622
+ // http://dev.w3.org/html5/spec-author-view/the-code-element.html
1623
+ var langExtension = attrs['lang'];
1624
+ if (!langExtension) {
1625
+ langExtension = className.match(langExtensionRe);
1626
+ // Support <pre class="prettyprint"><code class="language-c">
1627
+ var wrapper;
1628
+ if (!langExtension && (wrapper = childContentWrapper(cs))
1629
+ && codeRe.test(wrapper.tagName)) {
1630
+ langExtension = wrapper.className.match(langExtensionRe);
1631
+ }
1632
+
1633
+ if (langExtension) { langExtension = langExtension[1]; }
1634
+ }
1635
+
1636
+ var preformatted;
1637
+ if (preformattedTagNameRe.test(cs.tagName)) {
1638
+ preformatted = 1;
1639
+ } else {
1640
+ var currentStyle = cs['currentStyle'];
1641
+ var defaultView = doc.defaultView;
1642
+ var whitespace = (
1643
+ currentStyle
1644
+ ? currentStyle['whiteSpace']
1645
+ : (defaultView
1646
+ && defaultView.getComputedStyle)
1647
+ ? defaultView.getComputedStyle(cs, null)
1648
+ .getPropertyValue('white-space')
1649
+ : 0);
1650
+ preformatted = whitespace
1651
+ && 'pre' === whitespace.substring(0, 3);
1652
+ }
1653
+
1654
+ // Look for a class like linenums or linenums:<n> where <n> is the
1655
+ // 1-indexed number of the first line.
1656
+ var lineNums = attrs['linenums'];
1657
+ if (!(lineNums = lineNums === 'true' || +lineNums)) {
1658
+ lineNums = className.match(/\blinenums\b(?::(\d+))?/);
1659
+ lineNums =
1660
+ lineNums
1661
+ ? lineNums[1] && lineNums[1].length
1662
+ ? +lineNums[1] : true
1663
+ : false;
1664
+ }
1665
+ if (lineNums) { numberLines(cs, lineNums, preformatted); }
1666
+
1667
+ // do the pretty printing
1668
+ var prettyPrintingJob = {
1669
+ langExtension: langExtension,
1670
+ sourceNode: cs,
1671
+ numberLines: lineNums,
1672
+ pre: preformatted,
1673
+ sourceCode: null,
1674
+ basePos: null,
1675
+ spans: null,
1676
+ decorations: null
1677
+ };
1678
+ applyDecorator(prettyPrintingJob);
1679
+ }
1680
+ }
1681
+ }
1682
+ if (k < elements.length) {
1683
+ // finish up in a continuation
1684
+ win.setTimeout(doWork, 250);
1685
+ } else if ('function' === typeof opt_whenDone) {
1686
+ opt_whenDone();
1687
+ }
1688
+ }
1689
+
1690
+ doWork();
1691
+ }
1692
+
1693
+ /**
1694
+ * Contains functions for creating and registering new language handlers.
1695
+ * @type {Object}
1696
+ */
1697
+ var PR = win['PR'] = {
1698
+ 'createSimpleLexer': createSimpleLexer,
1699
+ 'registerLangHandler': registerLangHandler,
1700
+ 'sourceDecorator': sourceDecorator,
1701
+ 'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
1702
+ 'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
1703
+ 'PR_COMMENT': PR_COMMENT,
1704
+ 'PR_DECLARATION': PR_DECLARATION,
1705
+ 'PR_KEYWORD': PR_KEYWORD,
1706
+ 'PR_LITERAL': PR_LITERAL,
1707
+ 'PR_NOCODE': PR_NOCODE,
1708
+ 'PR_PLAIN': PR_PLAIN,
1709
+ 'PR_PUNCTUATION': PR_PUNCTUATION,
1710
+ 'PR_SOURCE': PR_SOURCE,
1711
+ 'PR_STRING': PR_STRING,
1712
+ 'PR_TAG': PR_TAG,
1713
+ 'PR_TYPE': PR_TYPE,
1714
+ 'prettyPrintOne':
1715
+ IN_GLOBAL_SCOPE
1716
+ ? (win['prettyPrintOne'] = $prettyPrintOne)
1717
+ : (prettyPrintOne = $prettyPrintOne),
1718
+ 'prettyPrint': prettyPrint =
1719
+ IN_GLOBAL_SCOPE
1720
+ ? (win['prettyPrint'] = $prettyPrint)
1721
+ : (prettyPrint = $prettyPrint)
1722
+ };
1723
+
1724
+ // Make PR available via the Asynchronous Module Definition (AMD) API.
1725
+ // Per https://github.com/amdjs/amdjs-api/wiki/AMD:
1726
+ // The Asynchronous Module Definition (AMD) API specifies a
1727
+ // mechanism for defining modules such that the module and its
1728
+ // dependencies can be asynchronously loaded.
1729
+ // ...
1730
+ // To allow a clear indicator that a global define function (as
1731
+ // needed for script src browser loading) conforms to the AMD API,
1732
+ // any global define function SHOULD have a property called "amd"
1733
+ // whose value is an object. This helps avoid conflict with any
1734
+ // other existing JavaScript code that could have defined a define()
1735
+ // function that does not conform to the AMD API.
1736
+ var define = win['define'];
1737
+ if (typeof define === "function" && define['amd']) {
1738
+ define("google-code-prettify", [], function () {
1739
+ return PR;
1740
+ });
1741
+ }
1742
+ })();