clike.js 17 KB

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