all repos — NoPaste @ 5c12c8a8f515faa64a6cd1d3f04d9aa60561322d

Resurrected - The PussTheCat.org fork of NoPaste

scripts/CodeMirror/mode/clojure/clojure.js (view raw)

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