PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/elpa/clojure-mode-20131227.1044/clojure-mode.el

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