Klimi's new dotfiles with stow.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1155 行
51 KiB

  1. ;;; cider-eval.el --- Interactive evaluation (compilation) functionality -*- lexical-binding: t -*-
  2. ;; Copyright © 2012-2013 Tim King, Phil Hagelberg, Bozhidar Batsov
  3. ;; Copyright © 2013-2019 Bozhidar Batsov, Artur Malabarba and CIDER contributors
  4. ;;
  5. ;; Author: Tim King <kingtim@gmail.com>
  6. ;; Phil Hagelberg <technomancy@gmail.com>
  7. ;; Bozhidar Batsov <bozhidar@batsov.com>
  8. ;; Artur Malabarba <bruce.connor.am@gmail.com>
  9. ;; Hugo Duncan <hugo@hugoduncan.org>
  10. ;; Steve Purcell <steve@sanityinc.com>
  11. ;; This program is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation, either version 3 of the License, or
  14. ;; (at your option) any later version.
  15. ;; This program is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  21. ;; This file is not part of GNU Emacs.
  22. ;;; Commentary:
  23. ;; This file contains CIDER's interactive evaluation (compilation) functionality.
  24. ;; Although Clojure doesn't really have the concept of evaluation (only
  25. ;; compilation), we're using everywhere in the code the term evaluation for
  26. ;; brevity (and to be in line with the naming employed by other similar modes).
  27. ;;
  28. ;; This files also contains all the logic related to displaying errors and
  29. ;; evaluation warnings.
  30. ;;
  31. ;; Pretty much all of the commands here are meant to be used mostly from
  32. ;; `cider-mode', but some of them might make sense in other contexts as well.
  33. ;;; Code:
  34. (require 'ansi-color)
  35. (require 'cl-lib)
  36. (require 'compile)
  37. (require 'map)
  38. (require 'seq)
  39. (require 'subr-x)
  40. (require 'clojure-mode)
  41. (require 'cider-client)
  42. (require 'cider-common)
  43. (require 'cider-compat)
  44. (require 'cider-overlays)
  45. (require 'cider-popup)
  46. (require 'cider-repl)
  47. (require 'cider-stacktrace)
  48. (require 'cider-util)
  49. (defconst cider-read-eval-buffer "*cider-read-eval*")
  50. (defconst cider-result-buffer "*cider-result*")
  51. (defcustom cider-show-error-buffer t
  52. "Control the popup behavior of cider stacktraces.
  53. The following values are possible t or 'always, 'except-in-repl,
  54. 'only-in-repl. Any other value, including nil, will cause the stacktrace
  55. not to be automatically shown.
  56. Irespective of the value of this variable, the `cider-error-buffer' is
  57. always generated in the background. Use `cider-selector' to
  58. navigate to this buffer."
  59. :type '(choice (const :tag "always" t)
  60. (const except-in-repl)
  61. (const only-in-repl)
  62. (const :tag "never" nil))
  63. :group 'cider)
  64. (defcustom cider-auto-jump-to-error t
  65. "Control the cursor jump behaviour in compilation error buffer.
  66. When non-nil automatically jump to error location during interactive
  67. compilation. When set to 'errors-only, don't jump to warnings.
  68. When set to nil, don't jump at all."
  69. :type '(choice (const :tag "always" t)
  70. (const errors-only)
  71. (const :tag "never" nil))
  72. :group 'cider
  73. :package-version '(cider . "0.7.0"))
  74. (defcustom cider-auto-select-error-buffer t
  75. "Controls whether to auto-select the error popup buffer."
  76. :type 'boolean
  77. :group 'cider)
  78. (defcustom cider-auto-track-ns-form-changes t
  79. "Controls whether to auto-evaluate a source buffer's ns form when changed.
  80. When non-nil CIDER will check for ns form changes before each eval command.
  81. When nil the users are expected to take care of the re-evaluating updated
  82. ns forms manually themselves."
  83. :type 'boolean
  84. :group 'cider
  85. :package-version '(cider . "0.15.0"))
  86. (defcustom cider-save-file-on-load 'prompt
  87. "Controls whether to prompt to save the file when loading a buffer.
  88. If nil, files are not saved.
  89. If 'prompt, the user is prompted to save the file if it's been modified.
  90. If t, save the file without confirmation."
  91. :type '(choice (const prompt :tag "Prompt to save the file if it's been modified")
  92. (const nil :tag "Don't save the file")
  93. (const t :tag "Save the file without confirmation"))
  94. :group 'cider
  95. :package-version '(cider . "0.6.0"))
  96. (defconst cider-output-buffer "*cider-out*")
  97. (defcustom cider-interactive-eval-output-destination 'repl-buffer
  98. "The destination for stdout and stderr produced from interactive evaluation."
  99. :type '(choice (const output-buffer)
  100. (const repl-buffer))
  101. :group 'cider
  102. :package-version '(cider . "0.7.0"))
  103. (defface cider-error-highlight-face
  104. '((((supports :underline (:style wave)))
  105. (:underline (:style wave :color "red") :inherit unspecified))
  106. (t (:inherit font-lock-warning-face :underline t)))
  107. "Face used to highlight compilation errors in Clojure buffers."
  108. :group 'cider)
  109. (defface cider-warning-highlight-face
  110. '((((supports :underline (:style wave)))
  111. (:underline (:style wave :color "yellow") :inherit unspecified))
  112. (t (:inherit font-lock-warning-face :underline (:color "yellow"))))
  113. "Face used to highlight compilation warnings in Clojure buffers."
  114. :group 'cider)
  115. (defcustom cider-comment-prefix ";; => "
  116. "The prefix to insert before the first line of commented output."
  117. :type 'string
  118. :group 'cider
  119. :package-version '(cider . "0.16.0"))
  120. (defcustom cider-comment-continued-prefix ";; "
  121. "The prefix to use on the second and subsequent lines of commented output."
  122. :type 'string
  123. :group 'cider
  124. :package-version '(cider . "0.16.0"))
  125. (defcustom cider-comment-postfix ""
  126. "The postfix to be appended after the final line of commented output."
  127. :type 'string
  128. :group 'cider
  129. :package-version '(cider . "0.16.0"))
  130. ;;; Utilities
  131. (defun cider--clear-compilation-highlights ()
  132. "Remove compilation highlights."
  133. (remove-overlays (point-min) (point-max) 'cider-note-p t))
  134. (defun cider-clear-compilation-highlights (&optional arg)
  135. "Remove compilation highlights.
  136. When invoked with a prefix ARG the command doesn't prompt for confirmation."
  137. (interactive "P")
  138. (when (or arg (y-or-n-p "Are you sure you want to clear the compilation highlights? "))
  139. (cider--clear-compilation-highlights)))
  140. (defun cider--quit-error-window ()
  141. "Buries the `cider-error-buffer' and quits its containing window."
  142. (when-let* ((error-win (get-buffer-window cider-error-buffer)))
  143. (save-excursion
  144. (quit-window nil error-win))))
  145. ;;; Dealing with compilation (evaluation) errors and warnings
  146. (defun cider-find-property (property &optional backward)
  147. "Find the next text region which has the specified PROPERTY.
  148. If BACKWARD is t, then search backward.
  149. Returns the position at which PROPERTY was found, or nil if not found."
  150. (let ((p (if backward
  151. (previous-single-char-property-change (point) property)
  152. (next-single-char-property-change (point) property))))
  153. (when (and (not (= p (point-min))) (not (= p (point-max))))
  154. p)))
  155. (defun cider-jump-to-compilation-error (&optional _arg _reset)
  156. "Jump to the line causing the current compilation error.
  157. _ARG and _RESET are ignored, as there is only ever one compilation error.
  158. They exist for compatibility with `next-error'."
  159. (interactive)
  160. (cl-labels ((goto-next-note-boundary
  161. ()
  162. (let ((p (or (cider-find-property 'cider-note-p)
  163. (cider-find-property 'cider-note-p t))))
  164. (when p
  165. (goto-char p)
  166. (message "%s" (get-char-property p 'cider-note))))))
  167. ;; if we're already on a compilation error, first jump to the end of
  168. ;; it, so that we find the next error.
  169. (when (get-char-property (point) 'cider-note-p)
  170. (goto-next-note-boundary))
  171. (goto-next-note-boundary)))
  172. (defun cider--show-error-buffer-p ()
  173. "Return non-nil if the error buffer must be shown on error.
  174. Takes into account both the value of `cider-show-error-buffer' and the
  175. currently selected buffer."
  176. (let* ((selected-buffer (window-buffer (selected-window)))
  177. (replp (with-current-buffer selected-buffer (derived-mode-p 'cider-repl-mode))))
  178. (memq cider-show-error-buffer
  179. (if replp
  180. '(t always only-in-repl)
  181. '(t always except-in-repl)))))
  182. (defun cider-new-error-buffer (&optional mode error-types)
  183. "Return an empty error buffer using MODE.
  184. When deciding whether to display the buffer, takes into account not only
  185. the value of `cider-show-error-buffer' and the currently selected buffer
  186. but also the ERROR-TYPES of the error, which is checked against the
  187. `cider-stacktrace-suppressed-errors' set.
  188. When deciding whether to select the buffer, takes into account the value of
  189. `cider-auto-select-error-buffer'."
  190. (if (and (cider--show-error-buffer-p)
  191. (not (cider-stacktrace-some-suppressed-errors-p error-types)))
  192. (cider-popup-buffer cider-error-buffer cider-auto-select-error-buffer mode 'ancillary)
  193. (cider-make-popup-buffer cider-error-buffer mode 'ancillary)))
  194. (defun cider-emit-into-color-buffer (buffer value)
  195. "Emit into color BUFFER the provided VALUE."
  196. (with-current-buffer buffer
  197. (let ((inhibit-read-only t)
  198. (buffer-undo-list t))
  199. (goto-char (point-max))
  200. (insert (format "%s" value))
  201. (ansi-color-apply-on-region (point-min) (point-max)))
  202. (goto-char (point-min))))
  203. (defun cider--handle-err-eval-response (response)
  204. "Render eval RESPONSE into a new error buffer.
  205. Uses the value of the `out' slot in RESPONSE."
  206. (nrepl-dbind-response response (out)
  207. (when out
  208. (let ((error-buffer (cider-new-error-buffer)))
  209. (cider-emit-into-color-buffer error-buffer out)
  210. (with-current-buffer error-buffer
  211. (compilation-minor-mode +1))))))
  212. (defun cider-default-err-eval-handler ()
  213. "Display the last exception without middleware support."
  214. (cider--handle-err-eval-response
  215. (cider-nrepl-sync-request:eval
  216. "(clojure.stacktrace/print-cause-trace *e)")))
  217. (defun cider--render-stacktrace-causes (causes &optional error-types)
  218. "If CAUSES is non-nil, render its contents into a new error buffer.
  219. Optional argument ERROR-TYPES contains a list which should determine the
  220. op/situation that originated this error."
  221. (when causes
  222. (let ((error-buffer (cider-new-error-buffer #'cider-stacktrace-mode error-types)))
  223. (cider-stacktrace-render error-buffer (reverse causes) error-types))))
  224. (defun cider--handle-stacktrace-response (response causes)
  225. "Handle stacktrace op RESPONSE, aggregating the result into CAUSES.
  226. If RESPONSE contains a cause, cons it onto CAUSES and return that. If
  227. RESPONSE is the final message (i.e. it contains a status), render CAUSES
  228. into a new error buffer."
  229. (nrepl-dbind-response response (class status)
  230. (cond (class (cons response causes))
  231. (status (cider--render-stacktrace-causes causes)))))
  232. (defun cider-default-err-op-handler ()
  233. "Display the last exception, with middleware support."
  234. ;; Causes are returned as a series of messages, which we aggregate in `causes'
  235. (let (causes)
  236. (cider-nrepl-send-request
  237. (thread-last
  238. (map-merge 'list
  239. '(("op" "stacktrace"))
  240. (cider--nrepl-print-request-map fill-column))
  241. (seq-mapcat #'identity))
  242. (lambda (response)
  243. ;; While the return value of `cider--handle-stacktrace-response' is not
  244. ;; meaningful for the last message, we do not need the value of `causes'
  245. ;; after it has been handled, so it's fine to set it unconditionally here
  246. (setq causes (cider--handle-stacktrace-response response causes))))))
  247. (defun cider-default-err-handler ()
  248. "This function determines how the error buffer is shown.
  249. It delegates the actual error content to the eval or op handler."
  250. (if (cider-nrepl-op-supported-p "stacktrace")
  251. (cider-default-err-op-handler)
  252. (cider-default-err-eval-handler)))
  253. (defvar cider-compilation-regexp
  254. '("\\(?:.*\\(warning, \\)\\|.*?\\(, compiling\\):(\\)\\(.*?\\):\\([[:digit:]]+\\)\\(?::\\([[:digit:]]+\\)\\)?\\(\\(?: - \\(.*\\)\\)\\|)\\)" 3 4 5 (1))
  255. "Specifications for matching errors and warnings in Clojure stacktraces.
  256. See `compilation-error-regexp-alist' for help on their format.")
  257. (add-to-list 'compilation-error-regexp-alist-alist
  258. (cons 'cider cider-compilation-regexp))
  259. (add-to-list 'compilation-error-regexp-alist 'cider)
  260. (defun cider-extract-error-info (regexp message)
  261. "Extract error information with REGEXP against MESSAGE."
  262. (let ((file (nth 1 regexp))
  263. (line (nth 2 regexp))
  264. (col (nth 3 regexp))
  265. (type (nth 4 regexp))
  266. (pat (car regexp)))
  267. (when (string-match pat message)
  268. ;; special processing for type (1.2) style
  269. (setq type (if (consp type)
  270. (or (and (car type) (match-end (car type)) 1)
  271. (and (cdr type) (match-end (cdr type)) 0)
  272. 2)))
  273. (list
  274. (when file
  275. (let ((val (match-string-no-properties file message)))
  276. (unless (string= val "NO_SOURCE_PATH") val)))
  277. (when line (string-to-number (match-string-no-properties line message)))
  278. (when col
  279. (let ((val (match-string-no-properties col message)))
  280. (when val (string-to-number val))))
  281. (aref [cider-warning-highlight-face
  282. cider-warning-highlight-face
  283. cider-error-highlight-face]
  284. (or type 2))
  285. message))))
  286. (defun cider--goto-expression-start ()
  287. "Go to the beginning a list, vector, map or set outside of a string.
  288. We do so by starting and the current position and proceeding backwards
  289. until we find a delimiters that's not inside a string."
  290. (if (and (looking-back "[])}]" (line-beginning-position))
  291. (null (nth 3 (syntax-ppss))))
  292. (backward-sexp)
  293. (while (or (not (looking-at-p "[({[]"))
  294. (nth 3 (syntax-ppss)))
  295. (backward-char))))
  296. (defun cider--find-last-error-location (message)
  297. "Return the location (begin end buffer) from the Clojure error MESSAGE.
  298. If location could not be found, return nil."
  299. (save-excursion
  300. (let ((info (cider-extract-error-info cider-compilation-regexp message)))
  301. (when info
  302. (let ((file (nth 0 info))
  303. (line (nth 1 info))
  304. (col (nth 2 info)))
  305. (unless (or (not (stringp file))
  306. (cider--tooling-file-p file))
  307. (when-let* ((buffer (cider-find-file file)))
  308. (with-current-buffer buffer
  309. (save-excursion
  310. (save-restriction
  311. (widen)
  312. (goto-char (point-min))
  313. (forward-line (1- line))
  314. (move-to-column (or col 0))
  315. (let ((begin (progn (if col (cider--goto-expression-start) (back-to-indentation))
  316. (point)))
  317. (end (progn (if col (forward-list) (move-end-of-line nil))
  318. (point))))
  319. (list begin end buffer))))))))))))
  320. (defun cider-handle-compilation-errors (message eval-buffer)
  321. "Highlight and jump to compilation error extracted from MESSAGE.
  322. EVAL-BUFFER is the buffer that was current during user's interactive
  323. evaluation command. Honor `cider-auto-jump-to-error'."
  324. (when-let* ((loc (cider--find-last-error-location message))
  325. (overlay (make-overlay (nth 0 loc) (nth 1 loc) (nth 2 loc)))
  326. (info (cider-extract-error-info cider-compilation-regexp message)))
  327. (let* ((face (nth 3 info))
  328. (note (nth 4 info))
  329. (auto-jump (if (eq cider-auto-jump-to-error 'errors-only)
  330. (not (or (eq face 'cider-warning-highlight-face)
  331. (string-match-p "warning" note)))
  332. cider-auto-jump-to-error)))
  333. (overlay-put overlay 'cider-note-p t)
  334. (overlay-put overlay 'font-lock-face face)
  335. (overlay-put overlay 'cider-note note)
  336. (overlay-put overlay 'help-echo note)
  337. (overlay-put overlay 'modification-hooks
  338. (list (lambda (o &rest _args) (delete-overlay o))))
  339. (when auto-jump
  340. (with-current-buffer eval-buffer
  341. (push-mark)
  342. ;; At this stage selected window commonly is *cider-error* and we need to
  343. ;; re-select the original user window. If eval-buffer is not
  344. ;; visible it was probably covered as a result of a small screen or user
  345. ;; configuration (https://github.com/clojure-emacs/cider/issues/847). In
  346. ;; that case we don't jump at all in order to avoid covering *cider-error*
  347. ;; buffer.
  348. (when-let* ((win (get-buffer-window eval-buffer)))
  349. (with-selected-window win
  350. (cider-jump-to (nth 2 loc) (car loc)))))))))
  351. ;;; Interactive evaluation handlers
  352. (defun cider-insert-eval-handler (&optional buffer)
  353. "Make an nREPL evaluation handler for the BUFFER.
  354. The handler simply inserts the result value in BUFFER."
  355. (let ((eval-buffer (current-buffer)))
  356. (nrepl-make-response-handler (or buffer eval-buffer)
  357. (lambda (_buffer value)
  358. (with-current-buffer buffer
  359. (insert value)))
  360. (lambda (_buffer out)
  361. (cider-repl-emit-interactive-stdout out))
  362. (lambda (_buffer err)
  363. (cider-handle-compilation-errors err eval-buffer))
  364. '())))
  365. (defun cider--emit-interactive-eval-output (output repl-emit-function)
  366. "Emit output resulting from interactive code evaluation.
  367. The OUTPUT can be sent to either a dedicated output buffer or the current
  368. REPL buffer. This is controlled by `cider-interactive-eval-output-destination'.
  369. REPL-EMIT-FUNCTION emits the OUTPUT."
  370. (pcase cider-interactive-eval-output-destination
  371. (`output-buffer (let ((output-buffer (or (get-buffer cider-output-buffer)
  372. (cider-popup-buffer cider-output-buffer t))))
  373. (cider-emit-into-popup-buffer output-buffer output)
  374. (pop-to-buffer output-buffer)))
  375. (`repl-buffer (funcall repl-emit-function output))
  376. (_ (error "Unsupported value %s for `cider-interactive-eval-output-destination'"
  377. cider-interactive-eval-output-destination))))
  378. (defun cider-emit-interactive-eval-output (output)
  379. "Emit OUTPUT resulting from interactive code evaluation.
  380. The output can be send to either a dedicated output buffer or the current
  381. REPL buffer. This is controlled via
  382. `cider-interactive-eval-output-destination'."
  383. (cider--emit-interactive-eval-output output 'cider-repl-emit-interactive-stdout))
  384. (defun cider-emit-interactive-eval-err-output (output)
  385. "Emit err OUTPUT resulting from interactive code evaluation.
  386. The output can be send to either a dedicated output buffer or the current
  387. REPL buffer. This is controlled via
  388. `cider-interactive-eval-output-destination'."
  389. (cider--emit-interactive-eval-output output 'cider-repl-emit-interactive-stderr))
  390. (defun cider--make-fringe-overlays-for-region (beg end)
  391. "Place eval indicators on all sexps between BEG and END."
  392. (with-current-buffer (if (markerp end)
  393. (marker-buffer end)
  394. (current-buffer))
  395. (save-excursion
  396. (goto-char beg)
  397. (remove-overlays beg end 'category 'cider-fringe-indicator)
  398. (condition-case nil
  399. (while (progn (clojure-forward-logical-sexp)
  400. (and (<= (point) end)
  401. (not (eobp))))
  402. (cider--make-fringe-overlay (point)))
  403. (scan-error nil)))))
  404. (defun cider-interactive-eval-handler (&optional buffer place)
  405. "Make an interactive eval handler for BUFFER.
  406. PLACE is used to display the evaluation result.
  407. If non-nil, it can be the position where the evaluated sexp ends,
  408. or it can be a list with (START END) of the evaluated region."
  409. (let* ((eval-buffer (current-buffer))
  410. (beg (car-safe place))
  411. (end (or (car-safe (cdr-safe place)) place))
  412. (beg (when beg (copy-marker beg)))
  413. (end (when end (copy-marker end)))
  414. (fringed nil))
  415. (nrepl-make-response-handler (or buffer eval-buffer)
  416. (lambda (_buffer value)
  417. (if beg
  418. (unless fringed
  419. (cider--make-fringe-overlays-for-region beg end)
  420. (setq fringed t))
  421. (cider--make-fringe-overlay end))
  422. (cider--display-interactive-eval-result value end))
  423. (lambda (_buffer out)
  424. (cider-emit-interactive-eval-output out))
  425. (lambda (_buffer err)
  426. (cider-emit-interactive-eval-err-output err)
  427. (cider-handle-compilation-errors err eval-buffer))
  428. '())))
  429. (defun cider-load-file-handler (&optional buffer)
  430. "Make a load file handler for BUFFER."
  431. (let ((eval-buffer (current-buffer)))
  432. (nrepl-make-response-handler (or buffer eval-buffer)
  433. (lambda (buffer value)
  434. (cider--display-interactive-eval-result value)
  435. (when (buffer-live-p buffer)
  436. (with-current-buffer buffer
  437. (cider--make-fringe-overlays-for-region (point-min) (point-max))
  438. (run-hooks 'cider-file-loaded-hook))))
  439. (lambda (_buffer value)
  440. (cider-emit-interactive-eval-output value))
  441. (lambda (_buffer err)
  442. (cider-emit-interactive-eval-err-output err)
  443. (cider-handle-compilation-errors err eval-buffer))
  444. '()
  445. (lambda ()
  446. (funcall nrepl-err-handler)))))
  447. (defun cider-eval-print-handler (&optional buffer)
  448. "Make a handler for evaluating and printing result in BUFFER."
  449. (nrepl-make-response-handler (or buffer (current-buffer))
  450. (lambda (buffer value)
  451. (with-current-buffer buffer
  452. (insert
  453. (if (derived-mode-p 'cider-clojure-interaction-mode)
  454. (format "\n%s\n" value)
  455. value))))
  456. (lambda (_buffer out)
  457. (cider-emit-interactive-eval-output out))
  458. (lambda (_buffer err)
  459. (cider-emit-interactive-eval-err-output err))
  460. '()))
  461. (defun cider-eval-print-with-comment-handler (buffer location comment-prefix)
  462. "Make a handler for evaluating and printing commented results in BUFFER.
  463. LOCATION is the location marker at which to insert. COMMENT-PREFIX is the
  464. comment prefix to use."
  465. (nrepl-make-response-handler buffer
  466. (lambda (buffer value)
  467. (with-current-buffer buffer
  468. (save-excursion
  469. (goto-char (marker-position location))
  470. (insert (concat comment-prefix
  471. value "\n")))))
  472. (lambda (_buffer out)
  473. (cider-emit-interactive-eval-output out))
  474. (lambda (_buffer err)
  475. (cider-emit-interactive-eval-err-output err))
  476. '()))
  477. (defun cider-eval-pprint-with-multiline-comment-handler (buffer location comment-prefix continued-prefix comment-postfix)
  478. "Make a handler for evaluating and inserting results in BUFFER.
  479. The inserted text is pretty-printed and region will be commented.
  480. LOCATION is the location marker at which to insert.
  481. COMMENT-PREFIX is the comment prefix for the first line of output.
  482. CONTINUED-PREFIX is the comment prefix to use for the remaining lines.
  483. COMMENT-POSTFIX is the text to output after the last line."
  484. (let ((res ""))
  485. (nrepl-make-response-handler
  486. buffer
  487. (lambda (_buffer value)
  488. (setq res (concat res value)))
  489. nil
  490. nil
  491. (lambda (buffer)
  492. (with-current-buffer buffer
  493. (save-excursion
  494. (goto-char (marker-position location))
  495. (let ((lines (split-string res "[\n]+" t)))
  496. ;; only the first line gets the normal comment-prefix
  497. (insert (concat comment-prefix (pop lines)))
  498. (dolist (elem lines)
  499. (insert (concat "\n" continued-prefix elem)))
  500. (unless (string= comment-postfix "")
  501. (insert comment-postfix))))))
  502. nil
  503. nil
  504. (lambda (_buffer warning)
  505. (setq res (concat res warning))))))
  506. (defun cider-popup-eval-handler (&optional buffer)
  507. "Make a handler for printing evaluation results in popup BUFFER.
  508. This is used by pretty-printing commands."
  509. (nrepl-make-response-handler
  510. (or buffer (current-buffer))
  511. (lambda (buffer value)
  512. (cider-emit-into-popup-buffer buffer (ansi-color-apply value) nil t))
  513. (lambda (_buffer out)
  514. (cider-emit-interactive-eval-output out))
  515. (lambda (_buffer err)
  516. (cider-emit-interactive-eval-err-output err))
  517. nil
  518. nil
  519. nil
  520. (lambda (buffer warning)
  521. (cider-emit-into-popup-buffer buffer warning 'font-lock-warning-face t))))
  522. ;;; Interactive valuation commands
  523. (defvar cider-to-nrepl-filename-function
  524. (with-no-warnings
  525. (if (eq system-type 'cygwin)
  526. #'cygwin-convert-file-name-to-windows
  527. #'identity))
  528. "Function to translate Emacs filenames to nREPL namestrings.")
  529. (defun cider--prep-interactive-eval (form connection)
  530. "Prepare the environment for an interactive eval of FORM in CONNECTION.
  531. Ensure the current ns declaration has been evaluated (so that the ns
  532. containing FORM exists). Cache ns-form in the current buffer unless FORM is
  533. ns declaration itself. Clear any compilation highlights and kill the error
  534. window."
  535. (cider--clear-compilation-highlights)
  536. (cider--quit-error-window)
  537. (let ((cur-ns-form (cider-ns-form)))
  538. (when (and cur-ns-form
  539. (not (cider-ns-form-p form))
  540. (cider-repl--ns-form-changed-p cur-ns-form connection))
  541. (when cider-auto-track-ns-form-changes
  542. ;; The first interactive eval on a file can load a lot of libs. This can
  543. ;; easily lead to more than 10 sec.
  544. (let ((nrepl-sync-request-timeout 30))
  545. ;; TODO: check for evaluation errors
  546. (cider-nrepl-sync-request:eval cur-ns-form connection)))
  547. ;; cache at the end, in case of errors
  548. (cider-repl--cache-ns-form cur-ns-form connection))))
  549. (defvar-local cider-interactive-eval-override nil
  550. "Function to call instead of `cider-interactive-eval'.")
  551. (defun cider-interactive-eval (form &optional callback bounds additional-params)
  552. "Evaluate FORM and dispatch the response to CALLBACK.
  553. If the code to be evaluated comes from a buffer, it is preferred to use a
  554. nil FORM, and specify the code via the BOUNDS argument instead.
  555. This function is the main entry point in CIDER's interactive evaluation
  556. API. Most other interactive eval functions should rely on this function.
  557. If CALLBACK is nil use `cider-interactive-eval-handler'.
  558. BOUNDS, if non-nil, is a list of two numbers marking the start and end
  559. positions of FORM in its buffer.
  560. ADDITIONAL-PARAMS is a map to be merged into the request message.
  561. If `cider-interactive-eval-override' is a function, call it with the same
  562. arguments and only proceed with evaluation if it returns nil."
  563. (let ((form (or form (apply #'buffer-substring-no-properties bounds)))
  564. (start (car-safe bounds))
  565. (end (car-safe (cdr-safe bounds))))
  566. (when (and start end)
  567. (remove-overlays start end 'cider-temporary t))
  568. (unless (and cider-interactive-eval-override
  569. (functionp cider-interactive-eval-override)
  570. (funcall cider-interactive-eval-override form callback bounds))
  571. (cider-map-repls :auto
  572. (lambda (connection)
  573. (cider--prep-interactive-eval form connection)
  574. (cider-nrepl-request:eval
  575. form
  576. (or callback (cider-interactive-eval-handler nil bounds))
  577. ;; always eval ns forms in the user namespace
  578. ;; otherwise trying to eval ns form for the first time will produce an error
  579. (if (cider-ns-form-p form) "user" (cider-current-ns))
  580. (when start (line-number-at-pos start))
  581. (when start (cider-column-number-at-pos start))
  582. (seq-mapcat #'identity additional-params)
  583. connection))))))
  584. (defun cider-eval-region (start end)
  585. "Evaluate the region between START and END."
  586. (interactive "r")
  587. (cider-interactive-eval nil
  588. nil
  589. (list start end)
  590. (cider--nrepl-pr-request-map)))
  591. (defun cider-eval-last-sexp (&optional output-to-current-buffer)
  592. "Evaluate the expression preceding point.
  593. If invoked with OUTPUT-TO-CURRENT-BUFFER, print the result in the current
  594. buffer."
  595. (interactive "P")
  596. (cider-interactive-eval nil
  597. (when output-to-current-buffer (cider-eval-print-handler))
  598. (cider-last-sexp 'bounds)
  599. (cider--nrepl-pr-request-map)))
  600. (defun cider-eval-last-sexp-and-replace ()
  601. "Evaluate the expression preceding point and replace it with its result."
  602. (interactive)
  603. (let ((last-sexp (cider-last-sexp)))
  604. ;; we have to be sure the evaluation won't result in an error
  605. (cider-nrepl-sync-request:eval last-sexp)
  606. ;; seems like the sexp is valid, so we can safely kill it
  607. (backward-kill-sexp)
  608. (cider-interactive-eval last-sexp
  609. (cider-eval-print-handler)
  610. nil
  611. (cider--nrepl-pr-request-map))))
  612. (defun cider-eval-sexp-at-point (&optional output-to-current-buffer)
  613. "Evaluate the expression around point.
  614. If invoked with OUTPUT-TO-CURRENT-BUFFER, output the result to current buffer."
  615. (interactive "P")
  616. (save-excursion
  617. (goto-char (cadr (cider-sexp-at-point 'bounds)))
  618. (cider-eval-last-sexp output-to-current-buffer)))
  619. (defvar-local cider-previous-eval-context nil
  620. "The previous evaluation context if any.
  621. That's set by commands like `cider-eval-last-sexp-in-context'.")
  622. (defun cider--eval-in-context (code)
  623. "Evaluate CODE in user-provided evaluation context."
  624. (let* ((code (string-trim-right code))
  625. (eval-context (read-string
  626. (format "Evaluation context (let-style) for `%s': " code)
  627. cider-previous-eval-context))
  628. (code (concat "(let [" eval-context "]\n " code ")")))
  629. (cider-interactive-eval code
  630. nil
  631. nil
  632. (cider--nrepl-pr-request-map))
  633. (setq-local cider-previous-eval-context eval-context)))
  634. (defun cider-eval-last-sexp-in-context ()
  635. "Evaluate the preceding sexp in user-supplied context.
  636. The context is just a let binding vector (without the brackets).
  637. The context is remembered between command invocations."
  638. (interactive)
  639. (cider--eval-in-context (cider-last-sexp)))
  640. (defun cider-eval-sexp-at-point-in-context ()
  641. "Evaluate the preceding sexp in user-supplied context.
  642. The context is just a let binding vector (without the brackets).
  643. The context is remembered between command invocations."
  644. (interactive)
  645. (cider--eval-in-context (cider-sexp-at-point)))
  646. (defun cider-eval-defun-to-comment (&optional insert-before)
  647. "Evaluate the \"top-level\" form and insert result as comment.
  648. The formatting of the comment is defined in `cider-comment-prefix'
  649. which, by default, is \";; => \" and can be customized.
  650. With the prefix arg INSERT-BEFORE, insert before the form, otherwise afterwards."
  651. (interactive "P")
  652. (let* ((bounds (cider-defun-at-point 'bounds))
  653. (insertion-point (nth (if insert-before 0 1) bounds)))
  654. (cider-interactive-eval nil
  655. (cider-eval-print-with-comment-handler
  656. (current-buffer)
  657. (set-marker (make-marker) insertion-point)
  658. cider-comment-prefix)
  659. bounds
  660. (cider--nrepl-pr-request-map))))
  661. (defun cider-pprint-form-to-comment (form-fn insert-before)
  662. "Evaluate the form selected by FORM-FN and insert result as comment.
  663. FORM-FN can be either `cider-last-sexp' or `cider-defun-at-point'.
  664. The formatting of the comment is controlled via three options:
  665. `cider-comment-prefix' \";; => \"
  666. `cider-comment-continued-prefix' \";; \"
  667. `cider-comment-postfix' \"\"
  668. so that with customization you can optionally wrap the output
  669. in the reader macro \"#_( .. )\", or \"(comment ... )\", or any
  670. other desired formatting.
  671. If INSERT-BEFORE is non-nil, insert before the form, otherwise afterwards."
  672. (let* ((bounds (funcall form-fn 'bounds))
  673. (insertion-point (nth (if insert-before 0 1) bounds))
  674. ;; when insert-before, we need a newline after the output to
  675. ;; avoid commenting the first line of the form
  676. (comment-postfix (concat cider-comment-postfix
  677. (if insert-before "\n" ""))))
  678. (cider-interactive-eval nil
  679. (cider-eval-pprint-with-multiline-comment-handler
  680. (current-buffer)
  681. (set-marker (make-marker) insertion-point)
  682. cider-comment-prefix
  683. cider-comment-continued-prefix
  684. comment-postfix)
  685. bounds
  686. (cider--nrepl-print-request-map fill-column))))
  687. (defun cider-pprint-eval-last-sexp-to-comment (&optional insert-before)
  688. "Evaluate the last sexp and insert result as comment.
  689. The formatting of the comment is controlled via three options:
  690. `cider-comment-prefix' \";; => \"
  691. `cider-comment-continued-prefix' \";; \"
  692. `cider-comment-postfix' \"\"
  693. so that with customization you can optionally wrap the output
  694. in the reader macro \"#_( .. )\", or \"(comment ... )\", or any
  695. other desired formatting.
  696. If INSERT-BEFORE is non-nil, insert before the form, otherwise afterwards."
  697. (interactive "P")
  698. (cider-pprint-form-to-comment 'cider-last-sexp insert-before))
  699. (defun cider-pprint-eval-defun-to-comment (&optional insert-before)
  700. "Evaluate the \"top-level\" form and insert result as comment.
  701. The formatting of the comment is controlled via three options:
  702. `cider-comment-prefix' \";; => \"
  703. `cider-comment-continued-prefix' \";; \"
  704. `cider-comment-postfix' \"\"
  705. so that with customization you can optionally wrap the output
  706. in the reader macro \"#_( .. )\", or \"(comment ... )\", or any
  707. other desired formatting.
  708. If INSERT-BEFORE is non-nil, insert before the form, otherwise afterwards."
  709. (interactive "P")
  710. (cider-pprint-form-to-comment 'cider-defun-at-point insert-before))
  711. (declare-function cider-switch-to-repl-buffer "cider-mode")
  712. (defun cider-eval-last-sexp-to-repl (&optional prefix)
  713. "Evaluate the expression preceding point and insert its result in the REPL.
  714. If invoked with a PREFIX argument, switch to the REPL buffer."
  715. (interactive "P")
  716. (cider-interactive-eval nil
  717. (cider-insert-eval-handler (cider-current-repl))
  718. (cider-last-sexp 'bounds)
  719. (cider--nrepl-pr-request-map))
  720. (when prefix
  721. (cider-switch-to-repl-buffer)))
  722. (defun cider-pprint-eval-last-sexp-to-repl (&optional prefix)
  723. "Evaluate expr before point and insert its pretty-printed result in the REPL.
  724. If invoked with a PREFIX argument, switch to the REPL buffer."
  725. (interactive "P")
  726. (cider-interactive-eval nil
  727. (cider-insert-eval-handler (cider-current-repl))
  728. (cider-last-sexp 'bounds)
  729. (cider--nrepl-print-request-map fill-column))
  730. (when prefix
  731. (cider-switch-to-repl-buffer)))
  732. (defun cider-eval-print-last-sexp (&optional pretty-print)
  733. "Evaluate the expression preceding point.
  734. Print its value into the current buffer.
  735. With an optional PRETTY-PRINT prefix it pretty-prints the result."
  736. (interactive "P")
  737. (cider-interactive-eval nil
  738. (cider-eval-print-handler)
  739. (cider-last-sexp 'bounds)
  740. (if pretty-print
  741. (cider--nrepl-print-request-map fill-column)
  742. (cider--nrepl-pr-request-map))))
  743. (defun cider--pprint-eval-form (form)
  744. "Pretty print FORM in popup buffer."
  745. (let* ((buffer (current-buffer))
  746. (result-buffer (cider-popup-buffer cider-result-buffer nil 'clojure-mode 'ancillary))
  747. (handler (cider-popup-eval-handler result-buffer)))
  748. (with-current-buffer buffer
  749. (cider-interactive-eval (when (stringp form) form)
  750. handler
  751. (when (consp form) form)
  752. (cider--nrepl-print-request-map fill-column)))))
  753. (defun cider-pprint-eval-last-sexp (&optional output-to-current-buffer)
  754. "Evaluate the sexp preceding point and pprint its value.
  755. If invoked with OUTPUT-TO-CURRENT-BUFFER, insert as comment in the current
  756. buffer, else display in a popup buffer."
  757. (interactive "P")
  758. (if output-to-current-buffer
  759. (cider-pprint-eval-last-sexp-to-comment)
  760. (cider--pprint-eval-form (cider-last-sexp 'bounds))))
  761. (defun cider--prompt-and-insert-inline-dbg ()
  762. "Insert a #dbg button at the current sexp."
  763. (save-excursion
  764. (let ((beg))
  765. (skip-chars-forward "\r\n[:blank:]")
  766. (unless (looking-at-p "(")
  767. (ignore-errors (backward-up-list)))
  768. (setq beg (point))
  769. (let* ((cond (cider-read-from-minibuffer "Condition for debugging (leave empty for \"always\"): "))
  770. (button (propertize (concat "#dbg"
  771. (unless (equal cond "")
  772. (format " ^{:break/when %s}" cond)))
  773. 'font-lock-face 'cider-fragile-button-face)))
  774. (when (> (current-column) 30)
  775. (insert "\n")
  776. (indent-according-to-mode))
  777. (insert button)
  778. (when (> (current-column) 40)
  779. (insert "\n")
  780. (indent-according-to-mode)))
  781. (make-button beg (point)
  782. 'help-echo "Breakpoint. Reevaluate this form to remove it."
  783. :type 'cider-fragile))))
  784. (defun cider-eval-defun-at-point (&optional debug-it)
  785. "Evaluate the current toplevel form, and print result in the minibuffer.
  786. With DEBUG-IT prefix argument, also debug the entire form as with the
  787. command `cider-debug-defun-at-point'."
  788. (interactive "P")
  789. (let ((inline-debug (eq 16 (car-safe debug-it))))
  790. (when debug-it
  791. (when (derived-mode-p 'clojurescript-mode)
  792. (when (y-or-n-p (concat "The debugger doesn't support ClojureScript yet, and we need help with that."
  793. " \nWould you like to read the Feature Request?"))
  794. (browse-url "https://github.com/clojure-emacs/cider/issues/1416"))
  795. (user-error "The debugger does not support ClojureScript"))
  796. (when inline-debug
  797. (cider--prompt-and-insert-inline-dbg)))
  798. (cider-interactive-eval (when (and debug-it (not inline-debug))
  799. (concat "#dbg\n" (cider-defun-at-point)))
  800. nil
  801. (cider-defun-at-point 'bounds)
  802. (cider--nrepl-pr-request-map))))
  803. (defun cider--calculate-opening-delimiters ()
  804. "Walks up the list of expressions to collect all sexp opening delimiters.
  805. The result is a list of the delimiters.
  806. That function is used in `cider-eval-defun-up-to-point' so it can make an
  807. incomplete expression complete."
  808. (interactive)
  809. (let ((result nil))
  810. (save-excursion
  811. (condition-case nil
  812. (while t
  813. (backward-up-list)
  814. (push (char-after) result))
  815. (error result)))))
  816. (defun cider--matching-delimiter (delimiter)
  817. "Get the matching (opening/closing) delimiter for DELIMITER."
  818. (pcase delimiter
  819. (?\( ?\))
  820. (?\[ ?\])
  821. (?\{ ?\})
  822. (?\) ?\()
  823. (?\] ?\[)
  824. (?\} ?\{)))
  825. (defun cider--calculate-closing-delimiters ()
  826. "Compute the list of closing delimiters to make the defun before point valid."
  827. (mapcar #'cider--matching-delimiter (cider--calculate-opening-delimiters)))
  828. (defun cider-eval-defun-up-to-point (&optional output-to-current-buffer)
  829. "Evaluate the current toplevel form up to point.
  830. If invoked with OUTPUT-TO-CURRENT-BUFFER, print the result in the current
  831. buffer. It constructs an expression to eval in the following manner:
  832. - It find the code between the point and the start of the toplevel expression;
  833. - It balances this bit of code by closing all open expressions;
  834. - It evaluates the resulting code using `cider-interactive-eval'."
  835. (interactive "P")
  836. (let* ((beg-of-defun (save-excursion (beginning-of-defun) (point)))
  837. (code (buffer-substring-no-properties beg-of-defun (point)))
  838. (code (concat code (cider--calculate-closing-delimiters))))
  839. (cider-interactive-eval code
  840. (when output-to-current-buffer
  841. (cider-eval-print-handler))
  842. nil
  843. (cider--nrepl-pr-request-map))))
  844. (defun cider-eval-sexp-up-to-point (&optional output-to-current-buffer)
  845. "Evaluate the current sexp form up to point.
  846. If invoked with OUTPUT-TO-CURRENT-BUFFER, print the result in the current
  847. buffer. It constructs an expression to eval in the following manner:
  848. - It finds the code between the point and the start of the sexp expression;
  849. - It balances this bit of code by closing the expression;
  850. - It evaluates the resulting code using `cider-interactive-eval'."
  851. (interactive "P")
  852. (let* ((beg-of-sexp (save-excursion (up-list) (backward-list) (point)))
  853. (beg-delimiter (save-excursion (up-list) (backward-list) (char-after)))
  854. (beg-set? (save-excursion (up-list) (backward-list) (char-before)))
  855. (code (buffer-substring-no-properties beg-of-sexp (point)))
  856. (code (if (= beg-set? ?#) (concat (list beg-set?) code) code))
  857. (code (concat code (list (cider--matching-delimiter beg-delimiter)))))
  858. (cider-interactive-eval code
  859. (when output-to-current-buffer
  860. (cider-eval-print-handler))
  861. nil
  862. (cider--nrepl-pr-request-map))))
  863. (defun cider-pprint-eval-defun-at-point (&optional output-to-current-buffer)
  864. "Evaluate the \"top-level\" form at point and pprint its value.
  865. If invoked with OUTPUT-TO-CURRENT-BUFFER, insert as comment in the current
  866. buffer, else display in a popup buffer."
  867. (interactive "P")
  868. (if output-to-current-buffer
  869. (cider-pprint-eval-defun-to-comment)
  870. (cider--pprint-eval-form (cider-defun-at-point 'bounds))))
  871. (defun cider-eval-ns-form ()
  872. "Evaluate the current buffer's namespace form."
  873. (interactive)
  874. (when (clojure-find-ns)
  875. (save-excursion
  876. (goto-char (match-beginning 0))
  877. (cider-eval-defun-at-point))))
  878. (defun cider-read-and-eval (&optional value)
  879. "Read a sexp from the minibuffer and output its result to the echo area.
  880. If VALUE is non-nil, it is inserted into the minibuffer as initial input."
  881. (interactive)
  882. (let* ((form (cider-read-from-minibuffer "Clojure Eval: " value))
  883. (override cider-interactive-eval-override)
  884. (ns-form (if (cider-ns-form-p form) "" (format "(ns %s)" (cider-current-ns)))))
  885. (with-current-buffer (get-buffer-create cider-read-eval-buffer)
  886. (erase-buffer)
  887. (clojure-mode)
  888. (unless (string= "" ns-form)
  889. (insert ns-form "\n\n"))
  890. (insert form)
  891. (let ((cider-interactive-eval-override override))
  892. (cider-interactive-eval form
  893. nil
  894. nil
  895. (cider--nrepl-pr-request-map))))))
  896. (defun cider-read-and-eval-defun-at-point ()
  897. "Insert the toplevel form at point in the minibuffer and output its result.
  898. The point is placed next to the function name in the minibuffer to allow
  899. passing arguments."
  900. (interactive)
  901. (let* ((fn-name (cadr (split-string (cider-defun-at-point))))
  902. (form (format "(%s)" fn-name)))
  903. (cider-read-and-eval (cons form (length form)))))
  904. ;; Eval keymaps
  905. (defvar cider-eval-pprint-commands-map
  906. (let ((map (define-prefix-command 'cider-eval-pprint-commands-map)))
  907. ;; single key bindings defined last for display in menu
  908. (define-key map (kbd "e") #'cider-pprint-eval-last-sexp)
  909. (define-key map (kbd "d") #'cider-pprint-eval-defun-at-point)
  910. (define-key map (kbd "c e") #'cider-pprint-eval-last-sexp-to-comment)
  911. (define-key map (kbd "c d") #'cider-pprint-eval-defun-to-comment)
  912. ;; duplicates with C- for convenience
  913. (define-key map (kbd "C-e") #'cider-pprint-eval-last-sexp)
  914. (define-key map (kbd "C-d") #'cider-pprint-eval-defun-at-point)
  915. (define-key map (kbd "C-c e") #'cider-pprint-eval-last-sexp-to-comment)
  916. (define-key map (kbd "C-c C-e") #'cider-pprint-eval-last-sexp-to-comment)
  917. (define-key map (kbd "C-c d") #'cider-pprint-eval-defun-to-comment)
  918. (define-key map (kbd "C-c C-d") #'cider-pprint-eval-defun-to-comment)
  919. map))
  920. (defvar cider-eval-commands-map
  921. (let ((map (define-prefix-command 'cider-eval-commands-map)))
  922. ;; single key bindings defined last for display in menu
  923. (define-key map (kbd "w") #'cider-eval-last-sexp-and-replace)
  924. (define-key map (kbd "r") #'cider-eval-region)
  925. (define-key map (kbd "n") #'cider-eval-ns-form)
  926. (define-key map (kbd "d") #'cider-eval-defun-at-point)
  927. (define-key map (kbd "e") #'cider-eval-last-sexp)
  928. (define-key map (kbd "v") #'cider-eval-sexp-at-point)
  929. (define-key map (kbd "o") #'cider-eval-sexp-up-to-point)
  930. (define-key map (kbd ".") #'cider-read-and-eval-defun-at-point)
  931. (define-key map (kbd "z") #'cider-eval-defun-up-to-point)
  932. (define-key map (kbd "c") #'cider-eval-last-sexp-in-context)
  933. (define-key map (kbd "b") #'cider-eval-sexp-at-point-in-context)
  934. (define-key map (kbd "f") 'cider-eval-pprint-commands-map)
  935. ;; duplicates with C- for convenience
  936. (define-key map (kbd "C-w") #'cider-eval-last-sexp-and-replace)
  937. (define-key map (kbd "C-r") #'cider-eval-region)
  938. (define-key map (kbd "C-n") #'cider-eval-ns-form)
  939. (define-key map (kbd "C-d") #'cider-eval-defun-at-point)
  940. (define-key map (kbd "C-f") #'cider-eval-last-sexp)
  941. (define-key map (kbd "C-v") #'cider-eval-sexp-at-point)
  942. (define-key map (kbd "C-o") #'cider-eval-sexp-up-to-point)
  943. (define-key map (kbd "C-.") #'cider-read-and-eval-defun-at-point)
  944. (define-key map (kbd "C-z") #'cider-eval-defun-up-to-point)
  945. (define-key map (kbd "C-c") #'cider-eval-last-sexp-in-context)
  946. (define-key map (kbd "C-b") #'cider-eval-sexp-at-point-in-context)
  947. (define-key map (kbd "C-f") 'cider-eval-pprint-commands-map)
  948. map))
  949. (defun cider--file-string (file)
  950. "Read the contents of a FILE and return as a string."
  951. (with-current-buffer (find-file-noselect file)
  952. (substring-no-properties (buffer-string))))
  953. (defun cider-load-buffer (&optional buffer)
  954. "Load (eval) BUFFER's file in nREPL.
  955. If no buffer is provided the command acts on the current buffer. If the
  956. buffer is for a cljc file, and both a Clojure and ClojureScript REPL exists
  957. for the project, it is evaluated in both REPLs."
  958. (interactive)
  959. (setq buffer (or buffer (current-buffer)))
  960. ;; When cider-load-buffer or cider-load-file are called in programs the
  961. ;; current context might not match the buffer's context. We use the caller
  962. ;; context instead of the buffer's context because that's the common use
  963. ;; case. For the other use case just let-bind the default-directory.
  964. (let ((orig-default-directory default-directory))
  965. (with-current-buffer buffer
  966. (check-parens)
  967. (let ((default-directory orig-default-directory))
  968. (unless buffer-file-name
  969. (user-error "Buffer `%s' is not associated with a file" (current-buffer)))
  970. (when (and cider-save-file-on-load
  971. (buffer-modified-p)
  972. (or (eq cider-save-file-on-load t)
  973. (y-or-n-p (format "Save file %s? " buffer-file-name))))
  974. (save-buffer))
  975. (remove-overlays nil nil 'cider-temporary t)
  976. (cider--clear-compilation-highlights)
  977. (cider--quit-error-window)
  978. (let ((filename (buffer-file-name buffer))
  979. (ns-form (cider-ns-form)))
  980. (cider-map-repls :auto
  981. (lambda (repl)
  982. (when ns-form
  983. (cider-repl--cache-ns-form ns-form repl))
  984. (cider-request:load-file (cider--file-string filename)
  985. (funcall cider-to-nrepl-filename-function
  986. (cider--server-filename filename))
  987. (file-name-nondirectory filename)
  988. repl)))
  989. (message "Loading %s..." filename))))))
  990. (defun cider-load-file (filename)
  991. "Load (eval) the Clojure file FILENAME in nREPL.
  992. If the file is a cljc file, and both a Clojure and ClojureScript REPL
  993. exists for the project, it is evaluated in both REPLs. The heavy lifting
  994. is done by `cider-load-buffer'."
  995. (interactive (list
  996. (read-file-name "Load file: " nil nil nil
  997. (when (buffer-file-name)
  998. (file-name-nondirectory
  999. (buffer-file-name))))))
  1000. (if-let* ((buffer (find-buffer-visiting filename)))
  1001. (cider-load-buffer buffer)
  1002. (cider-load-buffer (find-file-noselect filename))))
  1003. (defun cider-load-all-files (directory)
  1004. "Load all files in DIRECTORY (recursively).
  1005. Useful when the running nREPL on remote host."
  1006. (interactive "DLoad files beneath directory: ")
  1007. (mapcar #'cider-load-file
  1008. (directory-files-recursively directory "\\.clj[cs]?$")))
  1009. (defalias 'cider-eval-file 'cider-load-file
  1010. "A convenience alias as some people are confused by the load-* names.")
  1011. (defalias 'cider-eval-all-files 'cider-load-all-files
  1012. "A convenience alias as some people are confused by the load-* names.")
  1013. (defalias 'cider-eval-buffer 'cider-load-buffer
  1014. "A convenience alias as some people are confused by the load-* names.")
  1015. (defun cider-load-all-project-ns ()
  1016. "Load all namespaces in the current project."
  1017. (interactive)
  1018. (cider-ensure-connected)
  1019. (cider-ensure-op-supported "ns-load-all")
  1020. (when (y-or-n-p "Are you sure you want to load all namespaces in the project? ")
  1021. (message "Loading all project namespaces...")
  1022. (let ((loaded-ns-count (length (cider-sync-request:ns-load-all))))
  1023. (message "Loaded %d namespaces" loaded-ns-count))))
  1024. (provide 'cider-eval)
  1025. ;;; cider-eval.el ends here