You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

292 lines
15 KiB

7 months ago
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/5/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("clojure", function (options) {
  13. var atoms = ["false", "nil", "true"];
  14. var specialForms = [".", "catch", "def", "do", "if", "monitor-enter",
  15. "monitor-exit", "new", "quote", "recur", "set!", "throw", "try", "var"];
  16. var coreSymbols = ["*", "*'", "*1", "*2", "*3", "*agent*",
  17. "*allow-unresolved-vars*", "*assert*", "*clojure-version*",
  18. "*command-line-args*", "*compile-files*", "*compile-path*",
  19. "*compiler-options*", "*data-readers*", "*default-data-reader-fn*", "*e",
  20. "*err*", "*file*", "*flush-on-newline*", "*fn-loader*", "*in*",
  21. "*math-context*", "*ns*", "*out*", "*print-dup*", "*print-length*",
  22. "*print-level*", "*print-meta*", "*print-namespace-maps*",
  23. "*print-readably*", "*read-eval*", "*reader-resolver*", "*source-path*",
  24. "*suppress-read*", "*unchecked-math*", "*use-context-classloader*",
  25. "*verbose-defrecords*", "*warn-on-reflection*", "+", "+'", "-", "-'",
  26. "->", "->>", "->ArrayChunk", "->Eduction", "->Vec", "->VecNode",
  27. "->VecSeq", "-cache-protocol-fn", "-reset-methods", "..", "/", "<", "<=",
  28. "=", "==", ">", ">=", "EMPTY-NODE", "Inst", "StackTraceElement->vec",
  29. "Throwable->map", "accessor", "aclone", "add-classpath", "add-watch",
  30. "agent", "agent-error", "agent-errors", "aget", "alength", "alias",
  31. "all-ns", "alter", "alter-meta!", "alter-var-root", "amap", "ancestors",
  32. "and", "any?", "apply", "areduce", "array-map", "as->", "aset",
  33. "aset-boolean", "aset-byte", "aset-char", "aset-double", "aset-float",
  34. "aset-int", "aset-long", "aset-short", "assert", "assoc", "assoc!",
  35. "assoc-in", "associative?", "atom", "await", "await-for", "await1",
  36. "bases", "bean", "bigdec", "bigint", "biginteger", "binding", "bit-and",
  37. "bit-and-not", "bit-clear", "bit-flip", "bit-not", "bit-or", "bit-set",
  38. "bit-shift-left", "bit-shift-right", "bit-test", "bit-xor", "boolean",
  39. "boolean-array", "boolean?", "booleans", "bound-fn", "bound-fn*",
  40. "bound?", "bounded-count", "butlast", "byte", "byte-array", "bytes",
  41. "bytes?", "case", "cast", "cat", "char", "char-array",
  42. "char-escape-string", "char-name-string", "char?", "chars", "chunk",
  43. "chunk-append", "chunk-buffer", "chunk-cons", "chunk-first", "chunk-next",
  44. "chunk-rest", "chunked-seq?", "class", "class?", "clear-agent-errors",
  45. "clojure-version", "coll?", "comment", "commute", "comp", "comparator",
  46. "compare", "compare-and-set!", "compile", "complement", "completing",
  47. "concat", "cond", "cond->", "cond->>", "condp", "conj", "conj!", "cons",
  48. "constantly", "construct-proxy", "contains?", "count", "counted?",
  49. "create-ns", "create-struct", "cycle", "dec", "dec'", "decimal?",
  50. "declare", "dedupe", "default-data-readers", "definline", "definterface",
  51. "defmacro", "defmethod", "defmulti", "defn", "defn-", "defonce",
  52. "defprotocol", "defrecord", "defstruct", "deftype", "delay", "delay?",
  53. "deliver", "denominator", "deref", "derive", "descendants", "destructure",
  54. "disj", "disj!", "dissoc", "dissoc!", "distinct", "distinct?", "doall",
  55. "dorun", "doseq", "dosync", "dotimes", "doto", "double", "double-array",
  56. "double?", "doubles", "drop", "drop-last", "drop-while", "eduction",
  57. "empty", "empty?", "ensure", "ensure-reduced", "enumeration-seq",
  58. "error-handler", "error-mode", "eval", "even?", "every-pred", "every?",
  59. "ex-data", "ex-info", "extend", "extend-protocol", "extend-type",
  60. "extenders", "extends?", "false?", "ffirst", "file-seq", "filter",
  61. "filterv", "find", "find-keyword", "find-ns", "find-protocol-impl",
  62. "find-protocol-method", "find-var", "first", "flatten", "float",
  63. "float-array", "float?", "floats", "flush", "fn", "fn?", "fnext", "fnil",
  64. "for", "force", "format", "frequencies", "future", "future-call",
  65. "future-cancel", "future-cancelled?", "future-done?", "future?",
  66. "gen-class", "gen-interface", "gensym", "get", "get-in", "get-method",
  67. "get-proxy-class", "get-thread-bindings", "get-validator", "group-by",
  68. "halt-when", "hash", "hash-combine", "hash-map", "hash-ordered-coll",
  69. "hash-set", "hash-unordered-coll", "ident?", "identical?", "identity",
  70. "if-let", "if-not", "if-some", "ifn?", "import", "in-ns", "inc", "inc'",
  71. "indexed?", "init-proxy", "inst-ms", "inst-ms*", "inst?", "instance?",
  72. "int", "int-array", "int?", "integer?", "interleave", "intern",
  73. "interpose", "into", "into-array", "ints", "io!", "isa?", "iterate",
  74. "iterator-seq", "juxt", "keep", "keep-indexed", "key", "keys", "keyword",
  75. "keyword?", "last", "lazy-cat", "lazy-seq", "let", "letfn", "line-seq",
  76. "list", "list*", "list?", "load", "load-file", "load-reader",
  77. "load-string", "loaded-libs", "locking", "long", "long-array", "longs",
  78. "loop", "macroexpand", "macroexpand-1", "make-array", "make-hierarchy",
  79. "map", "map-entry?", "map-indexed", "map?", "mapcat", "mapv", "max",
  80. "max-key", "memfn", "memoize", "merge", "merge-with", "meta",
  81. "method-sig", "methods", "min", "min-key", "mix-collection-hash", "mod",
  82. "munge", "name", "namespace", "namespace-munge", "nat-int?", "neg-int?",
  83. "neg?", "newline", "next", "nfirst", "nil?", "nnext", "not", "not-any?",
  84. "not-empty", "not-every?", "not=", "ns", "ns-aliases", "ns-imports",
  85. "ns-interns", "ns-map", "ns-name", "ns-publics", "ns-refers",
  86. "ns-resolve", "ns-unalias", "ns-unmap", "nth", "nthnext", "nthrest",
  87. "num", "number?", "numerator", "object-array", "odd?", "or", "parents",
  88. "partial", "partition", "partition-all", "partition-by", "pcalls", "peek",
  89. "persistent!", "pmap", "pop", "pop!", "pop-thread-bindings", "pos-int?",
  90. "pos?", "pr", "pr-str", "prefer-method", "prefers",
  91. "primitives-classnames", "print", "print-ctor", "print-dup",
  92. "print-method", "print-simple", "print-str", "printf", "println",
  93. "println-str", "prn", "prn-str", "promise", "proxy",
  94. "proxy-call-with-super", "proxy-mappings", "proxy-name", "proxy-super",
  95. "push-thread-bindings", "pvalues", "qualified-ident?",
  96. "qualified-keyword?", "qualified-symbol?", "quot", "rand", "rand-int",
  97. "rand-nth", "random-sample", "range", "ratio?", "rational?",
  98. "rationalize", "re-find", "re-groups", "re-matcher", "re-matches",
  99. "re-pattern", "re-seq", "read", "read-line", "read-string",
  100. "reader-conditional", "reader-conditional?", "realized?", "record?",
  101. "reduce", "reduce-kv", "reduced", "reduced?", "reductions", "ref",
  102. "ref-history-count", "ref-max-history", "ref-min-history", "ref-set",
  103. "refer", "refer-clojure", "reify", "release-pending-sends", "rem",
  104. "remove", "remove-all-methods", "remove-method", "remove-ns",
  105. "remove-watch", "repeat", "repeatedly", "replace", "replicate", "require",
  106. "reset!", "reset-meta!", "reset-vals!", "resolve", "rest",
  107. "restart-agent", "resultset-seq", "reverse", "reversible?", "rseq",
  108. "rsubseq", "run!", "satisfies?", "second", "select-keys", "send",
  109. "send-off", "send-via", "seq", "seq?", "seqable?", "seque", "sequence",
  110. "sequential?", "set", "set-agent-send-executor!",
  111. "set-agent-send-off-executor!", "set-error-handler!", "set-error-mode!",
  112. "set-validator!", "set?", "short", "short-array", "shorts", "shuffle",
  113. "shutdown-agents", "simple-ident?", "simple-keyword?", "simple-symbol?",
  114. "slurp", "some", "some->", "some->>", "some-fn", "some?", "sort",
  115. "sort-by", "sorted-map", "sorted-map-by", "sorted-set", "sorted-set-by",
  116. "sorted?", "special-symbol?", "spit", "split-at", "split-with", "str",
  117. "string?", "struct", "struct-map", "subs", "subseq", "subvec", "supers",
  118. "swap!", "swap-vals!", "symbol", "symbol?", "sync", "tagged-literal",
  119. "tagged-literal?", "take", "take-last", "take-nth", "take-while", "test",
  120. "the-ns", "thread-bound?", "time", "to-array", "to-array-2d",
  121. "trampoline", "transduce", "transient", "tree-seq", "true?", "type",
  122. "unchecked-add", "unchecked-add-int", "unchecked-byte", "unchecked-char",
  123. "unchecked-dec", "unchecked-dec-int", "unchecked-divide-int",
  124. "unchecked-double", "unchecked-float", "unchecked-inc",
  125. "unchecked-inc-int", "unchecked-int", "unchecked-long",
  126. "unchecked-multiply", "unchecked-multiply-int", "unchecked-negate",
  127. "unchecked-negate-int", "unchecked-remainder-int", "unchecked-short",
  128. "unchecked-subtract", "unchecked-subtract-int", "underive", "unquote",
  129. "unquote-splicing", "unreduced", "unsigned-bit-shift-right", "update",
  130. "update-in", "update-proxy", "uri?", "use", "uuid?", "val", "vals",
  131. "var-get", "var-set", "var?", "vary-meta", "vec", "vector", "vector-of",
  132. "vector?", "volatile!", "volatile?", "vreset!", "vswap!", "when",
  133. "when-first", "when-let", "when-not", "when-some", "while",
  134. "with-bindings", "with-bindings*", "with-in-str", "with-loading-context",
  135. "with-local-vars", "with-meta", "with-open", "with-out-str",
  136. "with-precision", "with-redefs", "with-redefs-fn", "xml-seq", "zero?",
  137. "zipmap"];
  138. var haveBodyParameter = [
  139. "->", "->>", "as->", "binding", "bound-fn", "case", "catch", "comment",
  140. "cond", "cond->", "cond->>", "condp", "def", "definterface", "defmethod",
  141. "defn", "defmacro", "defprotocol", "defrecord", "defstruct", "deftype",
  142. "do", "doseq", "dotimes", "doto", "extend", "extend-protocol",
  143. "extend-type", "fn", "for", "future", "if", "if-let", "if-not", "if-some",
  144. "let", "letfn", "locking", "loop", "ns", "proxy", "reify", "struct-map",
  145. "some->", "some->>", "try", "when", "when-first", "when-let", "when-not",
  146. "when-some", "while", "with-bindings", "with-bindings*", "with-in-str",
  147. "with-loading-context", "with-local-vars", "with-meta", "with-open",
  148. "with-out-str", "with-precision", "with-redefs", "with-redefs-fn"];
  149. CodeMirror.registerHelper("hintWords", "clojure",
  150. [].concat(atoms, specialForms, coreSymbols));
  151. var atom = createLookupMap(atoms);
  152. var specialForm = createLookupMap(specialForms);
  153. var coreSymbol = createLookupMap(coreSymbols);
  154. var hasBodyParameter = createLookupMap(haveBodyParameter);
  155. var delimiter = /^(?:[\\\[\]\s"(),;@^`{}~]|$)/;
  156. var numberLiteral = /^(?:[+\-]?\d+(?:(?:N|(?:[eE][+\-]?\d+))|(?:\.?\d*(?:M|(?:[eE][+\-]?\d+))?)|\/\d+|[xX][0-9a-fA-F]+|r[0-9a-zA-Z]+)?(?=[\\\[\]\s"#'(),;@^`{}~]|$))/;
  157. var characterLiteral = /^(?:\\(?:backspace|formfeed|newline|return|space|tab|o[0-7]{3}|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{4}|.)?(?=[\\\[\]\s"(),;@^`{}~]|$))/;
  158. // simple-namespace := /^[^\\\/\[\]\d\s"#'(),;@^`{}~.][^\\\[\]\s"(),;@^`{}~.\/]*/
  159. // simple-symbol := /^(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)/
  160. // qualified-symbol := (<simple-namespace>(<.><simple-namespace>)*</>)?<simple-symbol>
  161. var qualifiedSymbol = /^(?:(?:[^\\\/\[\]\d\s"#'(),;@^`{}~.][^\\\[\]\s"(),;@^`{}~.\/]*(?:\.[^\\\/\[\]\d\s"#'(),;@^`{}~.][^\\\[\]\s"(),;@^`{}~.\/]*)*\/)?(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*(?=[\\\[\]\s"(),;@^`{}~]|$))/;
  162. function base(stream, state) {
  163. if (stream.eatSpace() || stream.eat(",")) return ["space", null];
  164. if (stream.match(numberLiteral)) return [null, "number"];
  165. if (stream.match(characterLiteral)) return [null, "string-2"];
  166. if (stream.eat(/^"/)) return (state.tokenize = inString)(stream, state);
  167. if (stream.eat(/^[(\[{]/)) return ["open", "bracket"];
  168. if (stream.eat(/^[)\]}]/)) return ["close", "bracket"];
  169. if (stream.eat(/^;/)) {stream.skipToEnd(); return ["space", "comment"];}
  170. if (stream.eat(/^[#'@^`~]/)) return [null, "meta"];
  171. var matches = stream.match(qualifiedSymbol);
  172. var symbol = matches && matches[0];
  173. if (!symbol) {
  174. // advance stream by at least one character so we don't get stuck.
  175. stream.next();
  176. stream.eatWhile(function (c) {return !is(c, delimiter);});
  177. return [null, "error"];
  178. }
  179. if (symbol === "comment" && state.lastToken === "(")
  180. return (state.tokenize = inComment)(stream, state);
  181. if (is(symbol, atom) || symbol.charAt(0) === ":") return ["symbol", "atom"];
  182. if (is(symbol, specialForm) || is(symbol, coreSymbol)) return ["symbol", "keyword"];
  183. if (state.lastToken === "(") return ["symbol", "builtin"]; // other operator
  184. return ["symbol", "variable"];
  185. }
  186. function inString(stream, state) {
  187. var escaped = false, next;
  188. while (next = stream.next()) {
  189. if (next === "\"" && !escaped) {state.tokenize = base; break;}
  190. escaped = !escaped && next === "\\";
  191. }
  192. return [null, "string"];
  193. }
  194. function inComment(stream, state) {
  195. var parenthesisCount = 1;
  196. var next;
  197. while (next = stream.next()) {
  198. if (next === ")") parenthesisCount--;
  199. if (next === "(") parenthesisCount++;
  200. if (parenthesisCount === 0) {
  201. stream.backUp(1);
  202. state.tokenize = base;
  203. break;
  204. }
  205. }
  206. return ["space", "comment"];
  207. }
  208. function createLookupMap(words) {
  209. var obj = {};
  210. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  211. return obj;
  212. }
  213. function is(value, test) {
  214. if (test instanceof RegExp) return test.test(value);
  215. if (test instanceof Object) return test.propertyIsEnumerable(value);
  216. }
  217. return {
  218. startState: function () {
  219. return {
  220. ctx: {prev: null, start: 0, indentTo: 0},
  221. lastToken: null,
  222. tokenize: base
  223. };
  224. },
  225. token: function (stream, state) {
  226. if (stream.sol() && (typeof state.ctx.indentTo !== "number"))
  227. state.ctx.indentTo = state.ctx.start + 1;
  228. var typeStylePair = state.tokenize(stream, state);
  229. var type = typeStylePair[0];
  230. var style = typeStylePair[1];
  231. var current = stream.current();
  232. if (type !== "space") {
  233. if (state.lastToken === "(" && state.ctx.indentTo === null) {
  234. if (type === "symbol" && is(current, hasBodyParameter))
  235. state.ctx.indentTo = state.ctx.start + options.indentUnit;
  236. else state.ctx.indentTo = "next";
  237. } else if (state.ctx.indentTo === "next") {
  238. state.ctx.indentTo = stream.column();
  239. }
  240. state.lastToken = current;
  241. }
  242. if (type === "open")
  243. state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};
  244. else if (type === "close") state.ctx = state.ctx.prev || state.ctx;
  245. return style;
  246. },
  247. indent: function (state) {
  248. var i = state.ctx.indentTo;
  249. return (typeof i === "number") ?
  250. i :
  251. state.ctx.start + 1;
  252. },
  253. closeBrackets: {pairs: "()[]{}\"\""},
  254. lineComment: ";;"
  255. };
  256. });
  257. CodeMirror.defineMIME("text/x-clojure", "clojure");
  258. CodeMirror.defineMIME("text/x-clojurescript", "clojure");
  259. CodeMirror.defineMIME("application/edn", "clojure");
  260. });