PageRenderTime 65ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/packs/clojure/lib/clojure-mode/clojure-mode.el

https://github.com/designerdada/dotemacs
Emacs Lisp | 1106 lines | 860 code | 107 blank | 139 comment | 23 complexity | 80580fe6644f67601900799dabe25b78 MD5 | raw file
  1. ;;; clojure-mode.el --- Major mode for Clojure code
  2. ;; Copyright © 2007-2013 Jeffrey Chu, Lennart Staflin, Phil Hagelberg
  3. ;;
  4. ;; Authors: Jeffrey Chu <jochu0@gmail.com>
  5. ;; Lennart Staflin <lenst@lysator.liu.se>
  6. ;; Phil Hagelberg <technomancy@gmail.com>
  7. ;; URL: http://github.com/technomancy/clojure-mode
  8. ;; Version: 2.1.0
  9. ;; Keywords: languages, lisp
  10. ;; This file is not part of GNU Emacs.
  11. ;;; Commentary:
  12. ;; Provides font-lock, indentation, and navigation for the Clojure
  13. ;; language. (http://clojure.org)
  14. ;; Users of older Emacs (pre-22) should get version 1.4:
  15. ;; http://github.com/technomancy/clojure-mode/tree/1.4
  16. ;; Slime integration has been removed; see the 1.x releases if you need it.
  17. ;; Using clojure-mode with paredit is highly recommended. Use paredit
  18. ;; as you would with any other minor mode; for instance:
  19. ;;
  20. ;; ;; require or autoload paredit-mode
  21. ;; (add-hook 'clojure-mode-hook 'paredit-mode)
  22. ;; See nREPL.el (http://github.com/kingtim/nrepl.el) for
  23. ;; better interaction with subprocesses via nREPL.
  24. ;;; License:
  25. ;; This program is free software; you can redistribute it and/or
  26. ;; modify it under the terms of the GNU General Public License
  27. ;; as published by the Free Software Foundation; either version 3
  28. ;; of the License, or (at your option) any later version.
  29. ;;
  30. ;; This program is distributed in the hope that it will be useful,
  31. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. ;; GNU General Public License for more details.
  34. ;;
  35. ;; You should have received a copy of the GNU General Public License
  36. ;; along with GNU Emacs; see the file COPYING. If not, write to the
  37. ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  38. ;; Boston, MA 02110-1301, USA.
  39. ;;; Code:
  40. (eval-when-compile
  41. (defvar calculate-lisp-indent-last-sexp)
  42. (defvar font-lock-beg)
  43. (defvar font-lock-end)
  44. (defvar paredit-version)
  45. (defvar paredit-mode))
  46. (require 'cl)
  47. (require 'tramp)
  48. (require 'inf-lisp)
  49. (require 'imenu)
  50. (require 'easymenu)
  51. (declare-function clojure-test-jump-to-implementation "clojure-test-mode.el")
  52. (defconst clojure-font-lock-keywords
  53. (eval-when-compile
  54. `( ;; Definitions.
  55. (,(concat "(\\(?:clojure.core/\\)?\\("
  56. (regexp-opt '("defn" "defn-" "def" "defonce"
  57. "defmulti" "defmethod" "defmacro"
  58. "defstruct" "deftype" "defprotocol"
  59. "defrecord" "deftest" "def\\[a-z\\]"))
  60. ;; Function declarations.
  61. "\\)\\>"
  62. ;; Any whitespace
  63. "[ \r\n\t]*"
  64. ;; Possibly type or metadata
  65. "\\(?:#?^\\(?:{[^}]*}\\|\\sw+\\)[ \r\n\t]*\\)*"
  66. "\\(\\sw+\\)?")
  67. (1 font-lock-keyword-face)
  68. (2 font-lock-function-name-face nil t))
  69. ;; (fn name? args ...)
  70. (,(concat "(\\(?:clojure.core/\\)?\\(fn\\)[ \t]+"
  71. ;; Possibly type
  72. "\\(?:#?^\\sw+[ \t]*\\)?"
  73. ;; Possibly name
  74. "\\(t\\sw+\\)?" )
  75. (1 font-lock-keyword-face)
  76. (2 font-lock-function-name-face nil t))
  77. (,(concat "(\\(\\(?:[a-z\.-]+/\\)?def\[a-z\]*-?\\)"
  78. ;; Function declarations.
  79. "\\>"
  80. ;; Any whitespace
  81. "[ \r\n\t]*"
  82. ;; Possibly type or metadata
  83. "\\(?:#?^\\(?:{[^}]*}\\|\\sw+\\)[ \r\n\t]*\\)*"
  84. "\\(\\sw+\\)?")
  85. (1 font-lock-keyword-face)
  86. (2 font-lock-function-name-face nil t))
  87. ;; Deprecated functions
  88. (,(concat
  89. "(\\(?:clojure.core/\\)?"
  90. (regexp-opt
  91. '("add-watcher" "remove-watcher" "add-classpath") t)
  92. "\\>")
  93. 1 font-lock-warning-face)
  94. ;; Control structures
  95. (,(concat
  96. "(\\(?:clojure.core/\\)?"
  97. (regexp-opt
  98. '("let" "letfn" "do"
  99. "case" "cond" "condp"
  100. "for" "loop" "recur"
  101. "when" "when-not" "when-let" "when-first"
  102. "if" "if-let" "if-not"
  103. "." ".." "->" "->>" "doto"
  104. "and" "or"
  105. "dosync" "doseq" "dotimes" "dorun" "doall"
  106. "load" "import" "unimport" "ns" "in-ns" "refer"
  107. "try" "catch" "finally" "throw"
  108. "with-open" "with-local-vars" "binding"
  109. "gen-class" "gen-and-load-class" "gen-and-save-class"
  110. "handler-case" "handle") t)
  111. "\\>")
  112. 1 font-lock-keyword-face)
  113. ;; Built-ins
  114. (,(concat
  115. "(\\(?:clojure.core/\\)?"
  116. (regexp-opt
  117. '("*" "*1" "*2" "*3" "*agent*"
  118. "*allow-unresolved-vars*" "*assert*" "*clojure-version*" "*command-line-args*" "*compile-files*"
  119. "*compile-path*" "*e" "*err*" "*file*" "*flush-on-newline*"
  120. "*in*" "*macro-meta*" "*math-context*" "*ns*" "*out*"
  121. "*print-dup*" "*print-length*" "*print-level*" "*print-meta*" "*print-readably*"
  122. "*read-eval*" "*source-path*" "*use-context-classloader*" "*warn-on-reflection*" "+"
  123. "-" "/"
  124. "<" "<=" "=" "==" ">"
  125. ">=" "accessor" "aclone"
  126. "agent" "agent-errors" "aget" "alength" "alias"
  127. "all-ns" "alter" "alter-meta!" "alter-var-root" "amap"
  128. "ancestors" "and" "apply" "areduce" "array-map" "as->"
  129. "aset" "aset-boolean" "aset-byte" "aset-char" "aset-double"
  130. "aset-float" "aset-int" "aset-long" "aset-short" "assert"
  131. "assoc" "assoc!" "assoc-in" "associative?" "atom"
  132. "await" "await-for" "await1" "bases" "bean"
  133. "bigdec" "bigint" "binding" "bit-and" "bit-and-not"
  134. "bit-clear" "bit-flip" "bit-not" "bit-or" "bit-set"
  135. "bit-shift-left" "bit-shift-right" "bit-test" "bit-xor" "boolean"
  136. "boolean-array" "booleans" "bound-fn" "bound-fn*" "butlast"
  137. "byte" "byte-array" "bytes" "case" "cast" "char"
  138. "char-array" "char-escape-string" "char-name-string" "char?" "chars"
  139. "chunk" "chunk-append" "chunk-buffer" "chunk-cons" "chunk-first"
  140. "chunk-next" "chunk-rest" "chunked-seq?" "class" "class?"
  141. "clear-agent-errors" "clojure-version" "coll?" "comment" "commute"
  142. "comp" "comparator" "compare" "compare-and-set!" "compile"
  143. "complement" "concat" "cond" "condp" "cond->" "cond->>" "conj"
  144. "conj!" "cons" "constantly" "construct-proxy" "contains?"
  145. "count" "counted?" "create-ns" "create-struct" "cycle"
  146. "dec" "decimal?" "declare" "definline" "defmacro"
  147. "defmethod" "defmulti" "defn" "defn-" "defonce"
  148. "defstruct" "delay" "delay?" "deliver" "deref"
  149. "derive" "descendants" "destructure" "disj" "disj!"
  150. "dissoc" "dissoc!" "distinct" "distinct?" "doall"
  151. "doc" "dorun" "doseq" "dosync" "dotimes"
  152. "doto" "double" "double-array" "doubles" "drop"
  153. "drop-last" "drop-while" "empty" "empty?" "ensure"
  154. "enumeration-seq" "eval" "even?" "every?"
  155. "extend" "extend-protocol" "extend-type" "extends?" "extenders" "ex-info" "ex-data"
  156. "false?" "ffirst" "file-seq" "filter" "filterv" "find" "find-doc"
  157. "find-ns" "find-var" "first" "flatten" "float" "float-array"
  158. "float?" "floats" "flush" "fn" "fn?"
  159. "fnext" "for" "force" "format" "future"
  160. "future-call" "future-cancel" "future-cancelled?" "future-done?" "future?"
  161. "gen-class" "gen-interface" "gensym" "get" "get-in"
  162. "get-method" "get-proxy-class" "get-thread-bindings" "get-validator" "group-by"
  163. "hash" "hash-map" "hash-set" "identical?" "identity" "if-let"
  164. "if-not" "ifn?" "import" "in-ns" "inc"
  165. "init-proxy" "instance?" "int" "int-array" "integer?"
  166. "interleave" "intern" "interpose" "into" "into-array"
  167. "ints" "io!" "isa?" "iterate" "iterator-seq"
  168. "juxt" "key" "keys" "keyword" "keyword?"
  169. "last" "lazy-cat" "lazy-seq" "let" "letfn"
  170. "line-seq" "list" "list*" "list?" "load"
  171. "load-file" "load-reader" "load-string" "loaded-libs" "locking"
  172. "long" "long-array" "longs" "loop" "macroexpand"
  173. "macroexpand-1" "make-array" "make-hierarchy" "map" "mapv" "map?"
  174. "map-indexed" "mapcat" "max" "max-key" "memfn" "memoize"
  175. "merge" "merge-with" "meta" "method-sig" "methods"
  176. "min" "min-key" "mod" "name" "namespace"
  177. "neg?" "newline" "next" "nfirst" "nil?"
  178. "nnext" "not" "not-any?" "not-empty" "not-every?"
  179. "not=" "ns" "ns-aliases" "ns-imports" "ns-interns"
  180. "ns-map" "ns-name" "ns-publics" "ns-refers" "ns-resolve"
  181. "ns-unalias" "ns-unmap" "nth" "nthnext" "num"
  182. "number?" "odd?" "or" "parents" "partial"
  183. "partition" "partition-all" "partition-by" "pcalls" "peek" "persistent!" "pmap"
  184. "pop" "pop!" "pop-thread-bindings" "pos?" "pr"
  185. "pr-str" "prefer-method" "prefers" "primitives-classnames" "print"
  186. "print-ctor" "print-doc" "print-dup" "print-method" "print-namespace-doc"
  187. "print-simple" "print-special-doc" "print-str" "printf" "println"
  188. "println-str" "prn" "prn-str" "promise" "proxy"
  189. "proxy-call-with-super" "proxy-mappings" "proxy-name" "proxy-super" "push-thread-bindings"
  190. "pvalues" "quot" "rand" "rand-int" "range"
  191. "ratio?" "rational?" "rationalize" "re-find" "re-groups"
  192. "re-matcher" "re-matches" "re-pattern" "re-seq" "read"
  193. "read-line" "read-string" "reify" "reduce" "reduce-kv" "ref" "ref-history-count"
  194. "ref-max-history" "ref-min-history" "ref-set" "refer" "refer-clojure"
  195. "release-pending-sends" "rem" "remove" "remove-method" "remove-ns"
  196. "repeat" "repeatedly" "replace" "replicate"
  197. "require" "reset!" "reset-meta!" "resolve" "rest"
  198. "resultset-seq" "reverse" "reversible?" "rseq" "rsubseq"
  199. "satisfies?" "second" "select-keys" "send" "send-off" "send-via" "seq"
  200. "seq?" "seque" "sequence" "sequential?" "set"
  201. "set-agent-send-executor!" "set-agent-send-off-executor!"
  202. "set-validator!" "set?" "short" "short-array" "shorts"
  203. "shutdown-agents" "slurp" "some" "some->" "some->>" "sort" "sort-by"
  204. "sorted-map" "sorted-map-by" "sorted-set" "sorted-set-by" "sorted?"
  205. "special-form-anchor" "special-symbol?" "spit" "split-at" "split-with" "str"
  206. "stream?" "string?" "struct" "struct-map" "subs"
  207. "subseq" "subvec" "supers" "swap!" "symbol"
  208. "symbol?" "sync" "syntax-symbol-anchor" "take" "take-last"
  209. "take-nth" "take-while" "test" "the-ns" "time"
  210. "to-array" "to-array-2d" "trampoline" "transient" "tree-seq"
  211. "true?" "type" "unchecked-add" "unchecked-dec" "unchecked-divide"
  212. "unchecked-inc" "unchecked-multiply" "unchecked-negate" "unchecked-remainder" "unchecked-subtract"
  213. "underive" "unquote" "unquote-splicing" "update-in" "update-proxy"
  214. "use" "val" "vals" "var-get" "var-set"
  215. "var?" "vary-meta" "vec" "vector" "vector?"
  216. "when" "when-first" "when-let" "when-not" "while"
  217. "with-bindings" "with-bindings*" "with-in-str" "with-loading-context" "with-local-vars"
  218. "with-meta" "with-open" "with-out-str" "with-precision" "xml-seq" "zipmap"
  219. ) t)
  220. "\\>")
  221. 1 font-lock-builtin-face)
  222. ;;Other namespaces in clojure.jar
  223. (,(concat
  224. "(\\(?:\.*/\\)?"
  225. (regexp-opt
  226. '(;; clojure.inspector
  227. "atom?" "collection-tag" "get-child" "get-child-count" "inspect"
  228. "inspect-table" "inspect-tree" "is-leaf" "list-model" "list-provider"
  229. ;; clojure.main
  230. "load-script" "main" "repl" "repl-caught" "repl-exception"
  231. "repl-prompt" "repl-read" "skip-if-eol" "skip-whitespace" "with-bindings"
  232. ;; clojure.set
  233. "difference" "index" "intersection" "join" "map-invert"
  234. "project" "rename" "rename-keys" "select" "union"
  235. ;; clojure.stacktrace
  236. "e" "print-cause-trace" "print-stack-trace" "print-throwable" "print-trace-element"
  237. ;; clojure.template
  238. "do-template" "apply-template"
  239. ;; clojure.test
  240. "*initial-report-counters*" "*load-tests*" "*report-counters*" "*stack-trace-depth*" "*test-out*"
  241. "*testing-contexts*" "*testing-vars*" "are" "assert-any" "assert-expr"
  242. "assert-predicate" "compose-fixtures" "deftest" "deftest-" "file-position"
  243. "function?" "get-possibly-unbound-var" "inc-report-counter" "is" "join-fixtures"
  244. "report" "run-all-tests" "run-tests" "set-test" "successful?"
  245. "test-all-vars" "test-ns" "test-var" "testing" "testing-contexts-str"
  246. "testing-vars-str" "try-expr" "use-fixtures" "with-test" "with-test-out"
  247. ;; clojure.walk
  248. "keywordize-keys" "macroexpand-all" "postwalk" "postwalk-demo" "postwalk-replace"
  249. "prewalk" "prewalk-demo" "prewalk-replace" "stringify-keys" "walk"
  250. ;; clojure.xml
  251. "*current*" "*sb*" "*stack*" "*state*" "attrs"
  252. "content" "content-handler" "element" "emit" "emit-element"
  253. ;; clojure.zip
  254. "append-child" "branch?" "children" "down" "edit"
  255. "end?" "insert-child" "insert-left" "insert-right" "left"
  256. "leftmost" "lefts" "make-node" "next" "node"
  257. "path" "prev" "remove" "replace" "right"
  258. "rightmost" "rights" "root" "seq-zip" "up"
  259. ) t)
  260. "\\>")
  261. 1 font-lock-type-face)
  262. ;; Constant values (keywords), including as metadata e.g. ^:static
  263. ("\\<^?:\\(\\sw\\|\\s_\\)+\\(\\>\\|\\_>\\)" 0 font-lock-constant-face)
  264. ;; Meta type annotation #^Type or ^Type
  265. ("#?^\\(\\sw\\|\\s_\\)+" 0 font-lock-preprocessor-face)
  266. ("\\<io\\!\\>" 0 font-lock-warning-face)
  267. ;;Java interop highlighting
  268. ("\\<\\.-?[a-z][a-zA-Z0-9]*\\>" 0 font-lock-preprocessor-face) ;; .foo .barBaz .qux01 .-flibble .-flibbleWobble
  269. ("\\<[A-Z][a-zA-Z0-9_]*[a-zA-Z0-9/$_]+\\>" 0 font-lock-preprocessor-face) ;; Foo Bar$Baz Qux_ World_OpenUDP
  270. ("\\<[a-zA-Z]+\\.[a-zA-Z0-9._]*[A-Z]+[a-zA-Z0-9/.$]*\\>" 0 font-lock-preprocessor-face) ;; Foo/Bar foo.bar.Baz foo.Bar/baz
  271. ("[a-z]*[A-Z]+[a-z][a-zA-Z0-9$]*\\>" 0 font-lock-preprocessor-face) ;; fooBar
  272. ("\\<[A-Z][a-zA-Z0-9$]*\\.\\>" 0 font-lock-preprocessor-face) ;; Foo. BarBaz. Qux$Quux. Corge9.
  273. ;; Highlight grouping constructs in regular expressions
  274. (clojure-mode-font-lock-regexp-groups
  275. (1 'font-lock-regexp-grouping-construct prepend))))
  276. "Default expressions to highlight in Clojure mode.")
  277. (defgroup clojure-mode nil
  278. "A mode for Clojure"
  279. :prefix "clojure-mode-"
  280. :group 'applications)
  281. (defcustom clojure-mode-font-lock-comment-sexp nil
  282. "Set to non-nil in order to enable font-lock of (comment...)
  283. forms. This option is experimental. Changing this will require a
  284. restart (ie. M-x clojure-mode) of existing clojure mode buffers."
  285. :type 'boolean
  286. :group 'clojure-mode)
  287. (defcustom clojure-mode-load-command "(clojure.core/load-file \"%s\")\n"
  288. "*Format-string for building a Clojure expression to load a file.
  289. This format string should use `%s' to substitute a file name
  290. and should result in a Clojure expression that will command the inferior
  291. Clojure to load that file."
  292. :type 'string
  293. :group 'clojure-mode)
  294. (defcustom clojure-mode-inf-lisp-command "lein repl"
  295. "The command used by `inferior-lisp-program'."
  296. :type 'string
  297. :group 'clojure-mode)
  298. (defcustom clojure-mode-use-backtracking-indent t
  299. "Set to non-nil to enable backtracking/context sensitive indentation."
  300. :type 'boolean
  301. :group 'clojure-mode)
  302. (defcustom clojure-max-backtracking 3
  303. "Maximum amount to backtrack up a list to check for context."
  304. :type 'integer
  305. :group 'clojure-mode)
  306. (defvar clojure-mode-map
  307. (let ((map (make-sparse-keymap)))
  308. (set-keymap-parent map lisp-mode-shared-map)
  309. (define-key map (kbd "C-M-x") 'lisp-eval-defun)
  310. (define-key map (kbd "C-x C-e") 'lisp-eval-last-sexp)
  311. (define-key map (kbd "C-c C-e") 'lisp-eval-last-sexp)
  312. (define-key map (kbd "C-c C-l") 'clojure-load-file)
  313. (define-key map (kbd "C-c C-r") 'lisp-eval-region)
  314. (define-key map (kbd "C-c C-t") 'clojure-jump-between-tests-and-code)
  315. (define-key map (kbd "C-c C-z") 'clojure-display-inferior-lisp-buffer)
  316. (define-key map (kbd "C-c M-q") 'clojure-fill-docstring)
  317. map)
  318. "Keymap for Clojure mode. Inherits from `lisp-mode-shared-map'.")
  319. (easy-menu-define clojure-mode-menu clojure-mode-map
  320. "Menu for Clojure mode."
  321. '("Clojure"
  322. ["Eval Function Definition" lisp-eval-defun]
  323. ["Eval Last Sexp" lisp-eval-last-sexp]
  324. ["Eval Region" lisp-eval-region]
  325. "--"
  326. ["Run Inferior Lisp" clojure-display-inferior-lisp-buffer]
  327. ["Display Inferior Lisp Buffer" clojure-display-inferior-lisp-buffer]
  328. ["Load File" clojure-load-file]
  329. "--"
  330. ["Fill Docstring" clojure-fill-docstring]
  331. ["Jump Between Test and Code" clojure-jump-between-tests-and-code]))
  332. (defvar clojure-mode-syntax-table
  333. (let ((table (copy-syntax-table emacs-lisp-mode-syntax-table)))
  334. (modify-syntax-entry ?~ "' " table)
  335. ;; can't safely make commas whitespace since it will apply even
  336. ;; inside string literals--ick!
  337. ;; (modify-syntax-entry ?, " " table)
  338. (modify-syntax-entry ?\{ "(}" table)
  339. (modify-syntax-entry ?\} "){" table)
  340. (modify-syntax-entry ?\[ "(]" table)
  341. (modify-syntax-entry ?\] ")[" table)
  342. (modify-syntax-entry ?^ "'" table)
  343. ;; Make hash a usual word character
  344. (modify-syntax-entry ?# "_ p" table)
  345. table))
  346. (defvar clojure-mode-abbrev-table nil
  347. "Abbrev table used in clojure-mode buffers.")
  348. (define-abbrev-table 'clojure-mode-abbrev-table ())
  349. (defvar clojure-prev-l/c-dir/file nil
  350. "Record last directory and file used in loading or compiling.
  351. This holds a cons cell of the form `(DIRECTORY . FILE)'
  352. describing the last `clojure-load-file' or `clojure-compile-file' command.")
  353. (defvar clojure-test-ns-segment-position -1
  354. "Which segment of the ns is \"test\" inserted in your test name convention.
  355. Customize this depending on your project's conventions. Negative
  356. numbers count from the end:
  357. leiningen.compile -> leiningen.test.compile (uses 1)
  358. clojure.http.client -> clojure.http.test.client (uses -1)")
  359. (defvar clojure-mode-version "2.1.0"
  360. "The current version of `clojure-mode'.")
  361. (defun clojure-mode-display-version ()
  362. "Display the current `clojure-mode-version' in the minibuffer."
  363. (interactive)
  364. (message "clojure-mode (version %s)" clojure-mode-version))
  365. ;; For compatibility with Emacs < 24, derive conditionally
  366. (defalias 'clojure-parent-mode
  367. (if (fboundp 'prog-mode) 'prog-mode 'fundamental-mode))
  368. (defun clojure-space-for-delimiter-p (endp delim)
  369. (if (eq major-mode 'clojure-mode)
  370. (save-excursion
  371. (backward-char)
  372. (if (and (or (char-equal delim ?\()
  373. (char-equal delim ?\")
  374. (char-equal delim ?{))
  375. (not endp))
  376. (if (char-equal (char-after) ?#)
  377. (and (not (bobp))
  378. (or (char-equal ?w (char-syntax (char-before)))
  379. (char-equal ?_ (char-syntax (char-before)))))
  380. t)
  381. t))
  382. t))
  383. ;;;###autoload
  384. (define-derived-mode clojure-mode clojure-parent-mode "Clojure"
  385. "Major mode for editing Clojure code - similar to Lisp mode.
  386. Commands:
  387. Delete converts tabs to spaces as it moves back.
  388. Blank lines separate paragraphs. Semicolons start comments.
  389. \\{clojure-mode-map}
  390. Note that `run-lisp' may be used either to start an inferior Lisp job
  391. or to switch back to an existing one.
  392. Entry to this mode calls the value of `clojure-mode-hook'
  393. if that value is non-nil."
  394. (set (make-local-variable 'imenu-create-index-function)
  395. (lambda ()
  396. (imenu--generic-function '((nil clojure-match-next-def 0)))))
  397. (set (make-local-variable 'indent-tabs-mode) nil)
  398. (lisp-mode-variables nil)
  399. (set (make-local-variable 'comment-start-skip)
  400. "\\(\\(^\\|[^\\\\\n]\\)\\(\\\\\\\\\\)*\\)\\(;+\\|#|\\) *")
  401. (set (make-local-variable 'lisp-indent-function)
  402. 'clojure-indent-function)
  403. (when (< emacs-major-version 24)
  404. (set (make-local-variable 'forward-sexp-function)
  405. 'clojure-forward-sexp))
  406. (set (make-local-variable 'lisp-doc-string-elt-property)
  407. 'clojure-doc-string-elt)
  408. (set (make-local-variable 'inferior-lisp-program) clojure-mode-inf-lisp-command)
  409. (set (make-local-variable 'parse-sexp-ignore-comments) t)
  410. (clojure-mode-font-lock-setup)
  411. (add-hook 'paredit-mode-hook
  412. (lambda ()
  413. (when (>= paredit-version 21)
  414. (define-key clojure-mode-map "{" 'paredit-open-curly)
  415. (define-key clojure-mode-map "}" 'paredit-close-curly)
  416. (add-to-list 'paredit-space-for-delimiter-predicates
  417. 'clojure-space-for-delimiter-p)))))
  418. (defun clojure-display-inferior-lisp-buffer ()
  419. "Display a buffer bound to `inferior-lisp-buffer'."
  420. (interactive)
  421. (if (and inferior-lisp-buffer (get-buffer inferior-lisp-buffer))
  422. (pop-to-buffer inferior-lisp-buffer t)
  423. (run-lisp inferior-lisp-program)))
  424. (defun clojure-load-file (file-name)
  425. "Load a Lisp file into the inferior Lisp process."
  426. (interactive (comint-get-source "Load Clojure file: "
  427. clojure-prev-l/c-dir/file
  428. '(clojure-mode) t))
  429. (comint-check-source file-name) ; Check to see if buffer needs saved.
  430. (setq clojure-prev-l/c-dir/file (cons (file-name-directory file-name)
  431. (file-name-nondirectory file-name)))
  432. (comint-send-string (inferior-lisp-proc)
  433. (format clojure-mode-load-command file-name))
  434. (switch-to-lisp t))
  435. (defun clojure-match-next-def ()
  436. "Scans the buffer backwards for the next top-level definition.
  437. Called by `imenu--generic-function'."
  438. (when (re-search-backward "^\\s *(def\\S *[ \n\t]+" nil t)
  439. (save-excursion
  440. (goto-char (match-end 0))
  441. (when (looking-at "#?\\^")
  442. (let (forward-sexp-function) ; using the built-in one
  443. (forward-sexp))) ; skip the metadata
  444. (re-search-forward "[^ \n\t)]+"))))
  445. (defun clojure-mode-font-lock-setup ()
  446. "Configures font-lock for editing Clojure code."
  447. (interactive)
  448. (set (make-local-variable 'font-lock-multiline) t)
  449. (add-to-list 'font-lock-extend-region-functions
  450. 'clojure-font-lock-extend-region-def t)
  451. (when clojure-mode-font-lock-comment-sexp
  452. (add-to-list 'font-lock-extend-region-functions
  453. 'clojure-font-lock-extend-region-comment t)
  454. (make-local-variable 'clojure-font-lock-keywords)
  455. (add-to-list 'clojure-font-lock-keywords
  456. 'clojure-font-lock-mark-comment t)
  457. (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil))
  458. (setq font-lock-defaults
  459. '(clojure-font-lock-keywords ; keywords
  460. nil nil
  461. (("+-*/.<>=!?$%_&~^:@" . "w")) ; syntax alist
  462. nil
  463. (font-lock-mark-block-function . mark-defun)
  464. (font-lock-syntactic-face-function
  465. . lisp-font-lock-syntactic-face-function))))
  466. (defun clojure-font-lock-def-at-point (point)
  467. "Find the position range between the top-most def* and the
  468. fourth element afterwards. Note that this means there's no
  469. gaurantee of proper font locking in def* forms that are not at
  470. top-level."
  471. (goto-char point)
  472. (condition-case nil
  473. (beginning-of-defun)
  474. (error nil))
  475. (let ((beg-def (point)))
  476. (when (and (not (= point beg-def))
  477. (looking-at "(def"))
  478. (condition-case nil
  479. (progn
  480. ;; move forward as much as possible until failure (or success)
  481. (forward-char)
  482. (dotimes (i 4)
  483. (forward-sexp)))
  484. (error nil))
  485. (cons beg-def (point)))))
  486. (defun clojure-font-lock-extend-region-def ()
  487. "Move fontification boundaries to always include the first four
  488. elements of a def* forms."
  489. (let ((changed nil))
  490. (let ((def (clojure-font-lock-def-at-point font-lock-beg)))
  491. (when def
  492. (destructuring-bind (def-beg . def-end) def
  493. (when (and (< def-beg font-lock-beg)
  494. (< font-lock-beg def-end))
  495. (setq font-lock-beg def-beg
  496. changed t)))))
  497. (let ((def (clojure-font-lock-def-at-point font-lock-end)))
  498. (when def
  499. (destructuring-bind (def-beg . def-end) def
  500. (when (and (< def-beg font-lock-end)
  501. (< font-lock-end def-end))
  502. (setq font-lock-end def-end
  503. changed t)))))
  504. changed))
  505. (defun clojure-mode-font-lock-regexp-groups (bound)
  506. "A function run by font-lock to highlight grouping constructs
  507. in regular expression."
  508. (catch 'found
  509. (while (re-search-forward (concat
  510. ;; A group may start using several alternatives:
  511. "\\(\\(?:"
  512. ;; 1. (? special groups
  513. "(\\?\\(?:"
  514. ;; a) non-capturing group (?:X)
  515. ;; b) independent non-capturing group (?>X)
  516. ;; c) zero-width positive lookahead (?=X)
  517. ;; d) zero-width negative lookahead (?!X)
  518. "[:=!>]\\|"
  519. ;; e) zero-width positive lookbehind (?<=X)
  520. ;; f) zero-width negative lookbehind (?<!X)
  521. "<[=!]\\|"
  522. ;; g) named capturing group (?<name>X)
  523. "<[[:alnum:]]+>"
  524. "\\)\\|" ;; end of special groups
  525. ;; 2. normal capturing groups (
  526. ;; 3. we also highlight alternative
  527. ;; separarators |, and closing parens )
  528. "[|()]"
  529. "\\)\\)") bound t)
  530. (let ((face (get-text-property (1- (point)) 'face)))
  531. (when (and (or (and (listp face)
  532. (memq 'font-lock-string-face face))
  533. (eq 'font-lock-string-face face))
  534. (clojure-string-start t))
  535. (throw 'found t))))))
  536. (defun clojure-find-block-comment-start (limit)
  537. "Search for (comment...) or #_ style block comments and put
  538. point at the beginning of the expression."
  539. (let ((pos (re-search-forward "\\((comment\\>\\|#_\\)" limit t)))
  540. (when pos
  541. (forward-char (- (length (match-string 1))))
  542. pos)))
  543. (defun clojure-font-lock-extend-region-comment ()
  544. "Move fontification boundaries to always contain
  545. entire (comment ..) and #_ sexp. Does not work if you have a
  546. white-space between ( and comment, but that is omitted to make
  547. this run faster."
  548. (let ((changed nil))
  549. (goto-char font-lock-beg)
  550. (condition-case nil (beginning-of-defun) (error nil))
  551. (let ((pos (clojure-find-block-comment-start font-lock-end)))
  552. (when pos
  553. (when (< (point) font-lock-beg)
  554. (setq font-lock-beg (point)
  555. changed t))
  556. (condition-case nil (forward-sexp) (error nil))
  557. (when (> (point) font-lock-end)
  558. (setq font-lock-end (point)
  559. changed t))))
  560. changed))
  561. (defun clojure-font-lock-mark-comment (limit)
  562. "Marks all (comment ..) and #_ forms with font-lock-comment-face."
  563. (let (pos)
  564. (while (and (< (point) limit)
  565. (setq pos (clojure-find-block-comment-start limit)))
  566. (when pos
  567. (condition-case nil
  568. (add-text-properties (point)
  569. (progn
  570. (forward-sexp)
  571. (point))
  572. '(face font-lock-comment-face multiline t))
  573. (error (forward-char 8))))))
  574. nil)
  575. ;; Docstring positions
  576. (put 'ns 'clojure-doc-string-elt 2)
  577. (put 'defn 'clojure-doc-string-elt 2)
  578. (put 'defn- 'clojure-doc-string-elt 2)
  579. (put 'defmulti 'clojure-doc-string-elt 2)
  580. (put 'defmacro 'clojure-doc-string-elt 2)
  581. (put 'definline 'clojure-doc-string-elt 2)
  582. (put 'defprotocol 'clojure-doc-string-elt 2)
  583. (defun clojure-forward-sexp (n)
  584. "Treat record literals like #user.Foo[1] and #user.Foo{:size 1}
  585. as a single sexp so that slime will send them properly. Arguably
  586. this behavior is unintuitive for the user pressing (eg) C-M-f
  587. himself, but since these are single objects I think it's right."
  588. (let ((dir (if (> n 0) 1 -1))
  589. (forward-sexp-function nil)) ; force the built-in version
  590. (while (not (zerop n))
  591. (forward-sexp dir)
  592. (when (save-excursion ; move back to see if we're in a record literal
  593. (and
  594. (condition-case nil
  595. (progn (backward-sexp) 't)
  596. ('scan-error nil))
  597. (looking-at "#\\w")))
  598. (forward-sexp dir)) ; if so, jump over it
  599. (setq n (- n dir)))))
  600. (defun clojure-indent-function (indent-point state)
  601. "This function is the normal value of the variable `lisp-indent-function'.
  602. It is used when indenting a line within a function call, to see if the
  603. called function says anything special about how to indent the line.
  604. INDENT-POINT is the position where the user typed TAB, or equivalent.
  605. Point is located at the point to indent under (for default indentation);
  606. STATE is the `parse-partial-sexp' state for that position.
  607. If the current line is in a call to a Lisp function
  608. which has a non-nil property `lisp-indent-function',
  609. that specifies how to do the indentation. The property value can be
  610. * `defun', meaning indent `defun'-style;
  611. * an integer N, meaning indent the first N arguments specially
  612. like ordinary function arguments and then indent any further
  613. arguments like a body;
  614. * a function to call just as this function was called.
  615. If that function returns nil, that means it doesn't specify
  616. the indentation.
  617. This function also returns nil meaning don't specify the indentation."
  618. (let ((normal-indent (current-column)))
  619. (goto-char (1+ (elt state 1)))
  620. (parse-partial-sexp (point) calculate-lisp-indent-last-sexp 0 t)
  621. (if (and (elt state 2)
  622. (not (looking-at "\\sw\\|\\s_")))
  623. ;; car of form doesn't seem to be a symbol
  624. (progn
  625. (if (not (> (save-excursion (forward-line 1) (point))
  626. calculate-lisp-indent-last-sexp))
  627. (progn (goto-char calculate-lisp-indent-last-sexp)
  628. (beginning-of-line)
  629. (parse-partial-sexp (point)
  630. calculate-lisp-indent-last-sexp 0 t)))
  631. ;; Indent under the list or under the first sexp on the same
  632. ;; line as calculate-lisp-indent-last-sexp. Note that first
  633. ;; thing on that line has to be complete sexp since we are
  634. ;; inside the innermost containing sexp.
  635. (backward-prefix-chars)
  636. (if (and (eq (char-after (point)) ?\[)
  637. (eq (char-after (elt state 1)) ?\())
  638. (+ (current-column) 2) ;; this is probably inside a defn
  639. (current-column)))
  640. (let* ((function (buffer-substring (point)
  641. (progn (forward-sexp 1) (point))))
  642. (open-paren (elt state 1))
  643. (method nil)
  644. (function-tail (first
  645. (last
  646. (split-string (substring-no-properties function) "/")))))
  647. (setq method (get (intern-soft function-tail) 'clojure-indent-function))
  648. (cond ((member (char-after open-paren) '(?\[ ?\{))
  649. (goto-char open-paren)
  650. (1+ (current-column)))
  651. ((or (eq method 'defun)
  652. (and (null method)
  653. (> (length function) 3)
  654. (string-match "\\`\\(?:\\S +/\\)?\\(def\\|with-\\)"
  655. function)))
  656. (lisp-indent-defform state indent-point))
  657. ((integerp method)
  658. (lisp-indent-specform method state
  659. indent-point normal-indent))
  660. (method
  661. (funcall method indent-point state))
  662. (clojure-mode-use-backtracking-indent
  663. (clojure-backtracking-indent
  664. indent-point state normal-indent)))))))
  665. (defun clojure-backtracking-indent (indent-point state normal-indent)
  666. "Experimental backtracking support. Will upwards in an sexp to
  667. check for contextual indenting."
  668. (let (indent (path) (depth 0))
  669. (goto-char (elt state 1))
  670. (while (and (not indent)
  671. (< depth clojure-max-backtracking))
  672. (let ((containing-sexp (point)))
  673. (parse-partial-sexp (1+ containing-sexp) indent-point 1 t)
  674. (when (looking-at "\\sw\\|\\s_")
  675. (let* ((start (point))
  676. (fn (buffer-substring start (progn (forward-sexp 1) (point))))
  677. (meth (get (intern-soft fn) 'clojure-backtracking-indent)))
  678. (let ((n 0))
  679. (when (< (point) indent-point)
  680. (condition-case ()
  681. (progn
  682. (forward-sexp 1)
  683. (while (< (point) indent-point)
  684. (parse-partial-sexp (point) indent-point 1 t)
  685. (incf n)
  686. (forward-sexp 1)))
  687. (error nil)))
  688. (push n path))
  689. (when meth
  690. (let ((def meth))
  691. (dolist (p path)
  692. (if (and (listp def)
  693. (< p (length def)))
  694. (setq def (nth p def))
  695. (if (listp def)
  696. (setq def (car (last def)))
  697. (setq def nil))))
  698. (goto-char (elt state 1))
  699. (when def
  700. (setq indent (+ (current-column) def)))))))
  701. (goto-char containing-sexp)
  702. (condition-case ()
  703. (progn
  704. (backward-up-list 1)
  705. (incf depth))
  706. (error (setq depth clojure-max-backtracking)))))
  707. indent))
  708. ;; clojure backtracking indent is experimental and the format for these
  709. ;; entries are subject to change
  710. (put 'implement 'clojure-backtracking-indent '(4 (2)))
  711. (put 'letfn 'clojure-backtracking-indent '((2) 2))
  712. (put 'proxy 'clojure-backtracking-indent '(4 4 (2)))
  713. (put 'reify 'clojure-backtracking-indent '((2)))
  714. (put 'deftype 'clojure-backtracking-indent '(4 4 (2)))
  715. (put 'defrecord 'clojure-backtracking-indent '(4 4 (2)))
  716. (put 'defprotocol 'clojure-backtracking-indent '(4 (2)))
  717. (put 'extend-type 'clojure-backtracking-indent '(4 (2)))
  718. (put 'extend-protocol 'clojure-backtracking-indent '(4 (2)))
  719. (defun put-clojure-indent (sym indent)
  720. (put sym 'clojure-indent-function indent))
  721. (defmacro define-clojure-indent (&rest kvs)
  722. `(progn
  723. ,@(mapcar (lambda (x) `(put-clojure-indent
  724. (quote ,(first x)) ,(second x))) kvs)))
  725. (defun add-custom-clojure-indents (name value)
  726. (custom-set-default name value)
  727. (mapcar (lambda (x)
  728. (put-clojure-indent x 'defun))
  729. value))
  730. (defcustom clojure-defun-indents nil
  731. "List of symbols to give defun-style indentation to in Clojure
  732. code, in addition to those that are built-in. You can use this to
  733. get emacs to indent your own macros the same as it does the
  734. built-ins like with-open. To set manually from lisp code,
  735. use (put-clojure-indent 'some-symbol 'defun)."
  736. :type '(repeat symbol)
  737. :group 'clojure-mode
  738. :set 'add-custom-clojure-indents)
  739. (define-clojure-indent
  740. ;; built-ins
  741. (ns 1)
  742. (fn 'defun)
  743. (def 'defun)
  744. (defn 'defun)
  745. (bound-fn 'defun)
  746. (if 1)
  747. (if-not 1)
  748. (case 1)
  749. (condp 2)
  750. (when 1)
  751. (while 1)
  752. (when-not 1)
  753. (when-first 1)
  754. (do 0)
  755. (future 0)
  756. (comment 0)
  757. (doto 1)
  758. (locking 1)
  759. (proxy 2)
  760. (with-open 1)
  761. (with-precision 1)
  762. (with-local-vars 1)
  763. (reify 'defun)
  764. (deftype 2)
  765. (defrecord 2)
  766. (defprotocol 1)
  767. (extend 1)
  768. (extend-protocol 1)
  769. (extend-type 1)
  770. (try 0)
  771. (catch 2)
  772. (finally 0)
  773. ;; binding forms
  774. (let 1)
  775. (letfn 1)
  776. (binding 1)
  777. (loop 1)
  778. (for 1)
  779. (doseq 1)
  780. (dotimes 1)
  781. (when-let 1)
  782. (if-let 1)
  783. ;; data structures
  784. (defstruct 1)
  785. (struct-map 1)
  786. (assoc 1)
  787. (defmethod 'defun)
  788. ;; clojure.test
  789. (testing 1)
  790. (deftest 'defun)
  791. (are 1)
  792. (use-fixtures 'defun))
  793. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  794. ;;
  795. ;; Better docstring filling for clojure-mode
  796. ;;
  797. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  798. (defun clojure-string-start (&optional regex)
  799. "Return the position of the \" that begins the string at point.
  800. If REGEX is non-nil, return the position of the # that begins
  801. the regex at point. If point is not inside a string or regex,
  802. return nil."
  803. (when (nth 3 (syntax-ppss)) ;; Are we really in a string?
  804. (save-excursion
  805. (save-match-data
  806. ;; Find a quote that appears immediately after whitespace,
  807. ;; beginning of line, hash, or an open paren, brace, or bracket
  808. (re-search-backward "\\(\\s-\\|^\\|#\\|(\\|\\[\\|{\\)\\(\"\\)")
  809. (let ((beg (match-beginning 2)))
  810. (when beg
  811. (if regex
  812. (and (char-equal ?# (char-before beg)) (1- beg))
  813. (when (not (char-equal ?# (char-before beg)))
  814. beg))))))))
  815. (defun clojure-char-at-point ()
  816. "Return the char at point or nil if at buffer end."
  817. (when (not (= (point) (point-max)))
  818. (buffer-substring-no-properties (point) (1+ (point)))))
  819. (defun clojure-char-before-point ()
  820. "Return the char before point or nil if at buffer beginning."
  821. (when (not (= (point) (point-min)))
  822. (buffer-substring-no-properties (point) (1- (point)))))
  823. ;; TODO: Deal with the fact that when point is exactly at the
  824. ;; beginning of a string, it thinks that is the end.
  825. (defun clojure-string-end ()
  826. "Return the position of the \" that ends the string at point.
  827. Note that point must be inside the string - if point is
  828. positioned at the opening quote, incorrect results will be
  829. returned."
  830. (save-excursion
  831. (save-match-data
  832. ;; If we're at the end of the string, just return point.
  833. (if (and (string= (clojure-char-at-point) "\"")
  834. (not (string= (clojure-char-before-point) "\\")))
  835. (point)
  836. ;; We don't want to get screwed by starting out at the
  837. ;; backslash in an escaped quote.
  838. (when (string= (clojure-char-at-point) "\\")
  839. (backward-char))
  840. ;; Look for a quote not preceeded by a backslash
  841. (re-search-forward "[^\\]\\\(\\\"\\)")
  842. (match-beginning 1)))))
  843. (defun clojure-docstring-start+end-points ()
  844. "Return the start and end points of the string at point as a cons."
  845. (if (and (fboundp 'paredit-string-start+end-points) paredit-mode)
  846. (paredit-string-start+end-points)
  847. (cons (clojure-string-start) (clojure-string-end))))
  848. (defun clojure-mark-string ()
  849. "Mark the string at point."
  850. (interactive)
  851. (goto-char (clojure-string-start))
  852. (forward-char)
  853. (set-mark (clojure-string-end)))
  854. (defun clojure-fill-docstring (&optional argument)
  855. "Fill the definition that the point is on appropriate for Clojure.
  856. Fills so that every paragraph has a minimum of two initial spaces,
  857. with the exception of the first line. Fill margins are taken from
  858. paragraph start, so a paragraph that begins with four spaces will
  859. remain indented by four spaces after refilling."
  860. (interactive "P")
  861. (if (and (fboundp 'paredit-in-string-p) paredit-mode)
  862. (unless (paredit-in-string-p)
  863. (error "Must be inside a string")))
  864. ;; Oddly, save-excursion doesn't do a good job of preserving point.
  865. ;; It's probably because we delete the string and then re-insert it.
  866. (let ((old-point (point)))
  867. (save-restriction
  868. (save-excursion
  869. (let* ((string-region (clojure-docstring-start+end-points))
  870. (string-start (1+ (car string-region)))
  871. (string-end (cdr string-region))
  872. (string (buffer-substring-no-properties (1+ (car string-region))
  873. (cdr string-region))))
  874. (delete-region string-start string-end)
  875. (insert
  876. (with-temp-buffer
  877. (insert string)
  878. (let ((left-margin 2))
  879. (delete-trailing-whitespace)
  880. (fill-region (point-min) (point-max))
  881. (buffer-substring-no-properties (+ 2 (point-min)) (point-max))))))))
  882. (goto-char old-point)))
  883. (defconst clojure-namespace-name-regex
  884. (rx line-start
  885. "("
  886. (zero-or-one (group (regexp "clojure.core/")))
  887. (zero-or-one (submatch "in-"))
  888. "ns"
  889. (zero-or-one "+")
  890. (one-or-more (any whitespace "\n"))
  891. (zero-or-more (or (submatch (zero-or-one "#")
  892. "^{"
  893. (zero-or-more (not (any "}")))
  894. "}")
  895. (zero-or-more "^:"
  896. (one-or-more (not (any whitespace)))))
  897. (one-or-more (any whitespace "\n")))
  898. ;; why is this here? oh (in-ns 'foo) or (ns+ :user)
  899. (zero-or-one (any ":'"))
  900. (group (one-or-more (not (any "()\"" whitespace))) word-end)))
  901. ;; for testing clojure-namespace-name-regex, you can evaluate this code and make
  902. ;; sure foo (or whatever the namespace name is) shows up in results. some of
  903. ;; these currently fail.
  904. ;; (mapcar (lambda (s) (let ((n (string-match clojure-namespace-name-regex s)))
  905. ;; (if n (match-string 4 s))))
  906. ;; '("(ns foo)"
  907. ;; "(ns
  908. ;; foo)"
  909. ;; "(ns foo.baz)"
  910. ;; "(ns ^:bar foo)"
  911. ;; "(ns ^:bar ^:baz foo)"
  912. ;; "(ns ^{:bar true} foo)"
  913. ;; "(ns #^{:bar true} foo)"
  914. ;; "(ns #^{:fail {}} foo)"
  915. ;; "(ns ^{:fail2 {}} foo.baz)"
  916. ;; "(ns ^{} foo)"
  917. ;; "(ns ^{:skip-wiki true}
  918. ;; aleph.netty
  919. ;; "
  920. ;; "(ns
  921. ;; foo)"
  922. ;; "foo"))
  923. (defun clojure-expected-ns ()
  924. "Returns the namespace name that the file should have."
  925. (let* ((project-dir (file-truename
  926. (locate-dominating-file default-directory
  927. "project.clj")))
  928. (relative (substring (file-truename (buffer-file-name)) (length project-dir) -4)))
  929. (replace-regexp-in-string
  930. "_" "-" (mapconcat 'identity (cdr (split-string relative "/")) "."))))
  931. (defun clojure-insert-ns-form ()
  932. (interactive)
  933. (goto-char (point-min))
  934. (insert (format "(ns %s)" (clojure-expected-ns))))
  935. (defun clojure-update-ns ()
  936. "Updates the namespace of the current buffer. Useful if a file has been renamed."
  937. (interactive)
  938. (let ((nsname (clojure-expected-ns)))
  939. (when nsname
  940. (save-restriction
  941. (save-excursion
  942. (save-match-data
  943. (if (clojure-find-ns)
  944. (replace-match nsname nil nil nil 4)
  945. (error "Namespace not found"))))))))
  946. (defun clojure-find-ns ()
  947. (let ((regexp clojure-namespace-name-regex))
  948. (save-restriction
  949. (save-excursion
  950. (goto-char (point-min))
  951. (when (re-search-forward regexp nil t)
  952. (match-string-no-properties 4))))))
  953. (defalias 'clojure-find-package 'clojure-find-ns)
  954. ;; Test navigation:
  955. (defun clojure-in-tests-p ()
  956. (or (string-match-p "test\." (clojure-find-ns))
  957. (string-match-p "/test" (buffer-file-name))))
  958. (defun clojure-underscores-for-hyphens (namespace)
  959. (replace-regexp-in-string "-" "_" namespace))
  960. (defun clojure-test-for (namespace)
  961. "Returns the path of the test file for the given namespace."
  962. (let* ((namespace (clojure-underscores-for-hyphens namespace))
  963. (segments (split-string namespace "\\.")))
  964. (format "%stest/%s_test.clj"
  965. (file-name-as-directory
  966. (locate-dominating-file buffer-file-name "src/"))
  967. (mapconcat 'identity segments "/"))))
  968. (defvar clojure-test-for-fn 'clojure-test-for
  969. "Var pointing to the function that will return the full path of the
  970. Clojure test file for the given namespace.")
  971. (defun clojure-jump-to-test ()
  972. "Jump from implementation file to test."
  973. (interactive)
  974. (find-file (funcall clojure-test-for-fn (clojure-find-ns))))
  975. (defun clojure-jump-between-tests-and-code ()
  976. (interactive)
  977. (if (clojure-in-tests-p)
  978. (clojure-test-jump-to-implementation)
  979. (clojure-jump-to-test)))
  980. ;;;###autoload
  981. (progn
  982. (put 'clojure-test-ns-segment-position 'safe-local-variable 'integerp)
  983. (put 'clojure-mode-load-command 'safe-local-variable 'stringp)
  984. (add-to-list 'auto-mode-alist '("\\.clj\\'" . clojure-mode))
  985. (add-to-list 'auto-mode-alist '("\\.cljs\\'" . clojure-mode))
  986. (add-to-list 'auto-mode-alist '("\\.dtm\\'" . clojure-mode))
  987. (add-to-list 'auto-mode-alist '("\\.edn\\'" . clojure-mode))
  988. (add-to-list 'interpreter-mode-alist '("jark" . clojure-mode))
  989. (add-to-list 'interpreter-mode-alist '("cake" . clojure-mode)))
  990. (provide 'clojure-mode)
  991. ;; Local Variables:
  992. ;; byte-compile-warnings: (not cl-functions)
  993. ;; End:
  994. ;;; clojure-mode.el ends here