2 * Copyright (C) 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 importScripts("utilities.js");
31 importScripts("cm/headlesscodemirror.js");
32 importScripts("cm/css.js");
33 importScripts("cm/javascript.js");
34 importScripts("cm/xml.js");
35 importScripts("cm/htmlmixed.js");
39 * @param {string} mimeType
40 * @return {function(string, function(string, ?string, number, number))}
42 createTokenizer: function(mimeType)
44 var mode = CodeMirror.getMode({indentUnit: 2}, mimeType);
45 var state = CodeMirror.startState(mode);
46 function tokenize(line, callback)
48 var stream = new CodeMirror.StringStream(line);
49 while (!stream.eol()) {
50 var style = mode.token(stream, state);
51 var value = stream.current();
52 callback(value, style, stream.start, stream.start + value.length);
53 stream.start = stream.pos;
61 * @typedef {{indentString: string, content: string, mimeType: string}}
63 var FormatterParameters;
65 var onmessage = function(event) {
66 var data = /** @type !{method: string, params: !FormatterParameters} */ (event.data);
70 FormatterWorker[data.method](data.params);
74 * @param {!FormatterParameters} params
76 FormatterWorker.format = function(params)
78 // Default to a 4-space indent.
79 var indentString = params.indentString || " ";
82 if (params.mimeType === "text/html") {
83 var formatter = new FormatterWorker.HTMLFormatter(indentString);
84 result = formatter.format(params.content);
85 } else if (params.mimeType === "text/css") {
86 result.mapping = { original: [0], formatted: [0] };
87 result.content = FormatterWorker._formatCSS(params.content, result.mapping, 0, 0, indentString);
89 result.mapping = { original: [0], formatted: [0] };
90 result.content = FormatterWorker._formatScript(params.content, result.mapping, 0, 0, indentString);
96 * @param {number} totalLength
97 * @param {number} chunkSize
99 FormatterWorker._chunkCount = function(totalLength, chunkSize)
101 if (totalLength <= chunkSize)
104 var remainder = totalLength % chunkSize;
105 var partialLength = totalLength - remainder;
106 return (partialLength / chunkSize) + (remainder ? 1 : 0);
110 * @param {!Object} params
112 FormatterWorker.javaScriptOutline = function(params)
114 var chunkSize = 100000; // characters per data chunk
115 var totalLength = params.content.length;
116 var lines = params.content.split("\n");
117 var chunkCount = FormatterWorker._chunkCount(totalLength, chunkSize);
118 var outlineChunk = [];
119 var previousIdentifier = null;
120 var previousToken = null;
121 var previousTokenType = null;
122 var currentChunk = 1;
123 var processedChunkCharacters = 0;
124 var addedFunction = false;
125 var isReadingArguments = false;
126 var argumentsText = "";
127 var currentFunction = null;
128 var tokenizer = FormatterWorker.createTokenizer("text/javascript");
129 for (var i = 0; i < lines.length; ++i) {
131 tokenizer(line, processToken);
135 * @param {?string} tokenType
138 function isJavaScriptIdentifier(tokenType)
142 return tokenType.startsWith("variable") || tokenType.startsWith("property") || tokenType === "def";
146 * @param {string} tokenValue
147 * @param {?string} tokenType
148 * @param {number} column
149 * @param {number} newColumn
151 function processToken(tokenValue, tokenType, column, newColumn)
153 if (isJavaScriptIdentifier(tokenType)) {
154 previousIdentifier = tokenValue;
155 if (tokenValue && previousToken === "function") {
156 // A named function: "function f...".
157 currentFunction = { line: i, column: column, name: tokenValue };
158 addedFunction = true;
159 previousIdentifier = null;
161 } else if (tokenType === "keyword") {
162 if (tokenValue === "function") {
163 if (previousIdentifier && (previousToken === "=" || previousToken === ":")) {
164 // Anonymous function assigned to an identifier: "...f = function..."
165 // or "funcName: function...".
166 currentFunction = { line: i, column: column, name: previousIdentifier };
167 addedFunction = true;
168 previousIdentifier = null;
171 } else if (tokenValue === "." && isJavaScriptIdentifier(previousTokenType))
172 previousIdentifier += ".";
173 else if (tokenValue === "(" && addedFunction)
174 isReadingArguments = true;
175 if (isReadingArguments && tokenValue)
176 argumentsText += tokenValue;
178 if (tokenValue === ")" && isReadingArguments) {
179 addedFunction = false;
180 isReadingArguments = false;
181 currentFunction.arguments = argumentsText.replace(/,[\r\n\s]*/g, ", ").replace(/([^,])[\r\n\s]+/g, "$1");
183 outlineChunk.push(currentFunction);
186 if (tokenValue.trim().length) {
187 // Skip whitespace tokens.
188 previousToken = tokenValue;
189 previousTokenType = tokenType;
191 processedChunkCharacters += newColumn - column;
193 if (processedChunkCharacters >= chunkSize) {
194 postMessage({ chunk: outlineChunk, total: chunkCount, index: currentChunk++ });
196 processedChunkCharacters = 0;
200 postMessage({ chunk: outlineChunk, total: chunkCount, index: chunkCount });
203 FormatterWorker.CSSParserStates = {
205 Selector: "Selector",
209 FormatterWorker.cssOutline = function(params)
211 var chunkSize = 100000; // characters per data chunk
212 var totalLength = params.content.length;
213 var lines = params.content.split("\n");
214 var chunkCount = FormatterWorker._chunkCount(totalLength, chunkSize);
216 var processedChunkCharacters = 0;
217 var currentChunk = 0;
219 var state = FormatterWorker.CSSParserStates.Initial;
224 * @param {string} tokenValue
225 * @param {?string} tokenType
226 * @param {number} column
227 * @param {number} newColumn
229 function processToken(tokenValue, tokenType, column, newColumn)
232 case FormatterWorker.CSSParserStates.Initial:
233 if (tokenType === "qualifier" || tokenType === "builtin" || tokenType === "tag") {
235 selectorText: tokenValue,
236 lineNumber: lineNumber,
239 state = FormatterWorker.CSSParserStates.Selector;
240 } else if (tokenType === "def") {
243 lineNumber: lineNumber,
246 state = FormatterWorker.CSSParserStates.AtRule;
249 case FormatterWorker.CSSParserStates.Selector:
250 if (tokenValue === "{" && tokenType === null) {
251 rule.selectorText = rule.selectorText.trim();
253 state = FormatterWorker.CSSParserStates.Initial;
255 rule.selectorText += tokenValue;
258 case FormatterWorker.CSSParserStates.AtRule:
259 if ((tokenValue === ";" || tokenValue === "{") && tokenType === null) {
260 rule.atRule = rule.atRule.trim();
262 state = FormatterWorker.CSSParserStates.Initial;
264 rule.atRule += tokenValue;
268 console.assert(false, "Unknown CSS parser state.");
270 processedChunkCharacters += newColumn - column;
271 if (processedChunkCharacters > chunkSize) {
272 postMessage({ chunk: rules, total: chunkCount, index: currentChunk++ });
274 processedChunkCharacters = 0;
277 var tokenizer = FormatterWorker.createTokenizer("text/css");
279 for (lineNumber = 0; lineNumber < lines.length; ++lineNumber) {
280 var line = lines[lineNumber];
281 tokenizer(line, processToken);
283 postMessage({ chunk: rules, total: chunkCount, index: currentChunk++ });
287 * @param {string} content
288 * @param {!{original: !Array.<number>, formatted: !Array.<number>}} mapping
289 * @param {number} offset
290 * @param {number} formattedOffset
291 * @param {string} indentString
294 FormatterWorker._formatScript = function(content, mapping, offset, formattedOffset, indentString)
296 var formattedContent;
298 var tokenizer = new FormatterWorker.JavaScriptTokenizer(content);
299 var builder = new FormatterWorker.JavaScriptFormattedContentBuilder(tokenizer.content(), mapping, offset, formattedOffset, indentString);
300 var formatter = new FormatterWorker.JavaScriptFormatter(tokenizer, builder);
302 formattedContent = builder.content();
304 formattedContent = content;
306 return formattedContent;
310 * @param {string} content
311 * @param {!{original: !Array.<number>, formatted: !Array.<number>}} mapping
312 * @param {number} offset
313 * @param {number} formattedOffset
314 * @param {string} indentString
317 FormatterWorker._formatCSS = function(content, mapping, offset, formattedOffset, indentString)
319 var formattedContent;
321 var builder = new FormatterWorker.CSSFormattedContentBuilder(content, mapping, offset, formattedOffset, indentString);
322 var formatter = new FormatterWorker.CSSFormatter(content, builder);
324 formattedContent = builder.content();
326 formattedContent = content;
328 return formattedContent;
333 * @param {string} indentString
335 FormatterWorker.HTMLFormatter = function(indentString)
337 this._indentString = indentString;
340 FormatterWorker.HTMLFormatter.prototype = {
342 * @param {string} content
343 * @return {!{content: string, mapping: {original: !Array.<number>, formatted: !Array.<number>}}}
345 format: function(content)
348 this._content = content;
349 this._formattedContent = "";
350 this._mapping = { original: [0], formatted: [0] };
353 var scriptOpened = false;
354 var styleOpened = false;
355 var tokenizer = FormatterWorker.createTokenizer("text/html");
358 * @this {FormatterWorker.HTMLFormatter}
360 function processToken(tokenValue, tokenType, tokenStart, tokenEnd) {
361 if (tokenType !== "tag")
363 if (tokenValue.toLowerCase() === "<script") {
365 } else if (scriptOpened && tokenValue === ">") {
366 scriptOpened = false;
367 this._scriptStarted(tokenEnd);
368 } else if (tokenValue.toLowerCase() === "</script") {
369 this._scriptEnded(tokenStart);
370 } else if (tokenValue.toLowerCase() === "<style") {
372 } else if (styleOpened && tokenValue === ">") {
374 this._styleStarted(tokenEnd);
375 } else if (tokenValue.toLowerCase() === "</style") {
376 this._styleEnded(tokenStart);
379 tokenizer(content, processToken.bind(this));
381 this._formattedContent += this._content.substring(this._position);
382 return { content: this._formattedContent, mapping: this._mapping };
386 * @param {number} cursor
388 _scriptStarted: function(cursor)
390 this._handleSubFormatterStart(cursor);
394 * @param {number} cursor
396 _scriptEnded: function(cursor)
398 this._handleSubFormatterEnd(FormatterWorker._formatScript, cursor);
402 * @param {number} cursor
404 _styleStarted: function(cursor)
406 this._handleSubFormatterStart(cursor);
410 * @param {number} cursor
412 _styleEnded: function(cursor)
414 this._handleSubFormatterEnd(FormatterWorker._formatCSS, cursor);
418 * @param {number} cursor
420 _handleSubFormatterStart: function(cursor)
422 this._formattedContent += this._content.substring(this._position, cursor);
423 this._formattedContent += "\n";
424 this._position = cursor;
428 * @param {function(string, !{formatted: !Array.<number>, original: !Array.<number>}, number, number, string)} formatFunction
429 * @param {number} cursor
431 _handleSubFormatterEnd: function(formatFunction, cursor)
433 if (cursor === this._position)
436 var scriptContent = this._content.substring(this._position, cursor);
437 this._mapping.original.push(this._position);
438 this._mapping.formatted.push(this._formattedContent.length);
439 var formattedScriptContent = formatFunction(scriptContent, this._mapping, this._position, this._formattedContent.length, this._indentString);
441 this._formattedContent += formattedScriptContent;
442 this._position = cursor;
446 Array.prototype.keySet = function()
449 for (var i = 0; i < this.length; ++i)
450 keys[this[i]] = true;
463 * @type {!{tokenizer}}
465 var exports = { tokenizer: null };
466 importScripts("UglifyJS/parse-js.js");
469 importScripts("JavaScriptFormatter.js");
470 importScripts("CSSFormatter.js");