clike.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. CodeMirror.defineMode("clike", function(config, parserConfig) {
  2. var indentUnit = config.indentUnit,
  3. statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
  4. keywords = parserConfig.keywords || {},
  5. builtin = parserConfig.builtin || {},
  6. blockKeywords = parserConfig.blockKeywords || {},
  7. atoms = parserConfig.atoms || {},
  8. hooks = parserConfig.hooks || {},
  9. multiLineStrings = parserConfig.multiLineStrings;
  10. var isOperatorChar = /[+\-*&%=<>!?|\/]/;
  11. var curPunc;
  12. function tokenBase(stream, state) {
  13. var ch = stream.next();
  14. if (hooks[ch]) {
  15. var result = hooks[ch](stream, state);
  16. if (result !== false) return result;
  17. }
  18. if (ch == '"' || ch == "'") {
  19. state.tokenize = tokenString(ch);
  20. return state.tokenize(stream, state);
  21. }
  22. if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
  23. curPunc = ch;
  24. return null;
  25. }
  26. if (/\d/.test(ch)) {
  27. stream.eatWhile(/[\w\.]/);
  28. return "number";
  29. }
  30. if (ch == "/") {
  31. if (stream.eat("*")) {
  32. state.tokenize = tokenComment;
  33. return tokenComment(stream, state);
  34. }
  35. if (stream.eat("/")) {
  36. stream.skipToEnd();
  37. return "comment";
  38. }
  39. }
  40. if (isOperatorChar.test(ch)) {
  41. stream.eatWhile(isOperatorChar);
  42. return "operator";
  43. }
  44. stream.eatWhile(/[\w\$_]/);
  45. var cur = stream.current();
  46. if (keywords.propertyIsEnumerable(cur)) {
  47. if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
  48. return "keyword";
  49. }
  50. if (builtin.propertyIsEnumerable(cur)) {
  51. if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement";
  52. return "builtin";
  53. }
  54. if (atoms.propertyIsEnumerable(cur)) return "atom";
  55. return "variable";
  56. }
  57. function tokenString(quote) {
  58. return function(stream, state) {
  59. var escaped = false, next, end = false;
  60. while ((next = stream.next()) != null) {
  61. if (next == quote && !escaped) {end = true; break;}
  62. escaped = !escaped && next == "\\";
  63. }
  64. if (end || !(escaped || multiLineStrings))
  65. state.tokenize = null;
  66. return "string";
  67. };
  68. }
  69. function tokenComment(stream, state) {
  70. var maybeEnd = false, ch;
  71. while (ch = stream.next()) {
  72. if (ch == "/" && maybeEnd) {
  73. state.tokenize = null;
  74. break;
  75. }
  76. maybeEnd = (ch == "*");
  77. }
  78. return "comment";
  79. }
  80. function Context(indented, column, type, align, prev) {
  81. this.indented = indented;
  82. this.column = column;
  83. this.type = type;
  84. this.align = align;
  85. this.prev = prev;
  86. }
  87. function pushContext(state, col, type) {
  88. var indent = state.indented;
  89. if (state.context && state.context.type == "statement")
  90. indent = state.context.indented;
  91. return state.context = new Context(indent, col, type, null, state.context);
  92. }
  93. function popContext(state) {
  94. var t = state.context.type;
  95. if (t == ")" || t == "]" || t == "}")
  96. state.indented = state.context.indented;
  97. return state.context = state.context.prev;
  98. }
  99. // Interface
  100. return {
  101. startState: function(basecolumn) {
  102. return {
  103. tokenize: null,
  104. context: new Context((basecolumn || 0) - indentUnit, 0, "top", false),
  105. indented: 0,
  106. startOfLine: true
  107. };
  108. },
  109. token: function(stream, state) {
  110. var ctx = state.context;
  111. if (stream.sol()) {
  112. if (ctx.align == null) ctx.align = false;
  113. state.indented = stream.indentation();
  114. state.startOfLine = true;
  115. }
  116. if (stream.eatSpace()) return null;
  117. curPunc = null;
  118. var style = (state.tokenize || tokenBase)(stream, state);
  119. if (style == "comment" || style == "meta") return style;
  120. if (ctx.align == null) ctx.align = true;
  121. if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state);
  122. else if (curPunc == "{") pushContext(state, stream.column(), "}");
  123. else if (curPunc == "[") pushContext(state, stream.column(), "]");
  124. else if (curPunc == "(") pushContext(state, stream.column(), ")");
  125. else if (curPunc == "}") {
  126. while (ctx.type == "statement") ctx = popContext(state);
  127. if (ctx.type == "}") ctx = popContext(state);
  128. while (ctx.type == "statement") ctx = popContext(state);
  129. }
  130. else if (curPunc == ctx.type) popContext(state);
  131. else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))
  132. pushContext(state, stream.column(), "statement");
  133. state.startOfLine = false;
  134. return style;
  135. },
  136. indent: function(state, textAfter) {
  137. if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass;
  138. var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
  139. if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
  140. var closing = firstChar == ctx.type;
  141. if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
  142. else if (ctx.align) return ctx.column + (closing ? 0 : 1);
  143. else return ctx.indented + (closing ? 0 : indentUnit);
  144. },
  145. electricChars: "{}"
  146. };
  147. });
  148. (function() {
  149. function words(str) {
  150. var obj = {}, words = str.split(" ");
  151. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  152. return obj;
  153. }
  154. var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
  155. "double static else struct entry switch extern typedef float union for unsigned " +
  156. "goto while enum void const signed volatile";
  157. function cppHook(stream, state) {
  158. if (!state.startOfLine) return false;
  159. for (;;) {
  160. if (stream.skipTo("\\")) {
  161. stream.next();
  162. if (stream.eol()) {
  163. state.tokenize = cppHook;
  164. break;
  165. }
  166. } else {
  167. stream.skipToEnd();
  168. state.tokenize = null;
  169. break;
  170. }
  171. }
  172. return "meta";
  173. }
  174. // C#-style strings where "" escapes a quote.
  175. function tokenAtString(stream, state) {
  176. var next;
  177. while ((next = stream.next()) != null) {
  178. if (next == '"' && !stream.eat('"')) {
  179. state.tokenize = null;
  180. break;
  181. }
  182. }
  183. return "string";
  184. }
  185. function mimes(ms, mode) {
  186. for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
  187. }
  188. mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
  189. name: "clike",
  190. keywords: words(cKeywords),
  191. blockKeywords: words("case do else for if switch while struct"),
  192. atoms: words("null"),
  193. hooks: {"#": cppHook}
  194. });
  195. mimes(["text/x-c++src", "text/x-c++hdr"], {
  196. name: "clike",
  197. keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
  198. "static_cast typeid catch operator template typename class friend private " +
  199. "this using const_cast inline public throw virtual delete mutable protected " +
  200. "wchar_t"),
  201. blockKeywords: words("catch class do else finally for if struct switch try while"),
  202. atoms: words("true false null"),
  203. hooks: {"#": cppHook}
  204. });
  205. CodeMirror.defineMIME("text/x-java", {
  206. name: "clike",
  207. keywords: words("abstract assert boolean break byte case catch char class const continue default " +
  208. "do double else enum extends final finally float for goto if implements import " +
  209. "instanceof int interface long native new package private protected public " +
  210. "return short static strictfp super switch synchronized this throw throws transient " +
  211. "try void volatile while"),
  212. blockKeywords: words("catch class do else finally for if switch try while"),
  213. atoms: words("true false null"),
  214. hooks: {
  215. "@": function(stream) {
  216. stream.eatWhile(/[\w\$_]/);
  217. return "meta";
  218. }
  219. }
  220. });
  221. CodeMirror.defineMIME("text/x-csharp", {
  222. name: "clike",
  223. keywords: words("abstract as base break case catch checked class const continue" +
  224. " default delegate do else enum event explicit extern finally fixed for" +
  225. " foreach goto if implicit in interface internal is lock namespace new" +
  226. " operator out override params private protected public readonly ref return sealed" +
  227. " sizeof stackalloc static struct switch this throw try typeof unchecked" +
  228. " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
  229. " global group into join let orderby partial remove select set value var yield"),
  230. blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
  231. builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
  232. " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
  233. " UInt64 bool byte char decimal double short int long object" +
  234. " sbyte float string ushort uint ulong"),
  235. atoms: words("true false null"),
  236. hooks: {
  237. "@": function(stream, state) {
  238. if (stream.eat('"')) {
  239. state.tokenize = tokenAtString;
  240. return tokenAtString(stream, state);
  241. }
  242. stream.eatWhile(/[\w\$_]/);
  243. return "meta";
  244. }
  245. }
  246. });
  247. CodeMirror.defineMIME("text/x-scala", {
  248. name: "clike",
  249. keywords: words(
  250. /* scala */
  251. "abstract case catch class def do else extends false final finally for forSome if " +
  252. "implicit import lazy match new null object override package private protected return " +
  253. "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
  254. "<% >: # @ " +
  255. /* package scala */
  256. "assert assume require print println printf readLine readBoolean readByte readShort " +
  257. "readChar readInt readLong readFloat readDouble " +
  258. "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
  259. "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
  260. "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
  261. "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
  262. "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
  263. /* package java.lang */
  264. "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
  265. "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
  266. "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
  267. "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
  268. ),
  269. blockKeywords: words("catch class do else finally for forSome if match switch try while"),
  270. atoms: words("true false null"),
  271. hooks: {
  272. "@": function(stream) {
  273. stream.eatWhile(/[\w\$_]/);
  274. return "meta";
  275. }
  276. }
  277. });
  278. }());