Advertisement
Guest User

Untitled

a guest
Dec 1st, 2015
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.75 KB | None | 0 0
  1. CodeMirror.defineMode("clojure", function () {
  2. var BUILTIN = "builtin", COMMENT = "comment", COMMENTFORM = "comment comment-form"; STRING = "string", CHAR = "char",
  3. ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword", META = "meta";
  4. var INDENT_WORD_SKIP = 2;
  5.  
  6. function makeKeywords(str) {
  7. var obj = {}, words = str.split(" ");
  8. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  9. return obj;
  10. }
  11.  
  12. var atoms = makeKeywords("true false nil");
  13.  
  14. var keywords = makeKeywords(
  15. "s/defn defn defn- def def- s/def defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject 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");
  16.  
  17. var builtins = makeKeywords(
  18. "* *' *1 *2 *3 *agent* *allow-unresolved-vars* *assert* *clojure-version* *command-line-args* *compile-files* *compile-path* *compiler-options* *data-readers* *e *err* *file* *flush-on-newline* *fn-loader* *in* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *unchecked-math* *use-context-classloader* *verbose-defrecords* *warn-on-reflection* + +' - -' -> ->> ->ArrayChunk ->Vec ->VecNode ->VecSeq -cache-protocol-fn -reset-methods .. / < <= = == > >= EMPTY-NODE accessor aclone add-classpath add-watch agent agent-error 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 biginteger 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* bound? 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 dec' decimal? declare default-data-readers definline definterface defmacro defmethod defmulti defn defn- defonce defprotocol defrecord defstruct deftype delay delay? deliver denominator deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq error-handler error-mode eval even? every-pred every? ex-data ex-info extend extend-protocol extend-type extenders extends? false? ffirst file-seq filter filterv find find-keyword find-ns find-protocol-impl find-protocol-method find-var first flatten float float-array float? floats flush fn fn? fnext fnil for force format frequencies 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 group-by hash hash-combine hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc inc' init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt keep keep-indexed 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-indexed map? mapcat mapv max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod munge name namespace namespace-munge 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 nthrest num number? numerator object-array odd? or parents partial partition partition-all partition-by pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-dup print-method print-simple 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 rand-nth range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string realized? reduce reduce-kv reductions ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure reify release-pending-sends rem remove remove-all-methods remove-method remove-ns remove-watch repeat repeatedly replace replicate require reset! reset-meta! resolve rest restart-agent resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-error-handler! set-error-mode! set-validator! set? short short-array shorts shuffle shutdown-agents slurp some some-fn sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-symbol? spit split-at split-with str string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync take take-last take-nth take-while test the-ns thread-bound? time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-add-int unchecked-byte unchecked-char unchecked-dec unchecked-dec-int unchecked-divide-int unchecked-double unchecked-float unchecked-inc unchecked-inc-int unchecked-int unchecked-long unchecked-multiply unchecked-multiply-int unchecked-negate unchecked-negate-int unchecked-remainder-int unchecked-short unchecked-subtract unchecked-subtract-int underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector-of 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 with-redefs with-redefs-fn xml-seq zero? zipmap *default-data-reader-fn* as-> cond-> cond->> reduced reduced? send-via set-agent-send-executor! set-agent-send-off-executor! some-> some->>");
  19.  
  20. var indentKeys = makeKeywords(
  21. // Built-ins
  22. "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 " +
  23.  
  24. // Binding forms
  25. "let letfn binding loop for doseq dotimes when-let if-let " +
  26.  
  27. // Data structures
  28. "defstruct struct-map assoc " +
  29.  
  30. // clojure.test
  31. "testing deftest " +
  32.  
  33. // contrib
  34. "handler-case handle dotrace deftrace");
  35.  
  36. var opposites = {")": "(",
  37. "]": "[",
  38. "}": "{"};
  39.  
  40. var tests = {
  41. digit: /\d/,
  42. digit_or_colon: /[\d:]/,
  43. hex: /[0-9a-f]/i,
  44. sign: /[+-]/,
  45. exponent: /e/i,
  46. char: /[^\s\(\[\{\}\]\)]/,
  47. keyword_char: /[^\s\(\[\;\)\]]/,
  48. basic: /[\w\$_\-\.\*\+\/\?\><!]/,
  49. lang_keyword: /[\w\*\+!\-_?:\/\.#=><]/,
  50. block_indent: /^(?:def|with)[^\/]+$|\/(?:def|with)/
  51. };
  52.  
  53. function stateStack(indent, type, prev) { // represents a state stack object
  54. this.indent = indent;
  55. this.type = type;
  56. this.prev = prev;
  57. }
  58.  
  59. function pushStack(state, indent, type) {
  60. state.indentStack = new stateStack(indent, type, state.indentStack);
  61. }
  62.  
  63. function popStack(state) {
  64. state.indentStack = state.indentStack.prev;
  65. }
  66.  
  67. function isNumber(ch, stream){
  68. // hex
  69. if ( ch === '0' && stream.eat(/x/i) ) {
  70. stream.eatWhile(tests.hex);
  71. return true;
  72. }
  73.  
  74. // leading sign
  75. if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) {
  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 ( stream.eat(tests.exponent) ) {
  90. stream.eat(tests.sign);
  91. stream.eatWhile(tests.digit);
  92. }
  93.  
  94. return true;
  95. }
  96.  
  97. return false;
  98. }
  99.  
  100. function eatString(stream) {
  101. var next, escaped = false;
  102. while ((next = stream.next()) != null) {
  103. if (next == "\"" && !escaped) {
  104. return false;
  105. }
  106. escaped = !escaped && next == "\\";
  107. }
  108. return "string";
  109. }
  110.  
  111. function openForm(ch, stream, state, commentForms) {
  112. var keyWord = '', origpos = stream.pos, indentTemp = stream.column(), letter;
  113. if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) {
  114. keyWord += letter;
  115. }
  116.  
  117. if (keyWord.length > 0 && keyWord == "comment" && commentForms) {
  118. state.mode = "comment";
  119. pushStack(state, indentTemp + INDENT_WORD_SKIP, "comment");
  120. } else if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) ||
  121. tests.block_indent.test(keyWord))) { // indent-word
  122. pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
  123. } else { // non-indent word
  124. // we continue eating the spaces
  125. stream.eatSpace();
  126. if (stream.eol() || stream.peek() == ";") {
  127. // nothing significant after
  128. // we restart indentation 1 space after
  129. pushStack(state, indentTemp + 1, ch);
  130. } else {
  131. pushStack(state, indentTemp + stream.current().length, ch); // else we match
  132. }
  133. }
  134. stream.pos = origpos; // undo all the eating
  135. }
  136.  
  137. function closeForm(ch, stream, state) {
  138. if (!state.indentStack) return;
  139.  
  140. if (state.indentStack.type == opposites[ch]) {
  141. popStack(state);
  142. }
  143. }
  144.  
  145. function commentForm(stream, state) {
  146. var next, escaped = false;
  147. while ((next = stream.next()) != null) {
  148. if (next == "\"") {
  149. return "comment-string";
  150. }
  151. if (next == "(" || next == "[" || next == "{") {
  152. openForm(next, stream, state);
  153. } else if (next == ")" && state.indentStack.type == "comment") {
  154. popStack(state);
  155. stream.backUp(1);
  156. return false;
  157. } else if(next == ")" || next == "]" || next == "}") {
  158. closeForm(next, stream, state);
  159. }
  160.  
  161. }
  162. return "comment";
  163. }
  164.  
  165. return {
  166. startState: function () {
  167. return {
  168. indentStack: null,
  169. indentation: 0,
  170. mode: false
  171. };
  172. },
  173.  
  174. token: function (stream, state) {
  175. if (state.indentStack == null && stream.sol()) {
  176. // update indentation, but only if indentStack is empty
  177. state.indentation = stream.indentation();
  178. }
  179.  
  180. // skip spaces
  181. if (state.mode != "string" && stream.eatSpace()) {
  182. return null;
  183. }
  184. var returnType = null;
  185.  
  186. switch(state.mode){
  187. case "string": // multi-line string parsing mode
  188. state.mode = eatString(stream);
  189. returnType = STRING; // continue on in string mode
  190. break;
  191.  
  192. case "comment-string":
  193. var mode = eatString(stream);
  194. if(!mode) {
  195. state.mode = "comment";
  196. }
  197. returnType = COMMENTFORM;
  198. break;
  199.  
  200. case "comment":
  201. state.mode = commentForm(stream, state);
  202. returnType = COMMENTFORM;
  203. break;
  204.  
  205. default: // default parsing mode
  206. var ch = stream.next();
  207.  
  208. if (ch == "\"") {
  209. state.mode = "string";
  210. returnType = STRING;
  211. } else if (ch == "\\") {
  212. stream.next();
  213. returnType = CHAR;
  214. } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) {
  215. returnType = ATOM;
  216. /* } else if (ch == "^" && (stream.peek() == ":" || stream.peek() == "{") {*/
  217. /*returnType = META;*/
  218. } else if (ch == ";") { // comment
  219. stream.skipToEnd(); // rest of the line is a comment
  220. returnType = COMMENT;
  221. } else if (isNumber(ch,stream)){
  222. returnType = NUMBER;
  223. } else if (ch == "(" || ch == "[" || ch == "{") {
  224. /**
  225. Either
  226. (indent-word ..
  227. (non-indent-word ..
  228. (;something else, bracket, etc.
  229. */
  230. openForm(ch, stream, state, this.commentForms);
  231. returnType = BRACKET;
  232. } else if (ch == ")" || ch == "]" || ch == "}") {
  233. closeForm(ch, stream, state);
  234. returnType = BRACKET;
  235. } else if ( ch == ":" ) {
  236. stream.eatWhile(tests.lang_keyword);
  237. return ATOM;
  238. } else {
  239. stream.eatWhile(tests.lang_keyword);
  240.  
  241. if (keywords && keywords.propertyIsEnumerable(stream.current())) {
  242. returnType = KEYWORD;
  243. } else if (builtins && builtins.propertyIsEnumerable(stream.current())) {
  244. returnType = BUILTIN;
  245. } else if (atoms && atoms.propertyIsEnumerable(stream.current())) {
  246. returnType = ATOM;
  247. } else returnType = null;
  248. }
  249. }
  250.  
  251. return returnType;
  252. },
  253.  
  254. indent: function (state) {
  255. if (state.indentStack == null) return state.indentation;
  256. return state.indentStack.indent;
  257. },
  258.  
  259. commentForms: false,
  260.  
  261. lineComment: ";;",
  262. disallowSingleQuoteStrings: true
  263. };
  264. });
  265.  
  266. CodeMirror.defineMIME("text/x-clojure", "clojure");
  267. CodeMirror.defineMIME("text/x-clojurescript", "clojure");
  268. CodeMirror.defineMIME("clj", "clojure");
  269. CodeMirror.defineMIME("cljs", "clojure");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement