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.

clojure.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. /**
  4. * Author: Hans Engel
  5. * Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
  6. */
  7. (function(mod) {
  8. if (typeof exports == "object" && typeof module == "object") // CommonJS
  9. mod(require("../../lib/codemirror"));
  10. else if (typeof define == "function" && define.amd) // AMD
  11. define(["../../lib/codemirror"], mod);
  12. else // Plain browser env
  13. mod(CodeMirror);
  14. })(function(CodeMirror) {
  15. "use strict";
  16. CodeMirror.defineMode("clojure", function (options) {
  17. var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", CHARACTER = "string-2",
  18. ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword", VAR = "variable";
  19. var INDENT_WORD_SKIP = options.indentUnit || 2;
  20. var NORMAL_INDENT_UNIT = options.indentUnit || 2;
  21. function makeKeywords(str) {
  22. var obj = {}, words = str.split(" ");
  23. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  24. return obj;
  25. }
  26. var atoms = makeKeywords("true false nil");
  27. var keywords = makeKeywords(
  28. "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest " +
  29. "slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn " +
  30. "do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync " +
  31. "doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars " +
  32. "binding gen-class gen-and-load-class gen-and-save-class handler-case handle");
  33. var builtins = makeKeywords(
  34. "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* " +
  35. "*compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* " +
  36. "*math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* " +
  37. "*source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> " +
  38. "->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor " +
  39. "aclone add-classpath add-watch agent agent-error agent-errors aget alength alias all-ns alter alter-meta! " +
  40. "alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double " +
  41. "aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 " +
  42. "bases bean bigdec bigint biginteger binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set " +
  43. "bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* bound? butlast " +
  44. "byte byte-array bytes case cat cast char char-array char-escape-string char-name-string char? chars chunk chunk-append " +
  45. "chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors " +
  46. "clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement completing concat cond condp " +
  47. "conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec dec' decimal? " +
  48. "declare dedupe default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol " +
  49. "defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc " +
  50. "dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last " +
  51. "drop-while eduction empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info " +
  52. "extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword " +
  53. "find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? " +
  54. "fnext fnil for force format frequencies future future-call future-cancel future-cancelled? future-done? future? " +
  55. "gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator group-by hash " +
  56. "hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? " +
  57. "int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep " +
  58. "keep-indexed key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file " +
  59. "load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array " +
  60. "make-hierarchy map map-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods " +
  61. "min min-key mod munge name namespace namespace-munge neg? newline next nfirst nil? nnext not not-any? not-empty " +
  62. "not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias " +
  63. "ns-unmap nth nthnext nthrest num number? numerator object-array odd? or parents partial partition partition-all " +
  64. "partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers " +
  65. "primitives-classnames print print-ctor print-dup print-method print-simple print-str printf println println-str " +
  66. "prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues " +
  67. "quot rand rand-int rand-nth random-sample range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern " +
  68. "re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history " +
  69. "ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods " +
  70. "remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest " +
  71. "restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? " +
  72. "seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts " +
  73. "shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? " +
  74. "special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol " +
  75. "symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transduce " +
  76. "transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec " +
  77. "unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int " +
  78. "unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int "+
  79. "unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote " +
  80. "unquote-splicing update update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of " +
  81. "vector? volatile! volatile? vreset! vswap! when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context " +
  82. "with-local-vars with-meta with-open with-out-str with-precision with-redefs with-redefs-fn xml-seq zero? zipmap " +
  83. "*default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! " +
  84. "set-agent-send-off-executor! some-> some->>");
  85. var indentKeys = makeKeywords(
  86. // Built-ins
  87. "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto " +
  88. "locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type " +
  89. "try catch " +
  90. // Binding forms
  91. "let letfn binding loop for doseq dotimes when-let if-let " +
  92. // Data structures
  93. "defstruct struct-map assoc " +
  94. // clojure.test
  95. "testing deftest " +
  96. // contrib
  97. "handler-case handle dotrace deftrace");
  98. var tests = {
  99. digit: /\d/,
  100. digit_or_colon: /[\d:]/,
  101. hex: /[0-9a-f]/i,
  102. sign: /[+-]/,
  103. exponent: /e/i,
  104. keyword_char: /[^\s\(\[\;\)\]]/,
  105. symbol: /[\w*+!\-\._?:<>\/\xa1-\uffff]/,
  106. block_indent: /^(?:def|with)[^\/]+$|\/(?:def|with)/
  107. };
  108. function stateStack(indent, type, prev) { // represents a state stack object
  109. this.indent = indent;
  110. this.type = type;
  111. this.prev = prev;
  112. }
  113. function pushStack(state, indent, type) {
  114. state.indentStack = new stateStack(indent, type, state.indentStack);
  115. }
  116. function popStack(state) {
  117. state.indentStack = state.indentStack.prev;
  118. }
  119. function isNumber(ch, stream){
  120. // hex
  121. if ( ch === '0' && stream.eat(/x/i) ) {
  122. stream.eatWhile(tests.hex);
  123. return true;
  124. }
  125. // leading sign
  126. if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
  127. stream.eat(tests.sign);
  128. ch = stream.next();
  129. }
  130. if ( tests.digit.test(ch) ) {
  131. stream.eat(ch);
  132. stream.eatWhile(tests.digit);
  133. if ( '.' == stream.peek() ) {
  134. stream.eat('.');
  135. stream.eatWhile(tests.digit);
  136. } else if ('/' == stream.peek() ) {
  137. stream.eat('/');
  138. stream.eatWhile(tests.digit);
  139. }
  140. if ( stream.eat(tests.exponent) ) {
  141. stream.eat(tests.sign);
  142. stream.eatWhile(tests.digit);
  143. }
  144. return true;
  145. }
  146. return false;
  147. }
  148. // Eat character that starts after backslash \
  149. function eatCharacter(stream) {
  150. var first = stream.next();
  151. // Read special literals: backspace, newline, space, return.
  152. // Just read all lowercase letters.
  153. if (first && first.match(/[a-z]/) && stream.match(/[a-z]+/, true)) {
  154. return;
  155. }
  156. // Read unicode character: \u1000 \uA0a1
  157. if (first === "u") {
  158. stream.match(/[0-9a-z]{4}/i, true);
  159. }
  160. }
  161. return {
  162. startState: function () {
  163. return {
  164. indentStack: null,
  165. indentation: 0,
  166. mode: false
  167. };
  168. },
  169. token: function (stream, state) {
  170. if (state.indentStack == null && stream.sol()) {
  171. // update indentation, but only if indentStack is empty
  172. state.indentation = stream.indentation();
  173. }
  174. // skip spaces
  175. if (state.mode != "string" && stream.eatSpace()) {
  176. return null;
  177. }
  178. var returnType = null;
  179. switch(state.mode){
  180. case "string": // multi-line string parsing mode
  181. var next, escaped = false;
  182. while ((next = stream.next()) != null) {
  183. if (next == "\"" && !escaped) {
  184. state.mode = false;
  185. break;
  186. }
  187. escaped = !escaped && next == "\\";
  188. }
  189. returnType = STRING; // continue on in string mode
  190. break;
  191. default: // default parsing mode
  192. var ch = stream.next();
  193. if (ch == "\"") {
  194. state.mode = "string";
  195. returnType = STRING;
  196. } else if (ch == "\\") {
  197. eatCharacter(stream);
  198. returnType = CHARACTER;
  199. } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
  200. returnType = ATOM;
  201. } else if (ch == ";") { // comment
  202. stream.skipToEnd(); // rest of the line is a comment
  203. returnType = COMMENT;
  204. } else if (isNumber(ch,stream)){
  205. returnType = NUMBER;
  206. } else if (ch == "(" || ch == "[" || ch == "{" ) {
  207. var keyWord = '', indentTemp = stream.column(), letter;
  208. /**
  209. Either
  210. (indent-word ..
  211. (non-indent-word ..
  212. (;something else, bracket, etc.
  213. */
  214. if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
  215. keyWord += letter;
  216. }
  217. if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
  218. tests.block_indent.test(keyWord))) { // indent-word
  219. pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
  220. } else { // non-indent word
  221. // we continue eating the spaces
  222. stream.eatSpace();
  223. if (stream.eol() || stream.peek() == ";") {
  224. // nothing significant after
  225. // we restart indentation the user defined spaces after
  226. pushStack(state, indentTemp + NORMAL_INDENT_UNIT, ch);
  227. } else {
  228. pushStack(state, indentTemp + stream.current().length, ch); // else we match
  229. }
  230. }
  231. stream.backUp(stream.current().length - 1); // undo all the eating
  232. returnType = BRACKET;
  233. } else if (ch == ")" || ch == "]" || ch == "}") {
  234. returnType = BRACKET;
  235. if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : (ch == "]" ? "[" :"{"))) {
  236. popStack(state);
  237. }
  238. } else if ( ch == ":" ) {
  239. stream.eatWhile(tests.symbol);
  240. return ATOM;
  241. } else {
  242. stream.eatWhile(tests.symbol);
  243. if (keywords && keywords.propertyIsEnumerable(stream.current())) {
  244. returnType = KEYWORD;
  245. } else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
  246. returnType = BUILTIN;
  247. } else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
  248. returnType = ATOM;
  249. } else {
  250. returnType = VAR;
  251. }
  252. }
  253. }
  254. return returnType;
  255. },
  256. indent: function (state) {
  257. if (state.indentStack == null) return state.indentation;
  258. return state.indentStack.indent;
  259. },
  260. closeBrackets: {pairs: "()[]{}\"\""},
  261. lineComment: ";;"
  262. };
  263. });
  264. CodeMirror.defineMIME("text/x-clojure", "clojure");
  265. CodeMirror.defineMIME("text/x-clojurescript", "clojure");
  266. CodeMirror.defineMIME("application/edn", "clojure");
  267. });