1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 // Distributed under an MIT license: http://codemirror.net/LICENSE
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
11 })(function(CodeMirror) {
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 indentStatements = parserConfig.indentStatements !== false;
25 var isOperatorChar = /[+\-*&%=<>!?|\/]/;
29 function tokenBase(stream, state) {
30 var ch = stream.next();
32 var result = hooks[ch](stream, state);
33 if (result !== false) return result;
35 if (ch == '"' || ch == "'") {
36 state.tokenize = tokenString(ch);
37 return state.tokenize(stream, state);
39 if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
44 stream.eatWhile(/[\w\.]/);
48 if (stream.eat("*")) {
49 state.tokenize = tokenComment;
50 return tokenComment(stream, state);
52 if (stream.eat("/")) {
57 if (isOperatorChar.test(ch)) {
58 stream.eatWhile(isOperatorChar);
61 stream.eatWhile(/[\w\$_\xa1-\uffff]/);
62 var cur = stream.current();
63 if (keywords.propertyIsEnumerable(cur)) {
64 if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
67 if (builtin.propertyIsEnumerable(cur)) {
68 if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
71 if (atoms.propertyIsEnumerable(cur)) return "atom";
75 function tokenString(quote) {
76 return function(stream, state) {
77 var escaped = false, next, end = false;
78 while ((next = stream.next()) != null) {
79 if (next == quote && !escaped) {end = true; break;}
80 escaped = !escaped && next == "\\";
82 if (end || !(escaped || multiLineStrings))
83 state.tokenize = null;
88 function tokenComment(stream, state) {
89 var maybeEnd = false, ch;
90 while (ch = stream.next()) {
91 if (ch == "/" && maybeEnd) {
92 state.tokenize = null;
95 maybeEnd = (ch == "*");
100 function Context(indented, column, type, align, prev) {
101 this.indented = indented;
102 this.column = column;
107 function pushContext(state, col, type) {
108 var indent = state.indented;
109 if (state.context && state.context.type == "statement")
110 indent = state.context.indented;
111 return state.context = new Context(indent, col, type, null, state.context);
113 function popContext(state) {
114 var t = state.context.type;
115 if (t == ")" || t == "]" || t == "}")
116 state.indented = state.context.indented;
117 return state.context = state.context.prev;
123 startState: function(basecolumn) {
126 context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
132 token: function(stream, state) {
133 var ctx = state.context;
135 if (ctx.align == null) ctx.align = false;
136 state.indented = stream.indentation();
137 state.startOfLine = true;
139 if (stream.eatSpace()) return null;
141 var style = (state.tokenize || tokenBase)(stream, state);
142 if (style == "comment" || style == "meta") return style;
143 if (ctx.align == null) ctx.align = true;
145 if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
146 else if (curPunc == "{") pushContext(state, stream.column(), "}");
147 else if (curPunc == "[") pushContext(state, stream.column(), "]");
148 else if (curPunc == "(") pushContext(state, stream.column(), ")");
149 else if (curPunc == "}") {
150 while (ctx.type == "statement") ctx = popContext(state);
151 if (ctx.type == "}") ctx = popContext(state);
152 while (ctx.type == "statement") ctx = popContext(state);
154 else if (curPunc == ctx.type) popContext(state);
155 else if (indentStatements &&
156 (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') ||
157 (ctx.type == "statement" && curPunc == "newstatement")))
158 pushContext(state, stream.column(), "statement");
159 state.startOfLine = false;
163 indent: function(state, textAfter) {
164 if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
165 var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
166 if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
167 var closing = firstChar == ctx.type;
168 if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
169 else if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
170 else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
171 else return ctx.indented + (closing ? 0 : indentUnit);
175 blockCommentStart: "/*",
176 blockCommentEnd: "*/",
182 function words(str) {
183 var obj = {}, words = str.split(" ");
184 for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
187 var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
188 "double static else struct entry switch extern typedef float union for unsigned " +
189 "goto while enum void const signed volatile";
191 function cppHook(stream, state) {
192 if (!state.startOfLine) return false;
194 if (stream.skipTo("\\")) {
197 state.tokenize = cppHook;
202 state.tokenize = null;
209 function cpp11StringHook(stream, state) {
212 if (stream.match(/(R|u8R|uR|UR|LR)/)) {
213 var match = stream.match(/"([^\s\\()]{0,16})\(/);
217 state.cpp11RawStringDelim = match[1];
218 state.tokenize = tokenRawString;
219 return tokenRawString(stream, state);
221 // Unicode strings/chars.
222 if (stream.match(/(u8|u|U|L)/)) {
223 if (stream.match(/["']/, /* eat */ false)) {
233 // C#-style strings where "" escapes a quote.
234 function tokenAtString(stream, state) {
236 while ((next = stream.next()) != null) {
237 if (next == '"' && !stream.eat('"')) {
238 state.tokenize = null;
245 // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
246 // <delim> can be a string up to 16 characters long.
247 function tokenRawString(stream, state) {
248 // Escape characters that have special regex meanings.
249 var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
250 var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
252 state.tokenize = null;
258 function def(mimes, mode) {
259 if (typeof mimes == "string") mimes = [mimes];
262 if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
269 mode.helperType = mimes[0];
270 CodeMirror.registerHelper("hintWords", mimes[0], words);
273 for (var i = 0; i < mimes.length; ++i)
274 CodeMirror.defineMIME(mimes[i], mode);
277 def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
279 keywords: words(cKeywords),
280 blockKeywords: words("case do else for if switch while struct"),
281 atoms: words("null"),
282 hooks: {"#": cppHook},
283 modeProps: {fold: ["brace", "include"]}
286 def(["text/x-c++src", "text/x-c++hdr"], {
288 keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
289 "static_cast typeid catch operator template typename class friend private " +
290 "this using const_cast inline public throw virtual delete mutable protected " +
291 "wchar_t alignas alignof constexpr decltype nullptr noexcept thread_local final " +
292 "static_assert override"),
293 blockKeywords: words("catch class do else finally for if struct switch try while"),
294 atoms: words("true false null"),
297 "u": cpp11StringHook,
298 "U": cpp11StringHook,
299 "L": cpp11StringHook,
302 modeProps: {fold: ["brace", "include"]}
307 keywords: words("abstract assert boolean break byte case catch char class const continue default " +
308 "do double else enum extends final finally float for goto if implements import " +
309 "instanceof int interface long native new package private protected public " +
310 "return short static strictfp super switch synchronized this throw throws transient " +
311 "try void volatile while"),
312 blockKeywords: words("catch class do else finally for if switch try while"),
313 atoms: words("true false null"),
315 "@": function(stream) {
316 stream.eatWhile(/[\w\$_]/);
320 modeProps: {fold: ["brace", "import"]}
323 def("text/x-csharp", {
325 keywords: words("abstract as base break case catch checked class const continue" +
326 " default delegate do else enum event explicit extern finally fixed for" +
327 " foreach goto if implicit in interface internal is lock namespace new" +
328 " operator out override params private protected public readonly ref return sealed" +
329 " sizeof stackalloc static struct switch this throw try typeof unchecked" +
330 " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
331 " global group into join let orderby partial remove select set value var yield"),
332 blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
333 builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
334 " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
335 " UInt64 bool byte char decimal double short int long object" +
336 " sbyte float string ushort uint ulong"),
337 atoms: words("true false null"),
339 "@": function(stream, state) {
340 if (stream.eat('"')) {
341 state.tokenize = tokenAtString;
342 return tokenAtString(stream, state);
344 stream.eatWhile(/[\w\$_]/);
350 function tokenTripleString(stream, state) {
352 while (!stream.eol()) {
353 if (!escaped && stream.match('"""')) {
354 state.tokenize = null;
357 escaped = stream.next() != "\\" && !escaped;
362 def("text/x-scala", {
367 "abstract case catch class def do else extends false final finally for forSome if " +
368 "implicit import lazy match new null object override package private protected return " +
369 "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
373 "assert assume require print println printf readLine readBoolean readByte readShort " +
374 "readChar readInt readLong readFloat readDouble " +
376 "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
377 "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
378 "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
379 "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
380 "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
382 /* package java.lang */
383 "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
384 "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
385 "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
386 "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
388 multiLineStrings: true,
389 blockKeywords: words("catch class do else finally for forSome if match switch try while"),
390 atoms: words("true false null"),
391 indentStatements: false,
393 "@": function(stream) {
394 stream.eatWhile(/[\w\$_]/);
397 '"': function(stream, state) {
398 if (!stream.match('""')) return false;
399 state.tokenize = tokenTripleString;
400 return state.tokenize(stream, state);
405 def(["x-shader/x-vertex", "x-shader/x-fragment"], {
407 keywords: words("float int bool void " +
408 "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
410 "sampler1D sampler2D sampler3D samplerCube " +
411 "sampler1DShadow sampler2DShadow" +
412 "const attribute uniform varying " +
413 "break continue discard return " +
414 "for while do if else struct " +
416 blockKeywords: words("for while do if else struct"),
417 builtin: words("radians degrees sin cos tan asin acos atan " +
418 "pow exp log exp2 sqrt inversesqrt " +
419 "abs sign floor ceil fract mod min max clamp mix step smootstep " +
420 "length distance dot cross normalize ftransform faceforward " +
421 "reflect refract matrixCompMult " +
422 "lessThan lessThanEqual greaterThan greaterThanEqual " +
423 "equal notEqual any all not " +
424 "texture1D texture1DProj texture1DLod texture1DProjLod " +
425 "texture2D texture2DProj texture2DLod texture2DProjLod " +
426 "texture3D texture3DProj texture3DLod texture3DProjLod " +
427 "textureCube textureCubeLod " +
428 "shadow1D shadow2D shadow1DProj shadow2DProj " +
429 "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
430 "dFdx dFdy fwidth " +
431 "noise1 noise2 noise3 noise4"),
432 atoms: words("true false " +
433 "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
434 "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
435 "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
437 "gl_Position gl_PointSize gl_ClipVertex " +
438 "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
439 "gl_TexCoord gl_FogFragCoord " +
440 "gl_FragCoord gl_FrontFacing " +
441 "gl_FragColor gl_FragData gl_FragDepth " +
442 "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
443 "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
444 "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
445 "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
446 "gl_ProjectionMatrixInverseTranspose " +
447 "gl_ModelViewProjectionMatrixInverseTranspose " +
448 "gl_TextureMatrixInverseTranspose " +
449 "gl_NormalScale gl_DepthRange gl_ClipPlane " +
450 "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
451 "gl_FrontLightModelProduct gl_BackLightModelProduct " +
452 "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
453 "gl_FogParameters " +
454 "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
455 "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
456 "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
457 "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
458 "gl_MaxDrawBuffers"),
459 hooks: {"#": cppHook},
460 modeProps: {fold: ["brace", "include"]}
465 keywords: words(cKeywords + "as atomic async call command component components configuration event generic " +
466 "implementation includes interface module new norace nx_struct nx_union post provides " +
467 "signal task uses abstract extends"),
468 blockKeywords: words("case do else for if switch while struct"),
469 atoms: words("null"),
470 hooks: {"#": cppHook},
471 modeProps: {fold: ["brace", "include"]}
474 def("text/x-objectivec", {
476 keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginery BOOL Class bycopy byref id IMP in " +
477 "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),
478 atoms: words("YES NO NULL NILL ON OFF"),
480 "@": function(stream) {
481 stream.eatWhile(/[\w\$]/);
486 modeProps: {fold: "brace"}