-
Notifications
You must be signed in to change notification settings - Fork 0
/
prettify.js
1432 lines (1341 loc) · 43.7 KB
/
prettify.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
*
* The lexer should work on a number of languages including C and friends,
* Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles.
* It works passably on Ruby, PHP and Awk and a decent subset of Perl, but,
* because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or
* CAML-like languages.
*
* If there's a language not mentioned here, then I don't know it, and don't
* know whether it works. If it has a C-like, Bash-like, or XML-like syntax
* then it should work passably.
*
* Usage:
* 1) include this source file in an html page via
* <script type="text/javascript" src="/path/to/prettify.js"></script>
* 2) define style rules. See the example page for examples.
* 3) mark the <pre> and <code> tags in your source with class=prettyprint.
* You can also use the (html deprecated) <xmp> tag, but the pretty printer
* needs to do more substantial DOM manipulations to support that, so some
* css styles may not be preserved.
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in.
*
* Change log:
* cbeust, 2006/08/22
* Java annotations (start with "@") are now captured as literals ("lit")
*/
var PR_keywords = new Object();
/** initialize the keyword list for our target languages. */
(function () {
var CPP_KEYWORDS = (
"bool break case catch char class const const_cast continue default " +
"delete deprecated dllexport dllimport do double dynamic_cast else enum " +
"explicit extern false float for friend goto if inline int long mutable " +
"naked namespace new noinline noreturn nothrow novtable operator private " +
"property protected public register reinterpret_cast return selectany " +
"short signed sizeof static static_cast struct switch template this " +
"thread throw true try typedef typeid typename union unsigned using " +
"declaration, using directive uuid virtual void volatile while typeof");
var JAVA_KEYWORDS = (
"abstract default goto package synchronized boolean do if private this " +
"break double implements protected throw byte else import public throws " +
"case enum instanceof return transient catch extends int short try char " +
"final interface static void class finally long strictfp volatile const " +
"float native super while continue for new switch");
var PYTHON_KEYWORDS = (
"and assert break class continue def del elif else except exec finally " +
"for from global if import in is lambda not or pass print raise return " +
"try while yield False True None");
var JSCRIPT_KEYWORDS = (
"abstract boolean break byte case catch char class const continue " +
"debugger default delete do double else enum export extends false final " +
"finally float for function goto if implements import in instanceof int " +
"interface long native new null package private protected public return " +
"short static super switch synchronized this throw throws transient " +
"true try typeof var void volatile while with NaN Infinity");
var PERL_KEYWORDS = (
"foreach require sub unless until use elsif BEGIN END");
var SH_KEYWORDS = (
"if then do done else fi end");
var RUBY_KEYWORDS = (
"if then elsif else end begin do rescue ensure while for class module " +
"def yield raise until unless and or not when case super undef break " +
"next redo retry in return alias defined");
var KEYWORDS = [CPP_KEYWORDS, JAVA_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS,
PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
for (var k = 0; k < KEYWORDS.length; k++) {
var kw = KEYWORDS[k].split(' ');
for (var i = 0; i < kw.length; i++) {
if (kw[i]) { PR_keywords[kw[i]] = true; }
}
}
}).call(this);
// token style names. correspond to css classes
/** token style for a string literal */
var PR_STRING = 'str';
/** token style for a keyword */
var PR_KEYWORD = 'kwd';
/** token style for a comment */
var PR_COMMENT = 'com';
/** token style for a type */
var PR_TYPE = 'typ';
/** token style for a literal value. e.g. 1, null, true. */
var PR_LITERAL = 'lit';
/** token style for a punctuation string. */
var PR_PUNCTUATION = 'pun';
/** token style for a punctuation string. */
var PR_PLAIN = 'pln';
/** token style for an sgml tag. */
var PR_TAG = 'tag';
/** token style for a markup declaration such as a DOCTYPE. */
var PR_DECLARATION = 'dec';
/** token style for embedded source. */
var PR_SOURCE = 'src';
/** token style for an sgml attribute name. */
var PR_ATTRIB_NAME = 'atn';
/** token style for an sgml attribute value. */
var PR_ATTRIB_VALUE = 'atv';
/** the position of the end of a token during. A division of a string into
* n tokens can be represented as a series n - 1 token ends, as long as
* runs of whitespace warrant their own token.
* @private
*/
function PR_TokenEnd(end, style) {
if (undefined === style) { throw new Error('BAD'); }
if ('number' != typeof(end)) { throw new Error('BAD'); }
this.end = end;
this.style = style;
}
PR_TokenEnd.prototype.toString = function () {
return '[PR_TokenEnd ' + this.end +
(this.style ? ':' + this.style : '') + ']';
};
/** a chunk of text with a style. These are used to represent both the output
* from the lexing functions as well as intermediate results.
* @constructor
* @param token the token text
* @param style one of the token styles defined in designdoc-template, or null
* for a styleless token, such as an embedded html tag.
* @private
*/
function PR_Token(token, style) {
if (undefined === style) { throw new Error('BAD'); }
this.token = token;
this.style = style;
}
PR_Token.prototype.toString = function () {
return '[PR_Token ' + this.token + (this.style ? ':' + this.style : '') + ']';
};
/** a helper class that decodes common html entities used to escape source and
* markup punctuation characters in html.
* @constructor
* @private
*/
function PR_DecodeHelper() {
this.next = 0;
this.ch = '\0';
}
PR_DecodeHelper.prototype.decode = function (s, i) {
var next = i + 1;
var ch = s.charAt(i);
if ('&' == ch) {
var semi = s.indexOf(';', next);
if (semi >= 0 && semi < next + 4) {
var entityName = s.substring(next, semi).toLowerCase();
next = semi + 1;
if ('lt' == entityName) {
ch = '<';
} else if ('gt' == entityName) {
ch = '>';
} else if ('quot' == entityName) {
ch = '"';
} else if ('apos' == entityName) {
ch = '\'';
} else if ('amp' == entityName) {
ch = '&';
} else {
next = i + 1;
}
}
}
this.next = next;
this.ch = ch;
return this.ch;
}
// some string utilities
function PR_isWordChar(ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
function PR_isIdentifierStart(ch) {
return PR_isWordChar(ch) || ch == '_' || ch == '$' || ch == '@';
}
function PR_isIdentifierPart(ch) {
return PR_isIdentifierStart(ch) || PR_isDigitChar(ch);
}
function PR_isSpaceChar(ch) {
return "\t \r\n".indexOf(ch) >= 0;
}
function PR_isDigitChar(ch) {
return ch >= '0' && ch <= '9';
}
function PR_trim(s) {
var i = 0, j = s.length - 1;
while (i <= j && PR_isSpaceChar(s.charAt(i))) { ++i; }
while (j > i && PR_isSpaceChar(s.charAt(j))) { --j; }
return s.substring(i, j + 1);
}
function PR_startsWith(s, prefix) {
return s.length >= prefix.length && prefix == s.substring(0, prefix.length);
}
function PR_endsWith(s, suffix) {
return s.length >= suffix.length &&
suffix == s.substring(s.length - suffix.length, s.length);
}
/** true iff prefix matches the first prefix characters in chars[0:len].
* @private
*/
function PR_prefixMatch(chars, len, prefix) {
if (len < prefix.length) { return false; }
for (var i = 0, n = prefix.length; i < n; ++i) {
if (prefix.charAt(i) != chars[i]) { return false; }
}
return true;
}
/** like textToHtml but escapes double quotes to be attribute safe. */
function PR_attribToHtml(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\"/g, '"')
.replace(/\xa0/, ' ');
}
/** escapest html special characters to html. */
function PR_textToHtml(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\xa0/g, ' ');
}
/** is the given node's innerHTML normally unescaped? */
function PR_isRawContent(node) {
return 'XMP' == node.tagName;
}
var PR_innerHtmlWorks = null;
function PR_getInnerHtml(node) {
// inner html is hopelessly broken in Safari 2.0.4 when the content is
// an html description of well formed XML and the containing tag is a PRE
// tag, so we detect that case and emulate innerHTML.
if (null == PR_innerHtmlWorks) {
var testNode = document.createElement('PRE');
testNode.appendChild(
document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
}
if (PR_innerHtmlWorks) {
var content = node.innerHTML;
// XMP tags contain unescaped entities so require special handling.
if (PR_isRawContent(node)) {
content = PR_textToHtml(content);
}
return content;
}
var out = [];
for (var child = node.firstChild; child; child = child.nextSibling) {
PR_normalizedHtml(child, out);
}
return out.join('');
}
/**
* walks the DOM returning a properly escaped version of innerHTML.
*/
function PR_normalizedHtml(node, out) {
switch (node.nodeType) {
case 1: // an element
var name = node.tagName.toLowerCase();
out.push('\074', name);
for (var i = 0; i < node.attributes.length; ++i) {
var attr = node.attributes[i];
if (!attr.specified) { continue; }
out.push(' ');
PR_normalizedHtml(attr, out);
}
out.push('>');
for (var child = node.firstChild; child; child = child.nextSibling) {
PR_normalizedHtml(child, out);
}
if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
out.push('<\/', name, '>');
}
break;
case 2: // an attribute
out.push(node.name.toLowerCase(), '="', PR_attribToHtml(node.value), '"');
break;
case 3: case 4: // text
out.push(PR_textToHtml(node.nodeValue));
break;
}
}
/** split markup into chunks of html tags (style null) and
* plain text (style {@link #PR_PLAIN}).
*
* @param s a String of html.
* @return an Array of PR_Tokens of style PR_PLAIN and null.
* @private
*/
function PR_chunkify(s) {
var chunks = new Array();
var state = 0;
var start = 0;
var pos = -1;
for (var i = 0, n = s.length; i < n; ++i) {
var ch = s.charAt(i);
switch (state) {
case 0:
if ('<' == ch) { state = 1; }
break;
case 1:
pos = i - 1;
if ('/' == ch) { state = 2; }
else if (PR_isWordChar(ch)) { state = 3; }
else if ('<' == ch) { state = 1; }
else { state = 0; }
break;
case 2:
if (PR_isWordChar(ch)) { state = 3; }
else if ('<' == ch) { state = 1; }
else { state = 0; }
break;
case 3:
if ('>' == ch) {
if (pos > start) {
chunks.push(new PR_Token(s.substring(start, pos), PR_PLAIN));
}
chunks.push(new PR_Token(s.substring(pos, i + 1), null));
start = i + 1;
pos = -1;
state = 0;
}
break;
}
}
if (s.length > start) {
chunks.push(new PR_Token(s.substring(start, s.length), PR_PLAIN));
}
return chunks;
}
/** splits chunks around entities.
* @private
*/
function PR_splitEntities(chunks) {
var chunksOut = new Array();
var state = 0;
for (var ci = 0, nc = chunks.length; ci < nc; ++ci) {
var chunk = chunks[ci];
if (PR_PLAIN != chunk.style) {
chunksOut.push(chunk);
continue;
}
var s = chunk.token;
var pos = 0;
var start;
for (var i = 0; i < s.length; ++i) {
var ch = s.charAt(i);
switch (state) {
case 0:
if ('&' == ch) { state = 1; }
break;
case 1:
if ('#' == ch || PR_isWordChar(ch)) {
start = i - 1;
state = 2;
} else {
state = 0;
}
break;
case 2:
if (';' == ch) {
if (start > pos) {
chunksOut.push(
new PR_Token(s.substring(pos, start), chunk.style));
}
chunksOut.push(new PR_Token(s.substring(start, i + 1), null));
pos = i + 1;
state = 0;
}
break;
}
}
if (s.length > pos) {
chunksOut.push(pos ?
new PR_Token(s.substring(pos, s.length), chunk.style) :
chunk);
}
}
return chunksOut;
}
/** walk the tokenEnds list and the chunk list in parallel to generate a list
* of split tokens.
* @private
*/
function PR_splitChunks(chunks, tokenEnds) {
var tokens = new Array(); // the output
var ci = 0; // index into chunks
// position of beginning of amount written so far in absolute space.
var posAbs = 0;
// position of amount written so far in chunk space
var posChunk = 0;
// current chunk
var chunk = new PR_Token('', null);
for (var ei = 0, ne = tokenEnds.length; ei < ne; ++ei) {
var tokenEnd = tokenEnds[ei];
var end = tokenEnd.end;
var tokLen = end - posAbs;
var remainingInChunk = chunk.token.length - posChunk;
while (remainingInChunk <= tokLen) {
if (remainingInChunk > 0) {
tokens.push(
new PR_Token(chunk.token.substring(posChunk, chunk.token.length),
null == chunk.style ? null : tokenEnd.style));
}
posAbs += remainingInChunk;
posChunk = 0;
if (ci < chunks.length) { chunk = chunks[ci++]; }
tokLen = end - posAbs;
remainingInChunk = chunk.token.length - posChunk;
}
if (tokLen) {
tokens.push(
new PR_Token(chunk.token.substring(posChunk, posChunk + tokLen),
tokenEnd.style));
posAbs += tokLen;
posChunk += tokLen;
}
}
return tokens;
}
/** splits markup tokens into declarations, tags, and source chunks.
* @private
*/
function PR_splitMarkup(chunks) {
// A state machine to split out declarations, tags, etc.
// This state machine deals with absolute space in the text, indexed by k,
// and position in the current chunk, indexed by pos and tokenStart to
// generate a list of the ends of tokens.
// Absolute space is calculated by considering the chunks as appended into
// one big string, as they were before being split.
// Known failure cases
// Server side scripting sections such as <?...?> in attributes.
// i.e. <span class="<? foo ?>">
// Handling this would require a stack, and we don't use PHP.
// The output: a list of pairs of PR_TokenEnd instances
var tokenEnds = new Array();
var state = 0; // FSM state variable
var k = 0; // position in absolute space of the start of the current chunk
var tokenStart = -1; // the start of the current token
// Try to find a closing tag for any open <style> or <script> tags
// We can't do this at a later stage because then the following case
// would fail:
// <script>document.writeln('<!--');</script>
// We use tokenChars[:tokenCharsI] to accumulate the tag name so that we
// can check whether to enter into a no scripting section when the tag ends.
var tokenChars = new Array(12);
var tokenCharsI = 0;
// if non null, the tag prefix that we need to see to break out.
var endScriptTag = null;
var decodeHelper = new PR_DecodeHelper();
for (var ci = 0, nc = chunks.length; ci < nc; ++ci) {
var chunk = chunks[ci];
if (PR_PLAIN != chunk.style) {
k += chunk.token.length;
continue;
}
var s = chunk.token;
var pos = 0; // the position past the last character processed so far in s
for (var i = 0, n = s.length; i < n; /* i = next at bottom */) {
decodeHelper.decode(s, i);
var ch = decodeHelper.ch;
var next = decodeHelper.next;
var tokenStyle = null;
switch (state) {
case 0:
if ('<' == ch) { state = 1; }
break;
case 1:
tokenCharsI = 0;
if ('/' == ch) { // only consider close tags if we're in script/style
state = 7;
} else if (null == endScriptTag) {
if ('!' == ch) {
state = 2;
} else if (PR_isWordChar(ch)) {
state = 8;
} else if ('?' == ch) {
state = 9;
} else if ('%' == ch) {
state = 11;
} else if ('<' != ch) {
state = 0;
}
} else if ('<' != ch) {
state = 0;
}
break;
case 2:
if ('-' == ch) {
state = 4;
} else if (PR_isWordChar(ch)) {
state = 3;
} else if ('<' == ch) {
state = 1;
} else {
state = 0;
}
break;
case 3:
if ('>' == ch) {
state = 0;
tokenStyle = PR_DECLARATION;
}
break;
case 4:
if ('-' == ch) { state = 5; }
break;
case 5:
if ('-' == ch) { state = 6; }
break;
case 6:
if ('>' == ch) {
state = 0;
tokenStyle = PR_COMMENT;
} else if ('-' == ch) {
state = 6;
} else {
state = 4;
}
break;
case 7:
if (PR_isWordChar(ch)) {
state = 8;
} else if ('<' == ch) {
state = 1;
} else {
state = 0;
}
break;
case 8:
if ('>' == ch) {
state = 0;
tokenStyle = PR_TAG;
}
break;
case 9:
if ('?' == ch) { state = 10; }
break;
case 10:
if ('>' == ch) {
state = 0;
tokenStyle = PR_SOURCE;
} else if ('?' != ch) {
state = 9;
}
break;
case 11:
if ('%' == ch) { state = 12; }
break;
case 12:
if ('>' == ch) {
state = 0;
tokenStyle = PR_SOURCE;
} else if ('%' != ch) {
state = 11;
}
break;
}
if (tokenCharsI < tokenChars.length) {
tokenChars[tokenCharsI++] = ch.toLowerCase();
}
if (1 == state) { tokenStart = k + i; }
i = next;
if (tokenStyle != null) {
if (null != tokenStyle) {
if (endScriptTag) {
if (PR_prefixMatch(tokenChars, tokenCharsI, endScriptTag)) {
endScriptTag = null;
}
} else {
if (PR_prefixMatch(tokenChars, tokenCharsI, 'script')) {
endScriptTag = '/script';
} else if (PR_prefixMatch(tokenChars, tokenCharsI, 'style')) {
endScriptTag = '/style';
} else if (PR_prefixMatch(tokenChars, tokenCharsI, 'xmp')) {
endScriptTag = '/xmp';
}
}
// disallow the tag if endScriptTag is set and this was not an open
// tag.
if (endScriptTag && tokenCharsI && '/' == tokenChars[0]) {
tokenStyle = null;
}
}
if (null != tokenStyle) {
tokenEnds.push(new PR_TokenEnd(tokenStart, PR_PLAIN));
tokenEnds.push(new PR_TokenEnd(k + next, tokenStyle));
}
}
}
k += chunk.token.length;
}
tokenEnds.push(new PR_TokenEnd(k, PR_PLAIN));
return tokenEnds;
}
/** splits the given string into comment, string, and "other" tokens.
* @return an array of PR_Tokens with style in
* (PR_STRING, PR_COMMENT, PR_PLAIN, null)
* The result array may contain spurious zero length tokens. Ignore them.
*
* @private
*/
function PR_splitStringAndCommentTokens(chunks) {
// a state machine to split out comments, strings, and other stuff
var tokenEnds = new Array(); // positions of ends of tokens in absolute space
var state = 0; // FSM state variable
var delim = -1; // string delimiter
var k = 0; // absolute position of beginning of current chunk
for (var ci = 0, nc = chunks.length; ci < nc; ++ci) {
var chunk = chunks[ci];
var s = chunk.token;
if (PR_PLAIN == chunk.style) {
for (var i = 0, n = s.length; i < n; ++i) {
var ch = s.charAt(i);
if (0 == state) {
if (ch == '"' || ch == '\'' || ch == '`') {
tokenEnds.push(new PR_TokenEnd(k + i, PR_PLAIN));
state = 1;
delim = ch;
} else if (ch == '/') {
state = 3;
} else if (ch == '#') {
tokenEnds.push(new PR_TokenEnd(k + i, PR_PLAIN));
state = 4;
}
} else if (1 == state) {
if (ch == delim) {
state = 0;
tokenEnds.push(new PR_TokenEnd(k + i + 1, PR_STRING));
} else if (ch == '\\') {
state = 2;
}
} else if (2 == state) {
state = 1;
} else if (3 == state) {
if (ch == '/') {
state = 4;
tokenEnds.push(new PR_TokenEnd(k + i - 1, PR_PLAIN));
} else if (ch == '*') {
state = 5;
tokenEnds.push(new PR_TokenEnd(k + i - 1, PR_PLAIN));
} else {
state = 0;
// next loop will reenter state 0 without same value of i, so
// ch will be reconsidered as start of new token.
--i;
}
} else if (4 == state) {
if (ch == '\r' || ch == '\n') {
state = 0;
tokenEnds.push(new PR_TokenEnd(k + i, PR_COMMENT));
}
} else if (5 == state) {
if (ch == '*') {
state = 6;
}
} else if (6 == state) {
if (ch == '/') {
state = 0;
tokenEnds.push(new PR_TokenEnd(k + i + 1, PR_COMMENT));
} else if (ch != '*') {
state = 5;
}
}
}
}
k += s.length;
}
var endTokenType;
switch (state) {
case 1: case 2:
endTokenType = PR_STRING;
break;
case 4: case 5: case 6:
endTokenType = PR_COMMENT;
break;
default:
endTokenType = PR_PLAIN;
break;
}
// handle unclosed token which can legally happen for line comments (state 4)
tokenEnds.push(new PR_TokenEnd(k, endTokenType)); // a token ends at the end
return PR_splitChunks(chunks, tokenEnds);
}
/** used by lexSource to split a non string, non comment token.
* @private
*/
function PR_splitNonStringNonCommentToken(s, outlist) {
var pos = 0;
var state = 0;
for (var i = 0; i <= s.length; i++) {
var ch = s.charAt(i);
// the next state.
// if set to -1 then it will cause a reentry to state 0 without consuming
// another character.
var nstate = state;
if (i == s.length) {
// nstate will not be equal to state, so it will append the token
nstate = -2;
} else {
switch (state) {
case 0: // whitespace state
if (PR_isIdentifierStart(ch)) {
nstate = 1;
} else if (PR_isDigitChar(ch)) {
nstate = 2;
} else if (!PR_isSpaceChar(ch)) {
nstate = 3;
}
if (nstate && pos < i) {
var t = s.substring(pos, i);
outlist.push(new PR_Token(t, PR_PLAIN));
pos = i;
}
break;
case 1: // identifier state
if (!PR_isIdentifierPart(ch)) {
nstate = -1;
}
break;
case 2: // number literal state
// handle numeric literals like
// 0x7f 300UL 100_000
// this does not treat floating point values as a single literal
// 0.1 and 3e-6
// are each split into multiple tokens
if (!(PR_isDigitChar(ch) || PR_isWordChar(ch) || ch == '_')) {
nstate = -1;
}
break;
case 3: // punctuation state
if (PR_isIdentifierStart(ch) || PR_isDigitChar(ch) ||
PR_isSpaceChar(ch)) {
nstate = -1;
}
break;
}
}
if (nstate != state) {
if (nstate < 0) {
if (i > pos) {
var t = s.substring(pos, i);
var ch0 = t.charAt(0);
var style;
if (PR_isIdentifierStart(ch0)) {
if (PR_keywords[t]) {
style = PR_KEYWORD;
} else if (ch0 === '@') {
style = PR_LITERAL;
} else {
// Treat any word that starts with an uppercase character and
// contains at least one lowercase character as a type, or
// ends with _t.
// This works perfectly for Java, pretty well for C++, and
// passably for Python. The _t catches C structs.
var isType = false;
if (ch0 >= 'A' && ch0 <= 'Z') {
for (var j = 1; j < t.length; j++) {
var ch1 = t.charAt(j);
if (ch1 >= 'a' && ch1 <= 'z') {
isType = true;
break;
}
}
if (!isType && t.length >= 2 &&
t.substring(t.length - 2) == '_t') {
isType = true;
}
}
style = isType ? PR_TYPE : PR_PLAIN;
}
} else if (PR_isDigitChar(ch0)) {
style = PR_LITERAL;
} else if (!PR_isSpaceChar(ch0)) {
style = PR_PUNCTUATION;
} else {
style = PR_PLAIN;
}
pos = i;
outlist.push(new PR_Token(t, style));
}
state = 0;
if (nstate == -1) {
// don't increment. This allows us to use state 0 to redispatch based
// on the current character.
i--;
continue;
}
}
state = nstate;
}
}
}
/** split a group of chunks of markup.
* @private
*/
function PR_tokenizeMarkup(chunks) {
if (!(chunks && chunks.length)) { return chunks; }
var tokenEnds = PR_splitMarkup(chunks);
return PR_splitChunks(chunks, tokenEnds);
}
/** split tags attributes and their values out from the tag name, and
* recursively lex source chunks.
* @private
*/
function PR_splitTagAttributes(tokens) {
var tokensOut = new Array();
var state = 0;
var stateStyle = PR_TAG;
var delim = null; // attribute delimiter for quoted value state.
var decodeHelper = new PR_DecodeHelper();
for (var ci = 0; ci < tokens.length; ++ci) {
var tok = tokens[ci];
if (PR_TAG == tok.style) {
var s = tok.token;
var start = 0;
for (var i = 0; i < s.length; /* i = next at bottom */) {
decodeHelper.decode(s, i);
var ch = decodeHelper.ch;
var next = decodeHelper.next;
var emitEnd = null; // null or position of end of chunk to emit.
var nextStyle = null; // null or next value of stateStyle
if (ch == '>') {
if (PR_TAG != stateStyle) {
emitEnd = i;
nextStyle = PR_TAG;
}
} else {
switch (state) {
case 0:
if ('<' == ch) { state = 1; }
break;
case 1:
if (PR_isSpaceChar(ch)) { state = 2; }
break;
case 2:
if (!PR_isSpaceChar(ch)) {
nextStyle = PR_ATTRIB_NAME;
emitEnd = i;
state = 3;
}
break;
case 3:
if ('=' == ch) {
emitEnd = i;
nextStyle = PR_TAG;
state = 5;
} else if (PR_isSpaceChar(ch)) {
emitEnd = i;
nextStyle = PR_TAG;
state = 4;
}
break;
case 4:
if ('=' == ch) {
state = 5;
} else if (!PR_isSpaceChar(ch)) {
emitEnd = i;
nextStyle = PR_ATTRIB_NAME;
state = 3;
}
break;
case 5:
if ('"' == ch || '\'' == ch) {
emitEnd = i;
nextStyle = PR_ATTRIB_VALUE;
state = 6;
delim = ch;
} else if (!PR_isSpaceChar(ch)) {
emitEnd = i;
nextStyle = PR_ATTRIB_VALUE;
state = 7;
}
break;
case 6:
if (ch == delim) {
emitEnd = next;
nextStyle = PR_TAG;
state = 2;
}
break;
case 7:
if (PR_isSpaceChar(ch)) {
emitEnd = i;
nextStyle = PR_TAG;
state = 2;
}
break;
}
}
if (emitEnd) {
if (emitEnd > start) {
tokensOut.push(
new PR_Token(s.substring(start, emitEnd), stateStyle));
start = emitEnd;
}
stateStyle = nextStyle;
}
i = next;
}
if (s.length > start) {
tokensOut.push(new PR_Token(s.substring(start, s.length), stateStyle));
}
} else {
if (tok.style) {
state = 0;
stateStyle = PR_TAG;
}
tokensOut.push(tok);
}
}
return tokensOut;
}
/** identify regions of markup that are really source code, and recursivley
* lex them.
* @private
*/
function PR_splitSourceNodes(tokens) {
var tokensOut = new Array();
// when we see a <script> tag, store '/' here so that we know to end the
// source processing
var endScriptTag = null;
var decodeHelper = new PR_DecodeHelper();
var sourceChunks = null;