Debian Codegraph @

codemirror-legacy-modes/mode/clojure.js

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