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 var isOperatorChar
= /[+\-*&%=<>!?|\/]/;
28 function tokenBase(stream
, state
) {
29 var ch
= stream
.next();
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
)) {
43 stream
.eatWhile(/[\w\.]/);
47 if (stream
.eat("*")) {
48 state
.tokenize
= tokenComment
;
49 return tokenComment(stream
, state
);
51 if (stream
.eat("/")) {
56 if (isOperatorChar
.test(ch
)) {
57 stream
.eatWhile(isOperatorChar
);
60 stream
.eatWhile(/[\w\$_]/);
61 var cur
= stream
.current();
62 if (keywords
.propertyIsEnumerable(cur
)) {
63 if (blockKeywords
.propertyIsEnumerable(cur
)) curPunc
= "newstatement";
66 if (builtin
.propertyIsEnumerable(cur
)) {
67 if (blockKeywords
.propertyIsEnumerable(cur
)) curPunc
= "newstatement";
70 if (atoms
.propertyIsEnumerable(cur
)) return "atom";
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;
87 function tokenComment(stream
, state
) {
88 var maybeEnd
= false, ch
;
89 while (ch
= stream
.next()) {
90 if (ch
== "/" && maybeEnd
) {
91 state
.tokenize
= null;
94 maybeEnd
= (ch
== "*");
99 function Context(indented
, column
, type
, align
, prev
) {
100 this.indented
= indented
;
101 this.column
= column
;
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
;
122 startState: function(basecolumn
) {
125 context
: new Context((basecolumn
|| 0) - indentUnit
, 0, "top", false),
131 token: function(stream
, state
) {
132 var ctx
= state
.context
;
134 if (ctx
.align
== null) ctx
.align
= false;
135 state
.indented
= stream
.indentation();
136 state
.startOfLine
= true;
138 if (stream
.eatSpace()) return 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;
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
);
172 blockCommentStart
: "/*",
173 blockCommentEnd
: "*/",
179 function words(str
) {
180 var obj
= {}, words
= str
.split(" ");
181 for (var i
= 0; i
< words
.length
; ++i
) obj
[words
[i
]] = true;
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;
191 if (stream
.skipTo("\\")) {
194 state
.tokenize
= cppHook
;
199 state
.tokenize
= null;
206 function cpp11StringHook(stream
, state
) {
209 if (stream
.match(/(R|u8R|uR|UR|LR)/)) {
210 var match
= stream
.match(/"([^\s\\()]{0,16})\(/);
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)) {
230 // C#-style strings where "" escapes a quote.
231 function tokenAtString(stream
, state
) {
233 while ((next
= stream
.next()) != null) {
234 if (next
== '"' && !stream
.eat('"')) {
235 state
.tokenize
= null;
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
+ '"'));
249 state
.tokenize
= null;
255 function def(mimes
, mode
) {
256 if (typeof mimes
== "string") mimes
= [mimes
];
259 if (obj
) for (var prop
in obj
) if (obj
.hasOwnProperty(prop
))
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"], {
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"], {
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"),
294 "u": cpp11StringHook
,
295 "U": cpp11StringHook
,
296 "L": cpp11StringHook
,
299 modeProps
: {fold
: ["brace", "include"]}
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"),
311 "@": function(stream
) {
312 stream
.eatWhile(/[\w\$_]/);
316 modeProps
: {fold
: ["brace", "import"]}
318 def("text/x-csharp", {
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"),
334 "@": function(stream
, state
) {
335 if (stream
.eat('"')) {
336 state
.tokenize
= tokenAtString
;
337 return tokenAtString(stream
, state
);
339 stream
.eatWhile(/[\w\$_]/);
344 def("text/x-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 _ : = => <- <: " +
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"),
375 "@": function(stream
) {
376 stream
.eatWhile(/[\w\$_]/);
381 def(["x-shader/x-vertex", "x-shader/x-fragment"], {
383 keywords
: words("float int bool void " +
384 "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
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 " +
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 " +
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"]}