aboutsummaryrefslogtreecommitdiff
path: root/imports/codemirror/mode/clojure/clojure.js
diff options
context:
space:
mode:
Diffstat (limited to 'imports/codemirror/mode/clojure/clojure.js')
-rwxr-xr-ximports/codemirror/mode/clojure/clojure.js207
1 files changed, 207 insertions, 0 deletions
diff --git a/imports/codemirror/mode/clojure/clojure.js b/imports/codemirror/mode/clojure/clojure.js
new file mode 100755
index 00000000..a951589e
--- /dev/null
+++ b/imports/codemirror/mode/clojure/clojure.js
@@ -0,0 +1,207 @@
1/**
2 * Author: Hans Engel
3 * Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun)
4 */
5CodeMirror.defineMode("clojure", function (config, mode) {
6 var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", TAG = "tag",
7 ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD="keyword";
8 var INDENT_WORD_SKIP = 2, KEYWORDS_SKIP = 1;
9
10 function makeKeywords(str) {
11 var obj = {}, words = str.split(" ");
12 for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
13 return obj;
14 }
15
16 var atoms = makeKeywords("true false nil");
17
18 var keywords = makeKeywords(
19 // Control structures
20 "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle" +
21
22 // Built-ins
23 "* *1 *2 *3 *agent* *allow-unresolved-vars* *assert *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - / < <= = == > >= accessor aclone agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map aset aset-boolean aset-byte aset-char aset-double aset-float aset-int aset-long aset-short assert assoc assoc! assoc-in associative? atom await await-for await1 bases bean bigdec bigint binding bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set bit-shift-left bit-shift-right bit-test bit-xor boolean boolean-array booleans bound-fn bound-fn* butlast byte byte-array bytes case cast char char-array char-escape-string char-name-string char? chars chunk chunk-append chunk-buffer chunk-cons chunk-first chunk-next chunk-rest chunked-seq? class class? clear-agent-errors clojure-version coll? comment commute comp comparator compare compare-and-set! compile complement concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? extend extend-protocol extend-type extends? extenders false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format future future-call future-cancel future-cancelled? future-done? future? gen-class gen-interface gensym get get-in get-method get-proxy-class get-thread-bindings get-validator hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt key keys keyword keyword? last lazy-cat lazy-seq let letfn line-seq list list* list? load load-file load-reader load-string loaded-libs locking long long-array longs loop macroexpand macroexpand-1 make-array make-hierarchy map map? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace neg? newline next nfirst nil? nnext not not-any? not-empty not-every? not= ns ns-aliases ns-imports ns-interns ns-map ns-name ns-publics ns-refers ns-resolve ns-unalias ns-unmap nth nthnext num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc print-str printf println println-str prn prn-str promise proxy proxy-call-with-super proxy-mappings proxy-name proxy-super push-thread-bindings pvalues quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reify reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq");
24
25 var indentKeys = makeKeywords(
26 // Built-ins
27 "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch" +
28
29 // Binding forms
30 "let letfn binding loop for doseq dotimes when-let if-let" +
31
32 // Data structures
33 "defstruct struct-map assoc" +
34
35 // clojure.test
36 "testing deftest" +
37
38 // contrib
39 "handler-case handle dotrace deftrace");
40
41 var tests = {
42 digit: /\d/,
43 digit_or_colon: /[\d:]/,
44 hex: /[0-9a-fA-F]/,
45 sign: /[+-]/,
46 exponent: /[eE]/,
47 keyword_char: /[^\s\(\[\;\)\]]/,
48 basic: /[\w\$_\-]/,
49 lang_keyword: /[\w*+!\-_?:\/]/
50 };
51
52 function stateStack(indent, type, prev) { // represents a state stack object
53 this.indent = indent;
54 this.type = type;
55 this.prev = prev;
56 }
57
58 function pushStack(state, indent, type) {
59 state.indentStack = new stateStack(indent, type, state.indentStack);
60 }
61
62 function popStack(state) {
63 state.indentStack = state.indentStack.prev;
64 }
65
66 function isNumber(ch, stream){
67 // hex
68 if ( ch === '0' && 'x' == stream.peek().toLowerCase() ) {
69 stream.eat('x');
70 stream.eatWhile(tests.hex);
71 return true;
72 }
73
74 // leading sign
75 if ( ch == '+' || ch == '-' ) {
76 stream.eat(tests.sign);
77 ch = stream.next();
78 }
79
80 if ( tests.digit.test(ch) ) {
81 stream.eat(ch);
82 stream.eatWhile(tests.digit);
83
84 if ( '.' == stream.peek() ) {
85 stream.eat('.');
86 stream.eatWhile(tests.digit);
87 }
88
89 if ( 'e' == stream.peek().toLowerCase() ) {
90 stream.eat(tests.exponent);
91 stream.eat(tests.sign);
92 stream.eatWhile(tests.digit);
93 }
94
95 return true;
96 }
97
98 return false;
99 }
100
101 return {
102 startState: function () {
103 return {
104 indentStack: null,
105 indentation: 0,
106 mode: false,
107 };
108 },
109
110 token: function (stream, state) {
111 if (state.indentStack == null && stream.sol()) {
112 // update indentation, but only if indentStack is empty
113 state.indentation = stream.indentation();
114 }
115
116 // skip spaces
117 if (stream.eatSpace()) {
118 return null;
119 }
120 var returnType = null;
121
122 switch(state.mode){
123 case "string": // multi-line string parsing mode
124 var next, escaped = false;
125 while ((next = stream.next()) != null) {
126 if (next == "\"" && !escaped) {
127
128 state.mode = false;
129 break;
130 }
131 escaped = !escaped && next == "\\";
132 }
133 returnType = STRING; // continue on in string mode
134 break;
135 default: // default parsing mode
136 var ch = stream.next();
137
138 if (ch == "\"") {
139 state.mode = "string";
140 returnType = STRING;
141 } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
142 returnType = ATOM;
143 } else if (ch == ";") { // comment
144 stream.skipToEnd(); // rest of the line is a comment
145 returnType = COMMENT;
146 } else if (isNumber(ch,stream)){
147 returnType = NUMBER;
148 } else if (ch == "(" || ch == "[") {
149 var keyWord = ''; var indentTemp = stream.column();
150 /**
151 Either
152 (indent-word ..
153 (non-indent-word ..
154 (;something else, bracket, etc.
155 */
156
157 while ((letter = stream.eat(tests.keyword_char)) != null) {
158 keyWord += letter;
159 }
160
161 if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
162
163 pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
164 } else { // non-indent word
165 // we continue eating the spaces
166 stream.eatSpace();
167 if (stream.eol() || stream.peek() == ";") {
168 // nothing significant after
169 // we restart indentation 1 space after
170 pushStack(state, indentTemp + 1, ch);
171 } else {
172 pushStack(state, indentTemp + stream.current().length, ch); // else we match
173 }
174 }
175 stream.backUp(stream.current().length - 1); // undo all the eating
176
177 returnType = BRACKET;
178 } else if (ch == ")" || ch == "]") {
179 returnType = BRACKET;
180 if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
181 popStack(state);
182 }
183 } else if ( ch == ":" ) {
184 stream.eatWhile(tests.lang_keyword);
185 return TAG;
186 } else {
187 stream.eatWhile(tests.basic);
188
189 if (keywords && keywords.propertyIsEnumerable(stream.current())) {
190 returnType = BUILTIN;
191 } else if ( atoms && atoms.propertyIsEnumerable(stream.current()) ) {
192 returnType = ATOM;
193 } else returnType = null;
194 }
195 }
196
197 return returnType;
198 },
199
200 indent: function (state, textAfter) {
201 if (state.indentStack == null) return state.indentation;
202 return state.indentStack.indent;
203 }
204 };
205});
206
207CodeMirror.defineMIME("text/x-clojure", "clojure");