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