rubycritic 3.0.0 → 3.1.0

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