@openui5/sap.ui.documentation 1.93.3 → 1.96.2

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