clike.js 11 KB

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