debug.el 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. ;;; debug.el --- debuggers and related commands for Emacs -*- lexical-binding: t -*-
  2. ;; Copyright (C) 1985-1986, 1994, 2001-2017 Free Software Foundation,
  3. ;; Inc.
  4. ;; Maintainer: emacs-devel@gnu.org
  5. ;; Keywords: lisp, tools, maint
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; This is a major mode documented in the Emacs Lisp manual.
  19. ;;; Code:
  20. (require 'button)
  21. (defgroup debugger nil
  22. "Debuggers and related commands for Emacs."
  23. :prefix "debugger-"
  24. :group 'debug)
  25. (defcustom debugger-mode-hook nil
  26. "Hooks run when `debugger-mode' is turned on."
  27. :type 'hook
  28. :group 'debugger
  29. :version "20.3")
  30. (defcustom debugger-batch-max-lines 40
  31. "Maximum lines to show in debugger buffer in a noninteractive Emacs.
  32. When the debugger is entered and Emacs is running in batch mode,
  33. if the backtrace text has more than this many lines,
  34. the middle is discarded, and just the beginning and end are displayed."
  35. :type 'integer
  36. :group 'debugger
  37. :version "21.1")
  38. (defcustom debugger-print-function #'cl-prin1
  39. "Function used to print values in the debugger backtraces."
  40. :type 'function
  41. :options '(cl-prin1 prin1)
  42. :version "26.1")
  43. (defcustom debugger-bury-or-kill 'bury
  44. "What to do with the debugger buffer when exiting `debug'.
  45. The value affects the behavior of operations on any window
  46. previously showing the debugger buffer.
  47. nil means that if its window is not deleted when exiting the
  48. debugger, invoking `switch-to-prev-buffer' will usually show
  49. the debugger buffer again.
  50. `append' means that if the window is not deleted, the debugger
  51. buffer moves to the end of the window's previous buffers so
  52. it's less likely that a future invocation of
  53. `switch-to-prev-buffer' will switch to it. Also, it moves the
  54. buffer to the end of the frame's buffer list.
  55. `bury' means that if the window is not deleted, its buffer is
  56. removed from the window's list of previous buffers. Also, it
  57. moves the buffer to the end of the frame's buffer list. This
  58. value provides the most reliable remedy to not have
  59. `switch-to-prev-buffer' switch to the debugger buffer again
  60. without killing the buffer.
  61. `kill' means to kill the debugger buffer.
  62. The value used here is passed to `quit-restore-window'."
  63. :type '(choice
  64. (const :tag "Keep alive" nil)
  65. (const :tag "Append" append)
  66. (const :tag "Bury" bury)
  67. (const :tag "Kill" kill))
  68. :group 'debugger
  69. :version "24.3")
  70. (defvar debugger-step-after-exit nil
  71. "Non-nil means \"single-step\" after the debugger exits.")
  72. (defvar debugger-value nil
  73. "This is the value for the debugger to return, when it returns.")
  74. (defvar debugger-old-buffer nil
  75. "This is the buffer that was current when the debugger was entered.")
  76. (defvar debugger-previous-window nil
  77. "This is the window last showing the debugger buffer.")
  78. (defvar debugger-previous-window-height nil
  79. "The last recorded height of `debugger-previous-window'.")
  80. (defvar debugger-previous-backtrace nil
  81. "The contents of the previous backtrace (including text properties).
  82. This is to optimize `debugger-make-xrefs'.")
  83. (defvar debugger-outer-match-data)
  84. (defvar debugger-will-be-back nil
  85. "Non-nil if we expect to get back in the debugger soon.")
  86. (defvar inhibit-debug-on-entry nil
  87. "Non-nil means that `debug-on-entry' is disabled.")
  88. (defvar debugger-jumping-flag nil
  89. "Non-nil means that `debug-on-entry' is disabled.
  90. This variable is used by `debugger-jump', `debugger-step-through',
  91. and `debugger-reenable' to temporarily disable debug-on-entry.")
  92. (defvar inhibit-trace) ;Not yet implemented.
  93. (defvar debugger-args nil
  94. "Arguments with which the debugger was called.
  95. It is a list expected to take the form (CAUSE . REST)
  96. where CAUSE can be:
  97. - debug: called for entry to a flagged function.
  98. - t: called because of debug-on-next-call.
  99. - lambda: same thing but via `funcall'.
  100. - exit: called because of exit of a flagged function.
  101. - error: called because of `debug-on-error'.")
  102. ;;;###autoload
  103. (setq debugger 'debug)
  104. ;;;###autoload
  105. (defun debug (&rest args)
  106. "Enter debugger. \\<debugger-mode-map>`\\[debugger-continue]' returns from the debugger.
  107. Arguments are mainly for use when this is called from the internals
  108. of the evaluator.
  109. You may call with no args, or you may pass nil as the first arg and
  110. any other args you like. In that case, the list of args after the
  111. first will be printed into the backtrace buffer."
  112. (interactive)
  113. (if inhibit-redisplay
  114. ;; Don't really try to enter debugger within an eval from redisplay.
  115. debugger-value
  116. (unless noninteractive
  117. (message "Entering debugger..."))
  118. (let (debugger-value
  119. (debugger-previous-state
  120. (if (get-buffer "*Backtrace*")
  121. (with-current-buffer (get-buffer "*Backtrace*")
  122. (list major-mode (buffer-string)))))
  123. (debugger-args args)
  124. (debugger-buffer (get-buffer-create "*Backtrace*"))
  125. (debugger-old-buffer (current-buffer))
  126. (debugger-window nil)
  127. (debugger-step-after-exit nil)
  128. (debugger-will-be-back nil)
  129. ;; Don't keep reading from an executing kbd macro!
  130. (executing-kbd-macro nil)
  131. ;; Save the outer values of these vars for the `e' command
  132. ;; before we replace the values.
  133. (debugger-outer-match-data (match-data))
  134. (debugger-with-timeout-suspend (with-timeout-suspend)))
  135. ;; Set this instead of binding it, so that `q'
  136. ;; will not restore it.
  137. (setq overriding-terminal-local-map nil)
  138. ;; Don't let these magic variables affect the debugger itself.
  139. (let ((last-command nil) this-command track-mouse
  140. (inhibit-trace t)
  141. unread-command-events
  142. unread-post-input-method-events
  143. last-input-event last-command-event last-nonmenu-event
  144. last-event-frame
  145. overriding-local-map
  146. load-read-function
  147. ;; If we are inside a minibuffer, allow nesting
  148. ;; so that we don't get an error from the `e' command.
  149. (enable-recursive-minibuffers
  150. (or enable-recursive-minibuffers (> (minibuffer-depth) 0)))
  151. (standard-input t) (standard-output t)
  152. inhibit-redisplay
  153. (cursor-in-echo-area nil)
  154. (window-configuration (current-window-configuration)))
  155. (unwind-protect
  156. (save-excursion
  157. (when (eq (car debugger-args) 'debug)
  158. ;; Skip the frames for backtrace-debug, byte-code,
  159. ;; debug--implement-debug-on-entry and the advice's `apply'.
  160. (backtrace-debug 4 t)
  161. ;; Place an extra debug-on-exit for macro's.
  162. (when (eq 'lambda (car-safe (cadr (backtrace-frame 4))))
  163. (backtrace-debug 5 t)))
  164. (pop-to-buffer
  165. debugger-buffer
  166. `((display-buffer-reuse-window
  167. display-buffer-in-previous-window)
  168. . (,(when (and (window-live-p debugger-previous-window)
  169. (frame-visible-p
  170. (window-frame debugger-previous-window)))
  171. `(previous-window . ,debugger-previous-window)))))
  172. (setq debugger-window (selected-window))
  173. (if (eq debugger-previous-window debugger-window)
  174. (when debugger-jumping-flag
  175. ;; Try to restore previous height of debugger
  176. ;; window.
  177. (condition-case nil
  178. (window-resize
  179. debugger-window
  180. (- debugger-previous-window-height
  181. (window-total-height debugger-window)))
  182. (error nil)))
  183. (setq debugger-previous-window debugger-window))
  184. (debugger-mode)
  185. (debugger-setup-buffer debugger-args)
  186. (when noninteractive
  187. ;; If the backtrace is long, save the beginning
  188. ;; and the end, but discard the middle.
  189. (when (> (count-lines (point-min) (point-max))
  190. debugger-batch-max-lines)
  191. (goto-char (point-min))
  192. (forward-line (/ 2 debugger-batch-max-lines))
  193. (let ((middlestart (point)))
  194. (goto-char (point-max))
  195. (forward-line (- (/ 2 debugger-batch-max-lines)
  196. debugger-batch-max-lines))
  197. (delete-region middlestart (point)))
  198. (insert "...\n"))
  199. (goto-char (point-min))
  200. (message "%s" (buffer-string))
  201. (kill-emacs -1))
  202. (message "")
  203. (let ((standard-output nil)
  204. (buffer-read-only t))
  205. (message "")
  206. ;; Make sure we unbind buffer-read-only in the right buffer.
  207. (save-excursion
  208. (recursive-edit))))
  209. (when (and (window-live-p debugger-window)
  210. (eq (window-buffer debugger-window) debugger-buffer))
  211. ;; Record height of debugger window.
  212. (setq debugger-previous-window-height
  213. (window-total-height debugger-window)))
  214. (if debugger-will-be-back
  215. ;; Restore previous window configuration (Bug#12623).
  216. (set-window-configuration window-configuration)
  217. (when (and (window-live-p debugger-window)
  218. (eq (window-buffer debugger-window) debugger-buffer))
  219. (progn
  220. ;; Unshow debugger-buffer.
  221. (quit-restore-window debugger-window debugger-bury-or-kill)
  222. ;; Restore current buffer (Bug#12502).
  223. (set-buffer debugger-old-buffer))))
  224. ;; Restore previous state of debugger-buffer in case we were
  225. ;; in a recursive invocation of the debugger, otherwise just
  226. ;; erase the buffer and put it into fundamental mode.
  227. (when (buffer-live-p debugger-buffer)
  228. (with-current-buffer debugger-buffer
  229. (let ((inhibit-read-only t))
  230. (erase-buffer)
  231. (if (null debugger-previous-state)
  232. (fundamental-mode)
  233. (insert (nth 1 debugger-previous-state))
  234. (funcall (nth 0 debugger-previous-state))))))
  235. (with-timeout-unsuspend debugger-with-timeout-suspend)
  236. (set-match-data debugger-outer-match-data)))
  237. (setq debug-on-next-call debugger-step-after-exit)
  238. debugger-value)))
  239. (defun debugger-insert-backtrace (frames do-xrefs)
  240. "Format and insert the backtrace FRAMES at point.
  241. Make functions into cross-reference buttons if DO-XREFS is non-nil."
  242. (let ((standard-output (current-buffer))
  243. (eval-buffers eval-buffer-list))
  244. (require 'help-mode) ; Define `help-function-def' button type.
  245. (pcase-dolist (`(,evald ,fun ,args ,flags) frames)
  246. (insert (if (plist-get flags :debug-on-exit)
  247. "* " " "))
  248. (let ((fun-file (and do-xrefs (symbol-file fun 'defun)))
  249. (fun-pt (point)))
  250. (cond
  251. ((and evald (not debugger-stack-frame-as-list))
  252. (funcall debugger-print-function fun)
  253. (if args (funcall debugger-print-function args) (princ "()")))
  254. (t
  255. (funcall debugger-print-function (cons fun args))
  256. (cl-incf fun-pt)))
  257. (when fun-file
  258. (make-text-button fun-pt (+ fun-pt (length (symbol-name fun)))
  259. :type 'help-function-def
  260. 'help-args (list fun fun-file))))
  261. ;; After any frame that uses eval-buffer, insert a line that
  262. ;; states the buffer position it's reading at.
  263. (when (and eval-buffers (memq fun '(eval-buffer eval-region)))
  264. (insert (format " ; Reading at buffer position %d"
  265. ;; This will get the wrong result if there are
  266. ;; two nested eval-region calls for the same
  267. ;; buffer. That's not a very useful case.
  268. (with-current-buffer (pop eval-buffers)
  269. (point)))))
  270. (insert "\n"))))
  271. (defun debugger-setup-buffer (args)
  272. "Initialize the `*Backtrace*' buffer for entry to the debugger.
  273. That buffer should be current already."
  274. (setq buffer-read-only nil)
  275. (erase-buffer)
  276. (set-buffer-multibyte t) ;Why was it nil ? -stef
  277. (setq buffer-undo-list t)
  278. (insert "Debugger entered")
  279. (let ((frames (nthcdr
  280. ;; Remove debug--implement-debug-on-entry and the
  281. ;; advice's `apply' frame.
  282. (if (eq (car args) 'debug) 3 1)
  283. (backtrace-frames 'debug)))
  284. (print-escape-newlines t)
  285. (print-escape-control-characters t)
  286. (print-level 8)
  287. (print-length 50)
  288. (pos (point)))
  289. (pcase (car args)
  290. ;; lambda is for debug-on-call when a function call is next.
  291. ;; debug is for debug-on-entry function called.
  292. ((or `lambda `debug)
  293. (insert "--entering a function:\n")
  294. (setq pos (1- (point))))
  295. ;; Exiting a function.
  296. (`exit
  297. (insert "--returning value: ")
  298. (setq pos (point))
  299. (setq debugger-value (nth 1 args))
  300. (funcall debugger-print-function debugger-value (current-buffer))
  301. (setf (cl-getf (nth 3 (car frames)) :debug-on-exit) nil)
  302. (insert ?\n))
  303. ;; Watchpoint triggered.
  304. ((and `watchpoint (let `(,symbol ,newval . ,details) (cdr args)))
  305. (insert
  306. "--"
  307. (pcase details
  308. (`(makunbound nil) (format "making %s void" symbol))
  309. (`(makunbound ,buffer) (format "killing local value of %s in buffer %s"
  310. symbol buffer))
  311. (`(defvaralias ,_) (format "aliasing %s to %s" symbol newval))
  312. (`(let ,_) (format "let-binding %s to %S" symbol newval))
  313. (`(unlet ,_) (format "ending let-binding of %s" symbol))
  314. (`(set nil) (format "setting %s to %S" symbol newval))
  315. (`(set ,buffer) (format "setting %s in buffer %s to %S"
  316. symbol buffer newval))
  317. (_ (error "unrecognized watchpoint triggered %S" (cdr args))))
  318. ": ")
  319. (setq pos (point))
  320. (insert ?\n))
  321. ;; Debugger entered for an error.
  322. (`error
  323. (insert "--Lisp error: ")
  324. (setq pos (point))
  325. (funcall debugger-print-function (nth 1 args) (current-buffer))
  326. (insert ?\n))
  327. ;; debug-on-call, when the next thing is an eval.
  328. (`t
  329. (insert "--beginning evaluation of function call form:\n")
  330. (setq pos (1- (point))))
  331. ;; User calls debug directly.
  332. (_
  333. (insert ": ")
  334. (setq pos (point))
  335. (funcall debugger-print-function
  336. (if (eq (car args) 'nil)
  337. (cdr args) args)
  338. (current-buffer))
  339. (insert ?\n)))
  340. (debugger-insert-backtrace frames t)
  341. ;; Place point on "stack frame 0" (bug#15101).
  342. (goto-char pos)))
  343. (defun debugger-step-through ()
  344. "Proceed, stepping through subexpressions of this expression.
  345. Enter another debugger on next entry to eval, apply or funcall."
  346. (interactive)
  347. (setq debugger-step-after-exit t)
  348. (setq debugger-jumping-flag t)
  349. (setq debugger-will-be-back t)
  350. (add-hook 'post-command-hook 'debugger-reenable)
  351. (message "Proceeding, will debug on next eval or call.")
  352. (exit-recursive-edit))
  353. (defun debugger-continue ()
  354. "Continue, evaluating this expression without stopping."
  355. (interactive)
  356. (unless debugger-may-continue
  357. (error "Cannot continue"))
  358. (message "Continuing.")
  359. (save-excursion
  360. ;; Check to see if we've flagged some frame for debug-on-exit, in which
  361. ;; case we'll probably come back to the debugger soon.
  362. (goto-char (point-min))
  363. (if (re-search-forward "^\\* " nil t)
  364. (setq debugger-will-be-back t)))
  365. (exit-recursive-edit))
  366. (defun debugger-return-value (val)
  367. "Continue, specifying value to return.
  368. This is only useful when the value returned from the debugger
  369. will be used, such as in a debug on exit from a frame."
  370. (interactive "XReturn value (evaluated): ")
  371. (when (memq (car debugger-args) '(t lambda error debug))
  372. (error "Cannot return a value %s"
  373. (if (eq (car debugger-args) 'error)
  374. "from an error" "at function entrance")))
  375. (setq debugger-value val)
  376. (princ "Returning " t)
  377. (prin1 debugger-value)
  378. (save-excursion
  379. ;; Check to see if we've flagged some frame for debug-on-exit, in which
  380. ;; case we'll probably come back to the debugger soon.
  381. (goto-char (point-min))
  382. (if (re-search-forward "^\\* " nil t)
  383. (setq debugger-will-be-back t)))
  384. (exit-recursive-edit))
  385. (defun debugger-jump ()
  386. "Continue to exit from this frame, with all debug-on-entry suspended."
  387. (interactive)
  388. (debugger-frame)
  389. (setq debugger-jumping-flag t)
  390. (add-hook 'post-command-hook 'debugger-reenable)
  391. (message "Continuing through this frame")
  392. (setq debugger-will-be-back t)
  393. (exit-recursive-edit))
  394. (defun debugger-reenable ()
  395. "Turn all debug-on-entry functions back on.
  396. This function is put on `post-command-hook' by `debugger-jump' and
  397. removes itself from that hook."
  398. (setq debugger-jumping-flag nil)
  399. (remove-hook 'post-command-hook 'debugger-reenable))
  400. (defun debugger-frame-number (&optional skip-base)
  401. "Return number of frames in backtrace before the one point points at."
  402. (save-excursion
  403. (beginning-of-line)
  404. (if (looking-at " *;;;\\|[a-z]")
  405. (error "This line is not a function call"))
  406. (let ((opoint (point))
  407. (count 0))
  408. (unless skip-base
  409. (while (not (eq (cadr (backtrace-frame count)) 'debug))
  410. (setq count (1+ count)))
  411. ;; Skip debug--implement-debug-on-entry frame.
  412. (when (eq 'debug--implement-debug-on-entry
  413. (cadr (backtrace-frame (1+ count))))
  414. (setq count (+ 2 count))))
  415. (goto-char (point-min))
  416. (when (looking-at "Debugger entered--\\(Lisp error\\|returning value\\):")
  417. (goto-char (match-end 0))
  418. (forward-sexp 1))
  419. (forward-line 1)
  420. (while (progn
  421. (forward-char 2)
  422. (cond ((debugger--locals-visible-p)
  423. (goto-char (next-single-char-property-change
  424. (point) 'locals-visible)))
  425. ((= (following-char) ?\()
  426. (forward-sexp 1))
  427. (t
  428. (forward-sexp 2)))
  429. (forward-line 1)
  430. (<= (point) opoint))
  431. (if (looking-at " *;;;")
  432. (forward-line 1))
  433. (setq count (1+ count)))
  434. count)))
  435. (defun debugger-frame ()
  436. "Request entry to debugger when this frame exits.
  437. Applies to the frame whose line point is on in the backtrace."
  438. (interactive)
  439. (backtrace-debug (debugger-frame-number) t)
  440. (beginning-of-line)
  441. (if (= (following-char) ? )
  442. (let ((inhibit-read-only t))
  443. (delete-char 1)
  444. (insert ?*)))
  445. (beginning-of-line))
  446. (defun debugger-frame-clear ()
  447. "Do not enter debugger when this frame exits.
  448. Applies to the frame whose line point is on in the backtrace."
  449. (interactive)
  450. (backtrace-debug (debugger-frame-number) nil)
  451. (beginning-of-line)
  452. (if (= (following-char) ?*)
  453. (let ((inhibit-read-only t))
  454. (delete-char 1)
  455. (insert ? )))
  456. (beginning-of-line))
  457. (defmacro debugger-env-macro (&rest body)
  458. "Run BODY in original environment."
  459. (declare (indent 0))
  460. `(progn
  461. (set-match-data debugger-outer-match-data)
  462. (prog1
  463. (progn ,@body)
  464. (setq debugger-outer-match-data (match-data)))))
  465. (defun debugger--backtrace-base ()
  466. "Return the function name that marks the top of the backtrace.
  467. See `backtrace-frame'."
  468. (cond ((eq 'debug--implement-debug-on-entry
  469. (cadr (backtrace-frame 1 'debug)))
  470. 'debug--implement-debug-on-entry)
  471. (t 'debug)))
  472. (defun debugger-eval-expression (exp &optional nframe)
  473. "Eval an expression, in an environment like that outside the debugger.
  474. The environment used is the one when entering the activation frame at point."
  475. (interactive
  476. (list (read--expression "Eval in stack frame: ")))
  477. (let ((nframe (or nframe
  478. (condition-case nil (1+ (debugger-frame-number 'skip-base))
  479. (error 0)))) ;; If on first line.
  480. (base (debugger--backtrace-base)))
  481. (debugger-env-macro
  482. (let ((val (backtrace-eval exp nframe base)))
  483. (prog1
  484. (prin1 val t)
  485. (let ((str (eval-expression-print-format val)))
  486. (if str (princ str t))))))))
  487. (defun debugger--locals-visible-p ()
  488. "Are the local variables of the current stack frame visible?"
  489. (save-excursion
  490. (move-to-column 2)
  491. (get-text-property (point) 'locals-visible)))
  492. (defun debugger--insert-locals (locals)
  493. "Insert the local variables LOCALS at point."
  494. (cond ((null locals)
  495. (insert "\n [no locals]"))
  496. (t
  497. (let ((print-escape-newlines t))
  498. (dolist (s+v locals)
  499. (let ((symbol (car s+v))
  500. (value (cdr s+v)))
  501. (insert "\n ")
  502. (prin1 symbol (current-buffer))
  503. (insert " = ")
  504. (prin1 value (current-buffer))))))))
  505. (defun debugger--show-locals ()
  506. "For the frame at point, insert locals and add text properties."
  507. (let* ((nframe (1+ (debugger-frame-number 'skip-base)))
  508. (base (debugger--backtrace-base))
  509. (locals (backtrace--locals nframe base))
  510. (inhibit-read-only t))
  511. (save-excursion
  512. (let ((start (progn
  513. (move-to-column 2)
  514. (point))))
  515. (end-of-line)
  516. (debugger--insert-locals locals)
  517. (add-text-properties start (point) '(locals-visible t))))))
  518. (defun debugger--hide-locals ()
  519. "Delete local variables and remove the text property."
  520. (let* ((col (current-column))
  521. (end (progn
  522. (move-to-column 2)
  523. (next-single-char-property-change (point) 'locals-visible)))
  524. (start (previous-single-char-property-change end 'locals-visible))
  525. (inhibit-read-only t))
  526. (remove-text-properties start end '(locals-visible))
  527. (goto-char start)
  528. (end-of-line)
  529. (delete-region (point) end)
  530. (move-to-column col)))
  531. (defun debugger-toggle-locals ()
  532. "Show or hide local variables of the current stack frame."
  533. (interactive)
  534. (cond ((debugger--locals-visible-p)
  535. (debugger--hide-locals))
  536. (t
  537. (debugger--show-locals))))
  538. (defvar debugger-mode-map
  539. (let ((map (make-keymap))
  540. (menu-map (make-sparse-keymap)))
  541. (set-keymap-parent map button-buffer-map)
  542. (suppress-keymap map)
  543. (define-key map "-" 'negative-argument)
  544. (define-key map "b" 'debugger-frame)
  545. (define-key map "c" 'debugger-continue)
  546. (define-key map "j" 'debugger-jump)
  547. (define-key map "r" 'debugger-return-value)
  548. (define-key map "u" 'debugger-frame-clear)
  549. (define-key map "d" 'debugger-step-through)
  550. (define-key map "l" 'debugger-list-functions)
  551. (define-key map "h" 'describe-mode)
  552. (define-key map "q" 'top-level)
  553. (define-key map "e" 'debugger-eval-expression)
  554. (define-key map "v" 'debugger-toggle-locals) ; "v" is for "variables".
  555. (define-key map " " 'next-line)
  556. (define-key map "R" 'debugger-record-expression)
  557. (define-key map "\C-m" 'debug-help-follow)
  558. (define-key map [mouse-2] 'push-button)
  559. (define-key map [menu-bar debugger] (cons "Debugger" menu-map))
  560. (define-key menu-map [deb-top]
  561. '(menu-item "Quit" top-level
  562. :help "Quit debugging and return to top level"))
  563. (define-key menu-map [deb-s0] '("--"))
  564. (define-key menu-map [deb-descr]
  565. '(menu-item "Describe Debugger Mode" describe-mode
  566. :help "Display documentation for debugger-mode"))
  567. (define-key menu-map [deb-hfol]
  568. '(menu-item "Help Follow" debug-help-follow
  569. :help "Follow cross-reference"))
  570. (define-key menu-map [deb-nxt]
  571. '(menu-item "Next Line" next-line
  572. :help "Move cursor down"))
  573. (define-key menu-map [deb-s1] '("--"))
  574. (define-key menu-map [deb-lfunc]
  575. '(menu-item "List debug on entry functions" debugger-list-functions
  576. :help "Display a list of all the functions now set to debug on entry"))
  577. (define-key menu-map [deb-fclear]
  578. '(menu-item "Cancel debug frame" debugger-frame-clear
  579. :help "Do not enter debugger when this frame exits"))
  580. (define-key menu-map [deb-frame]
  581. '(menu-item "Debug frame" debugger-frame
  582. :help "Request entry to debugger when this frame exits"))
  583. (define-key menu-map [deb-s2] '("--"))
  584. (define-key menu-map [deb-ret]
  585. '(menu-item "Return value..." debugger-return-value
  586. :help "Continue, specifying value to return."))
  587. (define-key menu-map [deb-rec]
  588. '(menu-item "Display and Record Expression" debugger-record-expression
  589. :help "Display a variable's value and record it in `*Backtrace-record*' buffer"))
  590. (define-key menu-map [deb-eval]
  591. '(menu-item "Eval Expression..." debugger-eval-expression
  592. :help "Eval an expression, in an environment like that outside the debugger"))
  593. (define-key menu-map [deb-jump]
  594. '(menu-item "Jump" debugger-jump
  595. :help "Continue to exit from this frame, with all debug-on-entry suspended"))
  596. (define-key menu-map [deb-cont]
  597. '(menu-item "Continue" debugger-continue
  598. :help "Continue, evaluating this expression without stopping"))
  599. (define-key menu-map [deb-step]
  600. '(menu-item "Step through" debugger-step-through
  601. :help "Proceed, stepping through subexpressions of this expression"))
  602. map))
  603. (put 'debugger-mode 'mode-class 'special)
  604. (define-derived-mode debugger-mode fundamental-mode "Debugger"
  605. "Mode for backtrace buffers, selected in debugger.
  606. \\<debugger-mode-map>
  607. A line starts with `*' if exiting that frame will call the debugger.
  608. Type \\[debugger-frame] or \\[debugger-frame-clear] to set or remove the `*'.
  609. When in debugger due to frame being exited,
  610. use the \\[debugger-return-value] command to override the value
  611. being returned from that frame.
  612. Use \\[debug-on-entry] and \\[cancel-debug-on-entry] to control
  613. which functions will enter the debugger when called.
  614. Complete list of commands:
  615. \\{debugger-mode-map}"
  616. (setq truncate-lines t)
  617. (set-syntax-table emacs-lisp-mode-syntax-table)
  618. (add-hook 'kill-buffer-hook
  619. (lambda () (if (> (recursion-depth) 0) (top-level)))
  620. nil t)
  621. (use-local-map debugger-mode-map))
  622. (defcustom debugger-record-buffer "*Debugger-record*"
  623. "Buffer name for expression values, for \\[debugger-record-expression]."
  624. :type 'string
  625. :group 'debugger
  626. :version "20.3")
  627. (defun debugger-record-expression (exp)
  628. "Display a variable's value and record it in `*Backtrace-record*' buffer."
  629. (interactive
  630. (list (read--expression "Record Eval: ")))
  631. (let* ((buffer (get-buffer-create debugger-record-buffer))
  632. (standard-output buffer))
  633. (princ (format "Debugger Eval (%s): " exp))
  634. (princ (debugger-eval-expression exp))
  635. (terpri))
  636. (with-current-buffer (get-buffer debugger-record-buffer)
  637. (message "%s"
  638. (buffer-substring (line-beginning-position 0)
  639. (line-end-position 0)))))
  640. (defun debug-help-follow (&optional pos)
  641. "Follow cross-reference at POS, defaulting to point.
  642. For the cross-reference format, see `help-make-xrefs'."
  643. (interactive "d")
  644. ;; Ideally we'd just do (call-interactively 'help-follow) except that this
  645. ;; assumes we're already in a *Help* buffer and reuses it, so it ends up
  646. ;; incorrectly "reusing" the *Backtrace* buffer to show the help info.
  647. (unless pos
  648. (setq pos (point)))
  649. (unless (push-button pos)
  650. ;; check if the symbol under point is a function or variable
  651. (let ((sym
  652. (intern
  653. (save-excursion
  654. (goto-char pos) (skip-syntax-backward "w_")
  655. (buffer-substring (point)
  656. (progn (skip-syntax-forward "w_")
  657. (point)))))))
  658. (when (or (boundp sym) (fboundp sym) (facep sym))
  659. (describe-symbol sym)))))
  660. ;; When you change this, you may also need to change the number of
  661. ;; frames that the debugger skips.
  662. (defun debug--implement-debug-on-entry (&rest _ignore)
  663. "Conditionally call the debugger.
  664. A call to this function is inserted by `debug-on-entry' to cause
  665. functions to break on entry."
  666. (if (or inhibit-debug-on-entry debugger-jumping-flag)
  667. nil
  668. (let ((inhibit-debug-on-entry t))
  669. (funcall debugger 'debug))))
  670. ;;;###autoload
  671. (defun debug-on-entry (function)
  672. "Request FUNCTION to invoke debugger each time it is called.
  673. When called interactively, prompt for FUNCTION in the minibuffer.
  674. This works by modifying the definition of FUNCTION. If you tell the
  675. debugger to continue, FUNCTION's execution proceeds. If FUNCTION is a
  676. normal function or a macro written in Lisp, you can also step through
  677. its execution. FUNCTION can also be a primitive that is not a special
  678. form, in which case stepping is not possible. Break-on-entry for
  679. primitive functions only works when that function is called from Lisp.
  680. Use \\[cancel-debug-on-entry] to cancel the effect of this command.
  681. Redefining FUNCTION also cancels it."
  682. (interactive
  683. (let ((fn (function-called-at-point)) val)
  684. (when (special-form-p fn)
  685. (setq fn nil))
  686. (setq val (completing-read
  687. (if fn
  688. (format "Debug on entry to function (default %s): " fn)
  689. "Debug on entry to function: ")
  690. obarray
  691. #'(lambda (symbol)
  692. (and (fboundp symbol)
  693. (not (special-form-p symbol))))
  694. t nil nil (symbol-name fn)))
  695. (list (if (equal val "") fn (intern val)))))
  696. (advice-add function :before #'debug--implement-debug-on-entry
  697. '((depth . -100)))
  698. function)
  699. (defun debug--function-list ()
  700. "List of functions currently set for debug on entry."
  701. (let ((funs '()))
  702. (mapatoms
  703. (lambda (s)
  704. (when (advice-member-p #'debug--implement-debug-on-entry s)
  705. (push s funs))))
  706. funs))
  707. ;;;###autoload
  708. (defun cancel-debug-on-entry (&optional function)
  709. "Undo effect of \\[debug-on-entry] on FUNCTION.
  710. If FUNCTION is nil, cancel debug-on-entry for all functions.
  711. When called interactively, prompt for FUNCTION in the minibuffer.
  712. To specify a nil argument interactively, exit with an empty minibuffer."
  713. (interactive
  714. (list (let ((name
  715. (completing-read
  716. "Cancel debug on entry to function (default all functions): "
  717. (mapcar #'symbol-name (debug--function-list)) nil t)))
  718. (when name
  719. (unless (string= name "")
  720. (intern name))))))
  721. (if function
  722. (progn
  723. (advice-remove function #'debug--implement-debug-on-entry)
  724. function)
  725. (message "Canceling debug-on-entry for all functions")
  726. (mapcar #'cancel-debug-on-entry (debug--function-list))))
  727. (defun debugger-list-functions ()
  728. "Display a list of all the functions now set to debug on entry."
  729. (interactive)
  730. (require 'help-mode)
  731. (help-setup-xref '(debugger-list-functions)
  732. (called-interactively-p 'interactive))
  733. (with-output-to-temp-buffer (help-buffer)
  734. (with-current-buffer standard-output
  735. (let ((funs (debug--function-list)))
  736. (if (null funs)
  737. (princ "No debug-on-entry functions now\n")
  738. (princ "Functions set to debug on entry:\n\n")
  739. (dolist (fun funs)
  740. (make-text-button (point) (progn (prin1 fun) (point))
  741. 'type 'help-function
  742. 'help-args (list fun))
  743. (terpri))
  744. ;; Now that debug--function-list uses advice-member-p, its
  745. ;; output should be reliable (except for bugs and the exceptional
  746. ;; case where some other advice ends up overriding ours).
  747. ;;(terpri)
  748. ;;(princ "Note: if you have redefined a function, then it may no longer\n")
  749. ;;(princ "be set to debug on entry, even if it is in the list.")
  750. )))))
  751. (defun debug--implement-debug-watch (symbol newval op where)
  752. "Conditionally call the debugger.
  753. This function is called when SYMBOL's value is modified."
  754. (if (or inhibit-debug-on-entry debugger-jumping-flag)
  755. nil
  756. (let ((inhibit-debug-on-entry t))
  757. (funcall debugger 'watchpoint symbol newval op where))))
  758. ;;;###autoload
  759. (defun debug-on-variable-change (variable)
  760. "Trigger a debugger invocation when VARIABLE is changed.
  761. When called interactively, prompt for VARIABLE in the minibuffer.
  762. This works by calling `add-variable-watch' on VARIABLE. If you
  763. quit from the debugger, this will abort the change (unless the
  764. change is caused by the termination of a let-binding).
  765. The watchpoint may be circumvented by C code that changes the
  766. variable directly (i.e., not via `set'). Changing the value of
  767. the variable (e.g., `setcar' on a list variable) will not trigger
  768. watchpoint.
  769. Use \\[cancel-debug-on-variable-change] to cancel the effect of
  770. this command. Uninterning VARIABLE or making it an alias of
  771. another symbol also cancels it."
  772. (interactive
  773. (let* ((var-at-point (variable-at-point))
  774. (var (and (symbolp var-at-point) var-at-point))
  775. (val (completing-read
  776. (concat "Debug when setting variable"
  777. (if var (format " (default %s): " var) ": "))
  778. obarray #'boundp
  779. t nil nil (and var (symbol-name var)))))
  780. (list (if (equal val "") var (intern val)))))
  781. (add-variable-watcher variable #'debug--implement-debug-watch))
  782. ;;;###autoload
  783. (defalias 'debug-watch #'debug-on-variable-change)
  784. (defun debug--variable-list ()
  785. "List of variables currently set for debug on set."
  786. (let ((vars '()))
  787. (mapatoms
  788. (lambda (s)
  789. (when (memq #'debug--implement-debug-watch
  790. (get s 'watchers))
  791. (push s vars))))
  792. vars))
  793. ;;;###autoload
  794. (defun cancel-debug-on-variable-change (&optional variable)
  795. "Undo effect of \\[debug-on-variable-change] on VARIABLE.
  796. If VARIABLE is nil, cancel debug-on-variable-change for all variables.
  797. When called interactively, prompt for VARIABLE in the minibuffer.
  798. To specify a nil argument interactively, exit with an empty minibuffer."
  799. (interactive
  800. (list (let ((name
  801. (completing-read
  802. "Cancel debug on set for variable (default all variables): "
  803. (mapcar #'symbol-name (debug--variable-list)) nil t)))
  804. (when name
  805. (unless (string= name "")
  806. (intern name))))))
  807. (if variable
  808. (remove-variable-watcher variable #'debug--implement-debug-watch)
  809. (message "Canceling debug-watch for all variables")
  810. (mapc #'cancel-debug-watch (debug--variable-list))))
  811. ;;;###autoload
  812. (defalias 'cancel-debug-watch #'cancel-debug-on-variable-change)
  813. (provide 'debug)
  814. ;;; debug.el ends here