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