Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / WebKit / Source / devtools / front_end / cm_modes / clike.js
blob3e253624b48236cc9927401f5d9f6ac0b5b2b1b5
1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 // Distributed under an MIT license: http://codemirror.net/LICENSE
4 (function(mod) {
5 if (typeof exports == "object" && typeof module == "object") // CommonJS
6 mod(require("../../lib/codemirror"));
7 else if (typeof define == "function" && define.amd) // AMD
8 define(["../../lib/codemirror"], mod);
9 else // Plain browser env
10 mod(CodeMirror);
11 })(function(CodeMirror) {
12 "use strict";
14 CodeMirror.defineMode("clike", function(config, parserConfig) {
15 var indentUnit = config.indentUnit,
16 statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
17 dontAlignCalls = parserConfig.dontAlignCalls,
18 keywords = parserConfig.keywords || {},
19 builtin = parserConfig.builtin || {},
20 blockKeywords = parserConfig.blockKeywords || {},
21 atoms = parserConfig.atoms || {},
22 hooks = parserConfig.hooks || {},
23 multiLineStrings = parserConfig.multiLineStrings;
24 var isOperatorChar = /[+\-*&%=<>!?|\/]/;
26 var curPunc;
28 function tokenBase(stream, state) {
29 var ch = stream.next();
30 if (hooks[ch]) {
31 var result = hooks[ch](stream, state);
32 if (result !== false) return result;
34 if (ch == '"' || ch == "'") {
35 state.tokenize = tokenString(ch);
36 return state.tokenize(stream, state);
38 if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
39 curPunc = ch;
40 return null;
42 if (/\d/.test(ch)) {
43 stream.eatWhile(/[\w\.]/);
44 return "number";
46 if (ch == "/") {
47 if (stream.eat("*")) {
48 state.tokenize = tokenComment;
49 return tokenComment(stream, state);
51 if (stream.eat("/")) {
52 stream.skipToEnd();
53 return "comment";
56 if (isOperatorChar.test(ch)) {
57 stream.eatWhile(isOperatorChar);
58 return "operator";
60 stream.eatWhile(/[\w\$_]/);
61 var cur = stream.current();
62 if (keywords.propertyIsEnumerable(cur)) {
63 if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
64 return "keyword";
66 if (builtin.propertyIsEnumerable(cur)) {
67 if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
68 return "builtin";
70 if (atoms.propertyIsEnumerable(cur)) return "atom";
71 return "variable";
74 function tokenString(quote) {
75 return function(stream, state) {
76 var escaped = false, next, end = false;
77 while ((next = stream.next()) != null) {
78 if (next == quote && !escaped) {end = true; break;}
79 escaped = !escaped && next == "\\";
81 if (end || !(escaped || multiLineStrings))
82 state.tokenize = null;
83 return "string";
87 function tokenComment(stream, state) {
88 var maybeEnd = false, ch;
89 while (ch = stream.next()) {
90 if (ch == "/" && maybeEnd) {
91 state.tokenize = null;
92 break;
94 maybeEnd = (ch == "*");
96 return "comment";
99 function Context(indented, column, type, align, prev) {
100 this.indented = indented;
101 this.column = column;
102 this.type = type;
103 this.align = align;
104 this.prev = prev;
106 function pushContext(state, col, type) {
107 var indent = state.indented;
108 if (state.context && state.context.type == "statement")
109 indent = state.context.indented;
110 return state.context = new Context(indent, col, type, null, state.context);
112 function popContext(state) {
113 var t = state.context.type;
114 if (t == ")" || t == "]" || t == "}")
115 state.indented = state.context.indented;
116 return state.context = state.context.prev;
119 // Interface
121 return {
122 startState: function(basecolumn) {
123 return {
124 tokenize: null,
125 context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
126 indented: 0,
127 startOfLine: true
131 token: function(stream, state) {
132 var ctx = state.context;
133 if (stream.sol()) {
134 if (ctx.align == null) ctx.align = false;
135 state.indented = stream.indentation();
136 state.startOfLine = true;
138 if (stream.eatSpace()) return null;
139 curPunc = null;
140 var style = (state.tokenize || tokenBase)(stream, state);
141 if (style == "comment" || style == "meta") return style;
142 if (ctx.align == null) ctx.align = true;
144 if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
145 else if (curPunc == "{") pushContext(state, stream.column(), "}");
146 else if (curPunc == "[") pushContext(state, stream.column(), "]");
147 else if (curPunc == "(") pushContext(state, stream.column(), ")");
148 else if (curPunc == "}") {
149 while (ctx.type == "statement") ctx = popContext(state);
150 if (ctx.type == "}") ctx = popContext(state);
151 while (ctx.type == "statement") ctx = popContext(state);
153 else if (curPunc == ctx.type) popContext(state);
154 else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
155 pushContext(state, stream.column(), "statement");
156 state.startOfLine = false;
157 return style;
160 indent: function(state, textAfter) {
161 if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
162 var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
163 if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
164 var closing = firstChar == ctx.type;
165 if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
166 else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
167 else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
168 else return ctx.indented + (closing ? 0 : indentUnit);
171 electricChars: "{}",
172 blockCommentStart: "/*",
173 blockCommentEnd: "*/",
174 lineComment: "//",
175 fold: "brace"
179 function words(str) {
180 var obj = {}, words = str.split(" ");
181 for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
182 return obj;
184 var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
185 "double static else struct entry switch extern typedef float union for unsigned " +
186 "goto while enum void const signed volatile";
188 function cppHook(stream, state) {
189 if (!state.startOfLine) return false;
190 for (;;) {
191 if (stream.skipTo("\\")) {
192 stream.next();
193 if (stream.eol()) {
194 state.tokenize = cppHook;
195 break;
197 } else {
198 stream.skipToEnd();
199 state.tokenize = null;
200 break;
203 return "meta";
206 function cpp11StringHook(stream, state) {
207 stream.backUp(1);
208 // Raw strings.
209 if (stream.match(/(R|u8R|uR|UR|LR)/)) {
210 var match = stream.match(/"([^\s\\()]{0,16})\(/);
211 if (!match) {
212 return false;
214 state.cpp11RawStringDelim = match[1];
215 state.tokenize = tokenRawString;
216 return tokenRawString(stream, state);
218 // Unicode strings/chars.
219 if (stream.match(/(u8|u|U|L)/)) {
220 if (stream.match(/["']/, /* eat */ false)) {
221 return "string";
223 return false;
225 // Ignore this hook.
226 stream.next();
227 return false;
230 // C#-style strings where "" escapes a quote.
231 function tokenAtString(stream, state) {
232 var next;
233 while ((next = stream.next()) != null) {
234 if (next == '"' && !stream.eat('"')) {
235 state.tokenize = null;
236 break;
239 return "string";
242 // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
243 // <delim> can be a string up to 16 characters long.
244 function tokenRawString(stream, state) {
245 // Escape characters that have special regex meanings.
246 var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
247 var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
248 if (match)
249 state.tokenize = null;
250 else
251 stream.skipToEnd();
252 return "string";
255 function def(mimes, mode) {
256 if (typeof mimes == "string") mimes = [mimes];
257 var words = [];
258 function add(obj) {
259 if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
260 words.push(prop);
262 add(mode.keywords);
263 add(mode.builtin);
264 add(mode.atoms);
265 if (words.length) {
266 mode.helperType = mimes[0];
267 CodeMirror.registerHelper("hintWords", mimes[0], words);
270 for (var i = 0; i < mimes.length; ++i)
271 CodeMirror.defineMIME(mimes[i], mode);
274 def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
275 name: "clike",
276 keywords: words(cKeywords),
277 blockKeywords: words("case do else for if switch while struct"),
278 atoms: words("null"),
279 hooks: {"#": cppHook},
280 modeProps: {fold: ["brace", "include"]}
283 def(["text/x-c++src", "text/x-c++hdr"], {
284 name: "clike",
285 keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
286 "static_cast typeid catch operator template typename class friend private " +
287 "this using const_cast inline public throw virtual delete mutable protected " +
288 "wchar_t alignas alignof constexpr decltype nullptr noexcept thread_local final " +
289 "static_assert override"),
290 blockKeywords: words("catch class do else finally for if struct switch try while"),
291 atoms: words("true false null"),
292 hooks: {
293 "#": cppHook,
294 "u": cpp11StringHook,
295 "U": cpp11StringHook,
296 "L": cpp11StringHook,
297 "R": cpp11StringHook
299 modeProps: {fold: ["brace", "include"]}
301 def("text/x-java", {
302 name: "clike",
303 keywords: words("abstract assert boolean break byte case catch char class const continue default " +
304 "do double else enum extends final finally float for goto if implements import " +
305 "instanceof int interface long native new package private protected public " +
306 "return short static strictfp super switch synchronized this throw throws transient " +
307 "try void volatile while"),
308 blockKeywords: words("catch class do else finally for if switch try while"),
309 atoms: words("true false null"),
310 hooks: {
311 "@": function(stream) {
312 stream.eatWhile(/[\w\$_]/);
313 return "meta";
316 modeProps: {fold: ["brace", "import"]}
318 def("text/x-csharp", {
319 name: "clike",
320 keywords: words("abstract as base break case catch checked class const continue" +
321 " default delegate do else enum event explicit extern finally fixed for" +
322 " foreach goto if implicit in interface internal is lock namespace new" +
323 " operator out override params private protected public readonly ref return sealed" +
324 " sizeof stackalloc static struct switch this throw try typeof unchecked" +
325 " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
326 " global group into join let orderby partial remove select set value var yield"),
327 blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
328 builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
329 " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
330 " UInt64 bool byte char decimal double short int long object" +
331 " sbyte float string ushort uint ulong"),
332 atoms: words("true false null"),
333 hooks: {
334 "@": function(stream, state) {
335 if (stream.eat('"')) {
336 state.tokenize = tokenAtString;
337 return tokenAtString(stream, state);
339 stream.eatWhile(/[\w\$_]/);
340 return "meta";
344 def("text/x-scala", {
345 name: "clike",
346 keywords: words(
348 /* scala */
349 "abstract case catch class def do else extends false final finally for forSome if " +
350 "implicit import lazy match new null object override package private protected return " +
351 "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
352 "<% >: # @ " +
354 /* package scala */
355 "assert assume require print println printf readLine readBoolean readByte readShort " +
356 "readChar readInt readLong readFloat readDouble " +
358 "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
359 "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
360 "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
361 "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
362 "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
364 /* package java.lang */
365 "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
366 "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
367 "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
368 "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
372 blockKeywords: words("catch class do else finally for forSome if match switch try while"),
373 atoms: words("true false null"),
374 hooks: {
375 "@": function(stream) {
376 stream.eatWhile(/[\w\$_]/);
377 return "meta";
381 def(["x-shader/x-vertex", "x-shader/x-fragment"], {
382 name: "clike",
383 keywords: words("float int bool void " +
384 "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
385 "mat2 mat3 mat4 " +
386 "sampler1D sampler2D sampler3D samplerCube " +
387 "sampler1DShadow sampler2DShadow" +
388 "const attribute uniform varying " +
389 "break continue discard return " +
390 "for while do if else struct " +
391 "in out inout"),
392 blockKeywords: words("for while do if else struct"),
393 builtin: words("radians degrees sin cos tan asin acos atan " +
394 "pow exp log exp2 sqrt inversesqrt " +
395 "abs sign floor ceil fract mod min max clamp mix step smootstep " +
396 "length distance dot cross normalize ftransform faceforward " +
397 "reflect refract matrixCompMult " +
398 "lessThan lessThanEqual greaterThan greaterThanEqual " +
399 "equal notEqual any all not " +
400 "texture1D texture1DProj texture1DLod texture1DProjLod " +
401 "texture2D texture2DProj texture2DLod texture2DProjLod " +
402 "texture3D texture3DProj texture3DLod texture3DProjLod " +
403 "textureCube textureCubeLod " +
404 "shadow1D shadow2D shadow1DProj shadow2DProj " +
405 "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
406 "dFdx dFdy fwidth " +
407 "noise1 noise2 noise3 noise4"),
408 atoms: words("true false " +
409 "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
410 "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
411 "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
412 "gl_FogCoord " +
413 "gl_Position gl_PointSize gl_ClipVertex " +
414 "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
415 "gl_TexCoord gl_FogFragCoord " +
416 "gl_FragCoord gl_FrontFacing " +
417 "gl_FragColor gl_FragData gl_FragDepth " +
418 "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
419 "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
420 "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
421 "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
422 "gl_ProjectionMatrixInverseTranspose " +
423 "gl_ModelViewProjectionMatrixInverseTranspose " +
424 "gl_TextureMatrixInverseTranspose " +
425 "gl_NormalScale gl_DepthRange gl_ClipPlane " +
426 "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
427 "gl_FrontLightModelProduct gl_BackLightModelProduct " +
428 "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
429 "gl_FogParameters " +
430 "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
431 "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
432 "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
433 "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
434 "gl_MaxDrawBuffers"),
435 hooks: {"#": cppHook},
436 modeProps: {fold: ["brace", "include"]}