clike.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1);
  144. else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit;
  145. else return ctx.indented + (closing ? 0 : indentUnit);
  146. },
  147. electricChars: "{}",
  148. blockCommentStart: "/*",
  149. blockCommentEnd: "*/",
  150. lineComment: "//"
  151. };
  152. });
  153. (function() {
  154. function words(str) {
  155. var obj = {}, words = str.split(" ");
  156. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  157. return obj;
  158. }
  159. var cKeywords = "auto if break int case long char register continue return default short do sizeof " +
  160. "double static else struct entry switch extern typedef float union for unsigned " +
  161. "goto while enum void const signed volatile";
  162. function cppHook(stream, state) {
  163. if (!state.startOfLine) return false;
  164. for (;;) {
  165. if (stream.skipTo("\\")) {
  166. stream.next();
  167. if (stream.eol()) {
  168. state.tokenize = cppHook;
  169. break;
  170. }
  171. } else {
  172. stream.skipToEnd();
  173. state.tokenize = null;
  174. break;
  175. }
  176. }
  177. return "meta";
  178. }
  179. // C#-style strings where "" escapes a quote.
  180. function tokenAtString(stream, state) {
  181. var next;
  182. while ((next = stream.next()) != null) {
  183. if (next == '"' && !stream.eat('"')) {
  184. state.tokenize = null;
  185. break;
  186. }
  187. }
  188. return "string";
  189. }
  190. function mimes(ms, mode) {
  191. for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode);
  192. }
  193. mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], {
  194. name: "clike",
  195. keywords: words(cKeywords),
  196. blockKeywords: words("case do else for if switch while struct"),
  197. atoms: words("null"),
  198. hooks: {"#": cppHook}
  199. });
  200. mimes(["text/x-c++src", "text/x-c++hdr"], {
  201. name: "clike",
  202. keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " +
  203. "static_cast typeid catch operator template typename class friend private " +
  204. "this using const_cast inline public throw virtual delete mutable protected " +
  205. "wchar_t"),
  206. blockKeywords: words("catch class do else finally for if struct switch try while"),
  207. atoms: words("true false null"),
  208. hooks: {"#": cppHook}
  209. });
  210. CodeMirror.defineMIME("text/x-java", {
  211. name: "clike",
  212. keywords: words("abstract assert boolean break byte case catch char class const continue default " +
  213. "do double else enum extends final finally float for goto if implements import " +
  214. "instanceof int interface long native new package private protected public " +
  215. "return short static strictfp super switch synchronized this throw throws transient " +
  216. "try void volatile while"),
  217. blockKeywords: words("catch class do else finally for if switch try while"),
  218. atoms: words("true false null"),
  219. hooks: {
  220. "@": function(stream) {
  221. stream.eatWhile(/[\w\$_]/);
  222. return "meta";
  223. }
  224. }
  225. });
  226. CodeMirror.defineMIME("text/x-csharp", {
  227. name: "clike",
  228. keywords: words("abstract as base break case catch checked class const continue" +
  229. " default delegate do else enum event explicit extern finally fixed for" +
  230. " foreach goto if implicit in interface internal is lock namespace new" +
  231. " operator out override params private protected public readonly ref return sealed" +
  232. " sizeof stackalloc static struct switch this throw try typeof unchecked" +
  233. " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
  234. " global group into join let orderby partial remove select set value var yield"),
  235. blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
  236. builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" +
  237. " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" +
  238. " UInt64 bool byte char decimal double short int long object" +
  239. " sbyte float string ushort uint ulong"),
  240. atoms: words("true false null"),
  241. hooks: {
  242. "@": function(stream, state) {
  243. if (stream.eat('"')) {
  244. state.tokenize = tokenAtString;
  245. return tokenAtString(stream, state);
  246. }
  247. stream.eatWhile(/[\w\$_]/);
  248. return "meta";
  249. }
  250. }
  251. });
  252. CodeMirror.defineMIME("text/x-scala", {
  253. name: "clike",
  254. keywords: words(
  255. /* scala */
  256. "abstract case catch class def do else extends false final finally for forSome if " +
  257. "implicit import lazy match new null object override package private protected return " +
  258. "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " +
  259. "<% >: # @ " +
  260. /* package scala */
  261. "assert assume require print println printf readLine readBoolean readByte readShort " +
  262. "readChar readInt readLong readFloat readDouble " +
  263. "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
  264. "Enumeration Equiv Error Exception Fractional Function IndexedSeq Integral Iterable " +
  265. "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
  266. "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
  267. "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector :: #:: " +
  268. /* package java.lang */
  269. "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
  270. "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
  271. "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
  272. "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
  273. ),
  274. blockKeywords: words("catch class do else finally for forSome if match switch try while"),
  275. atoms: words("true false null"),
  276. hooks: {
  277. "@": function(stream) {
  278. stream.eatWhile(/[\w\$_]/);
  279. return "meta";
  280. }
  281. }
  282. });
  283. }());