Klimi's new dotfiles with stow.
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

748 satır
34 KiB

4 yıl önce
  1. ;;; cider-debug.el --- CIDER interaction with the cider.debug nREPL middleware -*- lexical-binding: t; -*-
  2. ;; Copyright © 2015-2019 Bozhidar Batsov, Artur Malabarba and CIDER contributors
  3. ;; Author: Artur Malabarba <bruce.connor.am@gmail.com>
  4. ;; This program is free software; you can redistribute it and/or modify
  5. ;; it under the terms of the GNU General Public License as published by
  6. ;; the Free Software Foundation, either version 3 of the License, or
  7. ;; (at your option) any later version.
  8. ;; This program is distributed in the hope that it will be useful,
  9. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. ;; GNU General Public License for more details.
  12. ;; You should have received a copy of the GNU General Public License
  13. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. ;;; Commentary:
  15. ;; Instrument code with `cider-debug-defun-at-point', and when the code is
  16. ;; executed cider-debug will kick in. See this function's doc for more
  17. ;; information.
  18. ;;; Code:
  19. (require 'map)
  20. (require 'seq)
  21. (require 'subr-x)
  22. (require 'spinner)
  23. (require 'cider-browse-ns)
  24. (require 'cider-client)
  25. (require 'cider-eval)
  26. (require 'cider-inspector)
  27. (require 'cider-util)
  28. (require 'cider-common)
  29. (require 'cider-compat)
  30. (require 'nrepl-client) ; `nrepl--mark-id-completed'
  31. (require 'nrepl-dict)
  32. ;;; Customization
  33. (defgroup cider-debug nil
  34. "Presentation and behaviour of the cider debugger."
  35. :prefix "cider-debug-"
  36. :group 'cider
  37. :package-version '(cider . "0.10.0"))
  38. (defface cider-debug-code-overlay-face
  39. '((((class color) (background light)) :background "grey80")
  40. (((class color) (background dark)) :background "grey30"))
  41. "Face used to mark code being debugged."
  42. :group 'cider-debug
  43. :package-version '(cider . "0.9.1"))
  44. (defface cider-debug-prompt-face
  45. '((t :underline t :inherit font-lock-builtin-face))
  46. "Face used to highlight keys in the debug prompt."
  47. :group 'cider-debug
  48. :package-version '(cider . "0.10.0"))
  49. (defface cider-enlightened-face
  50. '((((class color) (background light)) :inherit cider-result-overlay-face
  51. :box (:color "darkorange" :line-width -1))
  52. (((class color) (background dark)) :inherit cider-result-overlay-face
  53. ;; "#dd0" is a dimmer yellow.
  54. :box (:color "#990" :line-width -1)))
  55. "Face used to mark enlightened sexps and their return values."
  56. :group 'cider-debug
  57. :package-version '(cider . "0.11.0"))
  58. (defface cider-enlightened-local-face
  59. '((((class color) (background light)) :weight bold :foreground "darkorange")
  60. (((class color) (background dark)) :weight bold :foreground "yellow"))
  61. "Face used to mark enlightened locals (not their values)."
  62. :group 'cider-debug
  63. :package-version '(cider . "0.11.0"))
  64. (defcustom cider-debug-prompt 'overlay
  65. "If and where to show the keys while debugging.
  66. If `minibuffer', show it in the minibuffer along with the return value.
  67. If `overlay', show it in an overlay above the current function.
  68. If t, do both.
  69. If nil, don't list available keys at all."
  70. :type '(choice (const :tag "Show in minibuffer" minibuffer)
  71. (const :tag "Show above function" overlay)
  72. (const :tag "Show in both places" t)
  73. (const :tag "Don't list keys" nil))
  74. :group 'cider-debug
  75. :package-version '(cider . "0.10.0"))
  76. (defcustom cider-debug-use-overlays t
  77. "Whether to higlight debugging information with overlays.
  78. Takes the same possible values as `cider-use-overlays', but only applies to
  79. values displayed during debugging sessions.
  80. To control the overlay that lists possible keys above the current function,
  81. configure `cider-debug-prompt' instead."
  82. :type '(choice (const :tag "End of line" t)
  83. (const :tag "Bottom of screen" nil)
  84. (const :tag "Both" both))
  85. :group 'cider-debug
  86. :package-version '(cider . "0.9.1"))
  87. (make-obsolete 'cider-debug-print-length 'cider-debug-print-options "0.20")
  88. (make-obsolete 'cider-debug-print-level 'cider-debug-print-options "0.20")
  89. (make-obsolete-variable 'cider-debug-print-options 'cider-print-options "0.21")
  90. ;;; Implementation
  91. (defun cider-browse-instrumented-defs ()
  92. "List all instrumented definitions."
  93. (interactive)
  94. (if-let* ((all (thread-first (cider-nrepl-send-sync-request '("op" "debug-instrumented-defs"))
  95. (nrepl-dict-get "list"))))
  96. (with-current-buffer (cider-popup-buffer cider-browse-ns-buffer t)
  97. (let ((inhibit-read-only t))
  98. (erase-buffer)
  99. (dolist (list all)
  100. (let* ((ns (car list))
  101. (ns-vars-with-meta (cider-sync-request:ns-vars-with-meta ns))
  102. ;; seq of metadata maps of the instrumented vars
  103. (instrumented-meta (mapcar (apply-partially #'nrepl-dict-get ns-vars-with-meta)
  104. (cdr list))))
  105. (cider-browse-ns--list (current-buffer) ns
  106. (seq-mapn #'cider-browse-ns--properties
  107. (cdr list)
  108. instrumented-meta)
  109. ns 'noerase)
  110. (goto-char (point-max))
  111. (insert "\n"))))
  112. (goto-char (point-min)))
  113. (message "No currently instrumented definitions")))
  114. (defun cider--debug-response-handler (response)
  115. "Handles RESPONSE from the cider.debug middleware."
  116. (nrepl-dbind-response response (status id causes)
  117. (when (member "enlighten" status)
  118. (cider--handle-enlighten response))
  119. (when (or (member "eval-error" status)
  120. (member "stack" status))
  121. ;; TODO: Make the error buffer a bit friendlier when we're just printing
  122. ;; the stack.
  123. (cider--render-stacktrace-causes causes))
  124. (when (member "need-debug-input" status)
  125. (cider--handle-debug response))
  126. (when (member "done" status)
  127. (nrepl--mark-id-completed id))))
  128. (defun cider--debug-init-connection ()
  129. "Initialize a connection with the cider.debug middleware."
  130. (cider-nrepl-send-request
  131. (thread-last
  132. (map-merge 'list
  133. '(("op" "init-debugger"))
  134. (cider--nrepl-print-request-map fill-column))
  135. (seq-mapcat #'identity))
  136. #'cider--debug-response-handler))
  137. ;;; Debugging overlays
  138. (defconst cider--fringe-arrow-string
  139. #("." 0 1 (display (left-fringe right-triangle)))
  140. "Used as an overlay's before-string prop to place a fringe arrow.")
  141. (defun cider--debug-display-result-overlay (value)
  142. "Place an overlay at point displaying VALUE."
  143. (when cider-debug-use-overlays
  144. ;; This is cosmetic, let's ensure it doesn't break the session no matter what.
  145. (ignore-errors
  146. ;; Result
  147. (cider--make-result-overlay (cider-font-lock-as-clojure value)
  148. :where (point-marker)
  149. :type 'debug-result
  150. 'before-string cider--fringe-arrow-string)
  151. ;; Code
  152. (cider--make-overlay (save-excursion (clojure-backward-logical-sexp 1) (point))
  153. (point) 'debug-code
  154. 'face 'cider-debug-code-overlay-face
  155. ;; Higher priority than `show-paren'.
  156. 'priority 2000))))
  157. ;;; Minor mode
  158. (defvar-local cider--debug-mode-commands-dict nil
  159. "An nrepl-dict from keys to debug commands.
  160. Autogenerated by `cider--turn-on-debug-mode'.")
  161. (defvar-local cider--debug-mode-response nil
  162. "Response that triggered current debug session.
  163. Set by `cider--turn-on-debug-mode'.")
  164. (defcustom cider-debug-display-locals nil
  165. "If non-nil, local variables are displayed while debugging.
  166. Can be toggled at any time with `\\[cider-debug-toggle-locals]'."
  167. :type 'boolean
  168. :group 'cider-debug
  169. :package-version '(cider . "0.10.0"))
  170. (defun cider--debug-format-locals-list (locals)
  171. "Return a string description of list LOCALS.
  172. Each element of LOCALS should be a list of at least two elements."
  173. (if locals
  174. (let ((left-col-width
  175. ;; To right-indent the variable names.
  176. (apply #'max (mapcar (lambda (l) (string-width (car l))) locals))))
  177. ;; A format string to build a format string. :-P
  178. (mapconcat (lambda (l) (format (format " %%%ds: %%s\n" left-col-width)
  179. (propertize (car l) 'face 'font-lock-variable-name-face)
  180. (cider-font-lock-as-clojure (cadr l))))
  181. locals ""))
  182. ""))
  183. (defun cider--debug-prompt (command-dict)
  184. "Return prompt to display for COMMAND-DICT."
  185. ;; Force `default' face, otherwise the overlay "inherits" the face of the text
  186. ;; after it.
  187. (format (propertize "%s\n" 'face 'default)
  188. (string-join
  189. (nrepl-dict-map (lambda (char cmd)
  190. (when-let* ((pos (cl-search char cmd)))
  191. (put-text-property pos (1+ pos) 'face 'cider-debug-prompt-face cmd))
  192. cmd)
  193. command-dict)
  194. " ")))
  195. (defvar-local cider--debug-prompt-overlay nil)
  196. (defun cider--debug-mode-redisplay ()
  197. "Display the input prompt to the user."
  198. (nrepl-dbind-response cider--debug-mode-response (debug-value input-type locals)
  199. (when (or (eq cider-debug-prompt t)
  200. (eq cider-debug-prompt 'overlay))
  201. (if (overlayp cider--debug-prompt-overlay)
  202. (overlay-put cider--debug-prompt-overlay
  203. 'before-string (cider--debug-prompt input-type))
  204. (setq cider--debug-prompt-overlay
  205. (cider--make-overlay
  206. (max (car (cider-defun-at-point 'bounds))
  207. (window-start))
  208. nil 'debug-prompt
  209. 'before-string (cider--debug-prompt input-type)))))
  210. (let* ((value (concat " " cider-eval-result-prefix
  211. (cider-font-lock-as-clojure
  212. (or debug-value "#unknown#"))))
  213. (to-display
  214. (concat (when cider-debug-display-locals
  215. (cider--debug-format-locals-list locals))
  216. (when (or (eq cider-debug-prompt t)
  217. (eq cider-debug-prompt 'minibuffer))
  218. (cider--debug-prompt input-type))
  219. (when (or (not cider-debug-use-overlays)
  220. (eq cider-debug-use-overlays 'both))
  221. value))))
  222. (if (> (string-width to-display) 0)
  223. (message "%s" to-display)
  224. ;; If there's nothing to display in the minibuffer. Just send the value
  225. ;; to the Messages buffer.
  226. (message "%s" value)
  227. (message nil)))))
  228. (defun cider-debug-toggle-locals ()
  229. "Toggle display of local variables."
  230. (interactive)
  231. (setq cider-debug-display-locals (not cider-debug-display-locals))
  232. (cider--debug-mode-redisplay))
  233. (defun cider--debug-lexical-eval (key form &optional callback _point)
  234. "Eval FORM in the lexical context of debug session given by KEY.
  235. Do nothing if CALLBACK is provided.
  236. Designed to be used as `cider-interactive-eval-override' and called instead
  237. of `cider-interactive-eval' in debug sessions."
  238. ;; The debugger uses its own callback, so if the caller is passing a callback
  239. ;; we return nil and let `cider-interactive-eval' do its thing.
  240. (unless callback
  241. (cider-debug-mode-send-reply (format "{:response :eval, :code %s}" form)
  242. key)
  243. t))
  244. (defvar cider--debug-mode-tool-bar-map
  245. (let ((tool-bar-map (make-sparse-keymap)))
  246. (tool-bar-add-item "right-arrow" #'cider-debug-mode-send-reply :next :label "Next step")
  247. (tool-bar-add-item "next-node" #'cider-debug-mode-send-reply :continue :label "Continue")
  248. (tool-bar-add-item "jump-to" #'cider-debug-mode-send-reply :out :label "Out of sexp")
  249. (tool-bar-add-item "exit" #'cider-debug-mode-send-reply :quit :label "Quit")
  250. tool-bar-map))
  251. (defvar cider--debug-mode-map)
  252. (define-minor-mode cider--debug-mode
  253. "Mode active during debug sessions.
  254. In order to work properly, this mode must be activated by
  255. `cider--turn-on-debug-mode'."
  256. nil " DEBUG" '()
  257. (if cider--debug-mode
  258. (if cider--debug-mode-response
  259. (nrepl-dbind-response cider--debug-mode-response (input-type)
  260. ;; A debug session is an ongoing eval, but it's annoying to have the
  261. ;; spinner spinning while you debug.
  262. (when spinner-current (spinner-stop))
  263. (setq-local tool-bar-map cider--debug-mode-tool-bar-map)
  264. (add-hook 'kill-buffer-hook #'cider--debug-quit nil 'local)
  265. (add-hook 'before-revert-hook #'cider--debug-quit nil 'local)
  266. (unless (consp input-type)
  267. (error "Activated debug-mode on a message not asking for commands: %s" cider--debug-mode-response))
  268. ;; Integrate with eval commands.
  269. (setq cider-interactive-eval-override
  270. (apply-partially #'cider--debug-lexical-eval
  271. (nrepl-dict-get cider--debug-mode-response "key")))
  272. ;; Set the keymap.
  273. (nrepl-dict-map (lambda (char _cmd)
  274. (unless (string= char "h") ; `here' needs a special command.
  275. (define-key cider--debug-mode-map char #'cider-debug-mode-send-reply))
  276. (when (string= char "o")
  277. (define-key cider--debug-mode-map (upcase char) #'cider-debug-mode-send-reply)))
  278. input-type)
  279. (setq cider--debug-mode-commands-dict input-type)
  280. ;; Show the prompt.
  281. (cider--debug-mode-redisplay)
  282. ;; If a sync request is ongoing, the user can't act normally to
  283. ;; provide input, so we enter `recursive-edit'.
  284. (when nrepl-ongoing-sync-request
  285. (recursive-edit)))
  286. (cider--debug-mode -1)
  287. (if (called-interactively-p 'any)
  288. (user-error (substitute-command-keys "Don't call this mode manually, use `\\[universal-argument] \\[cider-eval-defun-at-point]' instead"))
  289. (error "Attempt to activate `cider--debug-mode' without setting `cider--debug-mode-response' first")))
  290. (setq cider-interactive-eval-override nil)
  291. (setq cider--debug-mode-commands-dict nil)
  292. (setq cider--debug-mode-response nil)
  293. ;; We wait a moment before clearing overlays and the read-onlyness, so that
  294. ;; cider-nrepl has a chance to send the next message, and so that the user
  295. ;; doesn't accidentally hit `n' between two messages (thus editing the code).
  296. (when-let* ((proc (unless nrepl-ongoing-sync-request
  297. (get-buffer-process (cider-current-repl)))))
  298. (accept-process-output proc 1))
  299. (unless cider--debug-mode
  300. (setq buffer-read-only nil)
  301. (cider--debug-remove-overlays (current-buffer)))
  302. (when nrepl-ongoing-sync-request
  303. (ignore-errors (exit-recursive-edit)))))
  304. ;;; Bind the `:here` command to both h and H, because it behaves differently if
  305. ;;; invoked with an uppercase letter.
  306. (define-key cider--debug-mode-map "h" #'cider-debug-move-here)
  307. (define-key cider--debug-mode-map "H" #'cider-debug-move-here)
  308. (defun cider--debug-remove-overlays (&optional buffer)
  309. "Remove CIDER debug overlays from BUFFER if variable `cider--debug-mode' is nil."
  310. (when (or (not buffer) (buffer-live-p buffer))
  311. (with-current-buffer (or buffer (current-buffer))
  312. (unless cider--debug-mode
  313. (kill-local-variable 'tool-bar-map)
  314. (remove-overlays nil nil 'category 'debug-result)
  315. (remove-overlays nil nil 'category 'debug-code)
  316. (setq cider--debug-prompt-overlay nil)
  317. (remove-overlays nil nil 'category 'debug-prompt)))))
  318. (defun cider--debug-set-prompt (value)
  319. "Set `cider-debug-prompt' to VALUE, then redisplay."
  320. (setq cider-debug-prompt value)
  321. (cider--debug-mode-redisplay))
  322. (easy-menu-define cider-debug-mode-menu cider--debug-mode-map
  323. "Menu for CIDER debug mode"
  324. `("CIDER Debugger"
  325. ["Next step" (cider-debug-mode-send-reply ":next") :keys "n"]
  326. ["Continue" (cider-debug-mode-send-reply ":continue") :keys "c"]
  327. ["Continue non-stop" (cider-debug-mode-send-reply ":Continue") :keys "C"]
  328. ["Move out of sexp" (cider-debug-mode-send-reply ":out") :keys "o"]
  329. ["Quit" (cider-debug-mode-send-reply ":quit") :keys "q"]
  330. "--"
  331. ["Evaluate in current scope" (cider-debug-mode-send-reply ":eval") :keys "e"]
  332. ["Inject value" (cider-debug-mode-send-reply ":inject") :keys "i"]
  333. ["Inspect value" (cider-debug-mode-send-reply ":inspect")]
  334. ["Inspect local variables" (cider-debug-mode-send-reply ":locals") :keys "l"]
  335. "--"
  336. ("Configure keys prompt"
  337. ["Don't show keys" (cider--debug-set-prompt nil) :style toggle :selected (eq cider-debug-prompt nil)]
  338. ["Show in minibuffer" (cider--debug-set-prompt 'minibuffer) :style toggle :selected (eq cider-debug-prompt 'minibuffer)]
  339. ["Show above function" (cider--debug-set-prompt 'overlay) :style toggle :selected (eq cider-debug-prompt 'overlay)]
  340. ["Show in both places" (cider--debug-set-prompt t) :style toggle :selected (eq cider-debug-prompt t)]
  341. "--"
  342. ["List locals" cider-debug-toggle-locals :style toggle :selected cider-debug-display-locals])
  343. ["Customize" (customize-group 'cider-debug)]))
  344. (defun cider--uppercase-command-p ()
  345. "Return non-nil if the last command was uppercase letter."
  346. (ignore-errors
  347. (let ((case-fold-search nil))
  348. (string-match "[[:upper:]]" (string last-command-event)))))
  349. (defun cider-debug-mode-send-reply (command &optional key force)
  350. "Reply to the message that started current bufer's debugging session.
  351. COMMAND is sent as the input option. KEY can be provided to reply to a
  352. specific message. If FORCE is non-nil, send a \"force?\" argument in the
  353. message."
  354. (interactive (list
  355. (if (symbolp last-command-event)
  356. (symbol-name last-command-event)
  357. (ignore-errors
  358. (concat ":" (nrepl-dict-get cider--debug-mode-commands-dict
  359. (string last-command-event)))))
  360. nil
  361. (cider--uppercase-command-p)))
  362. (when (and (string-prefix-p ":" command) force)
  363. (setq command (format "{:response %s :force? true}" command)))
  364. (cider-nrepl-send-unhandled-request
  365. `("op" "debug-input"
  366. "input" ,(or command ":quit")
  367. "key" ,(or key (nrepl-dict-get cider--debug-mode-response "key"))))
  368. (ignore-errors (cider--debug-mode -1)))
  369. (defun cider--debug-quit ()
  370. "Send a :quit reply to the debugger. Used in hooks."
  371. (when cider--debug-mode
  372. (cider-debug-mode-send-reply ":quit")
  373. (message "Quitting debug session")))
  374. ;;; Movement logic
  375. (defconst cider--debug-buffer-format "*cider-debug %s*")
  376. (defun cider--debug-trim-code (code)
  377. "Remove whitespace and reader macros from the start of the CODE.
  378. Return trimmed CODE."
  379. (replace-regexp-in-string "\\`#[a-z]+[\n\r[:blank:]]*" "" code))
  380. (declare-function cider-set-buffer-ns "cider-mode")
  381. (defun cider--initialize-debug-buffer (code ns id &optional reason)
  382. "Create a new debugging buffer with CODE and namespace NS.
  383. ID is the id of the message that instrumented CODE.
  384. REASON is a keyword describing why this buffer was necessary."
  385. (let ((buffer-name (format cider--debug-buffer-format id)))
  386. (if-let* ((buffer (get-buffer buffer-name)))
  387. (cider-popup-buffer-display buffer 'select)
  388. (with-current-buffer (cider-popup-buffer buffer-name 'select
  389. #'clojure-mode 'ancillary)
  390. (cider-set-buffer-ns ns)
  391. (setq buffer-undo-list nil)
  392. (let ((inhibit-read-only t)
  393. (buffer-undo-list t))
  394. (erase-buffer)
  395. (insert (format "%s" (cider--debug-trim-code code)))
  396. (when code
  397. (insert "\n\n\n;; We had to create this temporary buffer because we couldn't find the original definition. That probably happened because "
  398. reason
  399. ".")
  400. (fill-paragraph))
  401. (cider--font-lock-ensure)
  402. (set-buffer-modified-p nil))))
  403. (switch-to-buffer buffer-name)
  404. (goto-char (point-min))))
  405. (defun cider--debug-goto-keyval (key)
  406. "Find KEY in current sexp or return nil."
  407. (when-let* ((limit (ignore-errors (save-excursion (up-list) (point)))))
  408. (search-forward-regexp (concat "\\_<" (regexp-quote key) "\\_>")
  409. limit 'noerror)))
  410. (defun cider--debug-move-point (coordinates)
  411. "Place point on after the sexp specified by COORDINATES.
  412. COORDINATES is a list of integers that specify how to navigate into the
  413. sexp that is after point when this function is called.
  414. As an example, a COORDINATES list of '(1 0 2) means:
  415. - enter next sexp then `forward-sexp' once,
  416. - enter next sexp,
  417. - enter next sexp then `forward-sexp' twice.
  418. In the following snippet, this takes us to the (* x 2) sexp (point is left
  419. at the end of the given sexp).
  420. (letfn [(twice [x]
  421. (* x 2))]
  422. (twice 15))
  423. In addition to numbers, a coordinate can be a string. This string names the
  424. key of a map, and it means \"go to the value associated with this key\"."
  425. (condition-case-unless-debug nil
  426. ;; Navigate through sexps inside the sexp.
  427. (let ((in-syntax-quote nil))
  428. (while coordinates
  429. (while (clojure--looking-at-non-logical-sexp)
  430. (forward-sexp))
  431. ;; An `@x` is read as (deref x), so we pop coordinates once to account
  432. ;; for the extra depth, and move past the @ char.
  433. (if (eq ?@ (char-after))
  434. (progn (forward-char 1)
  435. (pop coordinates))
  436. (down-list)
  437. ;; Are we entering a syntax-quote?
  438. (when (looking-back "`\\(#{\\|[{[(]\\)" (line-beginning-position))
  439. ;; If we are, this affects all nested structures until the next `~',
  440. ;; so we set this variable for all following steps in the loop.
  441. (setq in-syntax-quote t))
  442. (when in-syntax-quote
  443. ;; A `(. .) is read as (seq (concat (list .) (list .))). This pops
  444. ;; the `seq', since the real coordinates are inside the `concat'.
  445. (pop coordinates)
  446. ;; Non-list seqs like `[] and `{} are read with
  447. ;; an extra (apply vector ...), so pop it too.
  448. (unless (eq ?\( (char-before))
  449. (pop coordinates)))
  450. ;; #(...) is read as (fn* ([] ...)), so we patch that here.
  451. (when (looking-back "#(" (line-beginning-position))
  452. (pop coordinates))
  453. (if coordinates
  454. (let ((next (pop coordinates)))
  455. (when in-syntax-quote
  456. ;; We're inside the `concat' form, but we need to discard the
  457. ;; actual `concat' symbol from the coordinate.
  458. (setq next (1- next)))
  459. ;; String coordinates are map keys.
  460. (if (stringp next)
  461. (cider--debug-goto-keyval next)
  462. (clojure-forward-logical-sexp next)
  463. (when in-syntax-quote
  464. (clojure-forward-logical-sexp 1)
  465. (forward-sexp -1)
  466. ;; Here a syntax-quote is ending.
  467. (let ((match (when (looking-at "~@?")
  468. (match-string 0))))
  469. (when match
  470. (setq in-syntax-quote nil))
  471. ;; A `~@' is read as the object itself, so we don't pop
  472. ;; anything.
  473. (unless (equal "~@" match)
  474. ;; Anything else (including a `~') is read as a `list'
  475. ;; form inside the `concat', so we need to pop the list
  476. ;; from the coordinates.
  477. (pop coordinates))))))
  478. ;; If that extra pop was the last coordinate, this represents the
  479. ;; entire #(...), so we should move back out.
  480. (backward-up-list))))
  481. ;; Place point at the end of instrumented sexp.
  482. (clojure-forward-logical-sexp 1))
  483. ;; Avoid throwing actual errors, since this happens on every breakpoint.
  484. (error (message "Can't find instrumented sexp, did you edit the source?"))))
  485. (defun cider--debug-position-for-code (code)
  486. "Return non-nil if point is roughly before CODE.
  487. This might move point one line above."
  488. (or (looking-at-p (regexp-quote code))
  489. (let ((trimmed (regexp-quote (cider--debug-trim-code code))))
  490. (or (looking-at-p trimmed)
  491. ;; If this is a fake #dbg injected by `C-u
  492. ;; C-M-x', then the sexp we want is actually on
  493. ;; the line above.
  494. (progn (forward-line -1)
  495. (looking-at-p trimmed))))))
  496. (defun cider--debug-find-source-position (response &optional create-if-needed)
  497. "Return a marker of the position after the sexp specified in RESPONSE.
  498. This marker might be in a different buffer! If the sexp can't be
  499. found (file that contains the code is no longer visited or has been
  500. edited), return nil. However, if CREATE-IF-NEEDED is non-nil, a new buffer
  501. is created in this situation and the return value is never nil.
  502. Follow the \"line\" and \"column\" entries in RESPONSE, and check whether
  503. the code at point matches the \"code\" entry in RESPONSE. If it doesn't,
  504. assume that the code in this file has been edited, and create a temp buffer
  505. holding the original code.
  506. Either way, navigate inside the code by following the \"coor\" entry which
  507. is a coordinate measure in sexps."
  508. (nrepl-dbind-response response (code file line column ns original-id coor)
  509. (when (or code (and file line column))
  510. ;; This is for restoring current-buffer.
  511. (save-excursion
  512. (let ((out))
  513. ;; We prefer in-source debugging.
  514. (when-let* ((buf (and file line column
  515. (ignore-errors
  516. (cider--find-buffer-for-file file)))))
  517. ;; The logic here makes it hard to use `with-current-buffer'.
  518. (with-current-buffer buf
  519. ;; This is for restoring point inside buf.
  520. (save-excursion
  521. ;; Get to the proper line & column in the file
  522. (forward-line (- line (line-number-at-pos)))
  523. (move-to-column column)
  524. ;; Check if it worked
  525. (when (cider--debug-position-for-code code)
  526. ;; Find the desired sexp.
  527. (cider--debug-move-point coor)
  528. (setq out (point-marker))))))
  529. ;; But we can create a temp buffer if that fails.
  530. (or out
  531. (when create-if-needed
  532. (cider--initialize-debug-buffer
  533. code ns original-id
  534. (if (and line column)
  535. "you edited the code"
  536. "your nREPL version is older than 0.2.11"))
  537. (save-excursion
  538. (cider--debug-move-point coor)
  539. (point-marker)))))))))
  540. (defun cider--handle-debug (response)
  541. "Handle debugging notification.
  542. RESPONSE is a message received from the nrepl describing the input
  543. needed. It is expected to contain at least \"key\", \"input-type\", and
  544. \"prompt\", and possibly other entries depending on the input-type."
  545. (nrepl-dbind-response response (debug-value key input-type prompt inspect)
  546. (condition-case-unless-debug e
  547. (progn
  548. (pcase input-type
  549. ("expression" (cider-debug-mode-send-reply
  550. (condition-case nil
  551. (cider-read-from-minibuffer
  552. (or prompt "Expression: "))
  553. (quit "nil"))
  554. key))
  555. ((pred sequencep)
  556. (let* ((marker (cider--debug-find-source-position response 'create-if-needed)))
  557. (pop-to-buffer (marker-buffer marker))
  558. (goto-char marker))
  559. ;; The overlay code relies on window boundaries, but point could have been
  560. ;; moved outside the window by some other code. Redisplay here to ensure the
  561. ;; visible window includes point.
  562. (redisplay)
  563. ;; Remove overlays AFTER redisplaying! Otherwise there's a visible
  564. ;; flicker even if we immediately recreate the overlays.
  565. (cider--debug-remove-overlays)
  566. (when cider-debug-use-overlays
  567. (cider--debug-display-result-overlay debug-value))
  568. (setq cider--debug-mode-response response)
  569. (cider--debug-mode 1)))
  570. (when inspect
  571. (setq cider-inspector--current-repl (cider-current-repl))
  572. (cider-inspector--render-value inspect)))
  573. ;; If something goes wrong, we send a "quit" or the session hangs.
  574. (error (cider-debug-mode-send-reply ":quit" key)
  575. (message "Error encountered while handling the debug message: %S" e)))))
  576. (defun cider--handle-enlighten (response)
  577. "Handle an enlighten notification.
  578. RESPONSE is a message received from the nrepl describing the value and
  579. coordinates of a sexp. Create an overlay after the specified sexp
  580. displaying its value."
  581. (when-let* ((marker (cider--debug-find-source-position response)))
  582. (with-current-buffer (marker-buffer marker)
  583. (save-excursion
  584. (goto-char marker)
  585. (clojure-backward-logical-sexp 1)
  586. (nrepl-dbind-response response (debug-value erase-previous)
  587. (when erase-previous
  588. (remove-overlays (point) marker 'category 'enlighten))
  589. (when debug-value
  590. (if (memq (char-before marker) '(?\) ?\] ?}))
  591. ;; Enlightening a sexp looks like a regular return value, except
  592. ;; for a different border.
  593. (cider--make-result-overlay (cider-font-lock-as-clojure debug-value)
  594. :where (cons marker marker)
  595. :type 'enlighten
  596. :prepend-face 'cider-enlightened-face)
  597. ;; Enlightening a symbol uses a more abbreviated format. The
  598. ;; result face is the same as a regular result, but we also color
  599. ;; the symbol with `cider-enlightened-local-face'.
  600. (cider--make-result-overlay (cider-font-lock-as-clojure debug-value)
  601. :format "%s"
  602. :where (cons (point) marker)
  603. :type 'enlighten
  604. 'face 'cider-enlightened-local-face))))))))
  605. ;;; Move here command
  606. ;; This is the inverse of `cider--debug-move-point'. However, that algorithm is
  607. ;; complicated, and trying to code its inverse would probably be insane.
  608. ;; Instead, we find the coordinate by trial and error.
  609. (defun cider--debug-find-coordinates-for-point (target &optional list-so-far)
  610. "Return the coordinates list for reaching TARGET.
  611. Assumes that the next thing after point is a logical Clojure sexp and that
  612. TARGET is inside it. The returned list is suitable for use in
  613. `cider--debug-move-point'. LIST-SO-FAR is for internal use."
  614. (when (looking-at (rx (or "(" "[" "#{" "{")))
  615. (let ((starting-point (point)))
  616. (unwind-protect
  617. (let ((x 0))
  618. ;; Keep incrementing the last coordinate until we've moved
  619. ;; past TARGET.
  620. (while (condition-case nil
  621. (progn (goto-char starting-point)
  622. (cider--debug-move-point (append list-so-far (list x)))
  623. (< (point) target))
  624. ;; Not a valid coordinate. Move back a step and stop here.
  625. (scan-error (setq x (1- x))
  626. nil))
  627. (setq x (1+ x)))
  628. (setq list-so-far (append list-so-far (list x)))
  629. ;; We have moved past TARGET, now determine whether we should
  630. ;; stop, or if target is deeper inside the previous sexp.
  631. (if (or (= target (point))
  632. (progn (forward-sexp -1)
  633. (<= target (point))))
  634. list-so-far
  635. (goto-char starting-point)
  636. (cider--debug-find-coordinates-for-point target list-so-far)))
  637. ;; `unwind-protect' clause.
  638. (goto-char starting-point)))))
  639. (defun cider-debug-move-here (&optional force)
  640. "Skip any breakpoints up to point.
  641. The boolean value of FORCE will be sent in the reply."
  642. (interactive (list (cider--uppercase-command-p)))
  643. (unless cider--debug-mode
  644. (user-error "`cider-debug-move-here' only makes sense during a debug session"))
  645. (let ((here (point)))
  646. (nrepl-dbind-response cider--debug-mode-response (line column)
  647. (if (and line column (buffer-file-name))
  648. (progn ;; Get to the proper line & column in the file
  649. (forward-line (1- (- line (line-number-at-pos))))
  650. (move-to-column column))
  651. (beginning-of-defun))
  652. ;; Is HERE inside the sexp being debugged?
  653. (when (or (< here (point))
  654. (save-excursion
  655. (forward-sexp 1)
  656. (> here (point))))
  657. (user-error "Point is outside the sexp being debugged"))
  658. ;; Move forward until start of sexp.
  659. (comment-normalize-vars)
  660. (comment-forward (point-max))
  661. ;; Find the coordinate and send it.
  662. (cider-debug-mode-send-reply
  663. (format "{:response :here, :coord %s :force? %s}"
  664. (cider--debug-find-coordinates-for-point here)
  665. (if force "true" "false"))))))
  666. ;;; User commands
  667. ;;;###autoload
  668. (defun cider-debug-defun-at-point ()
  669. "Instrument the \"top-level\" expression at point.
  670. If it is a defn, dispatch the instrumented definition. Otherwise,
  671. immediately evaluate the instrumented expression.
  672. While debugged code is being evaluated, the user is taken through the
  673. source code and displayed the value of various expressions. At each step,
  674. a number of keys will be prompted to the user."
  675. (interactive)
  676. (cider-eval-defun-at-point 'debug-it))
  677. (provide 'cider-debug)
  678. ;;; cider-debug.el ends here