* lisp/emacs-lisp/smie.el (smie-next-sexp): Fix up "other-end" info when
[bpt/emacs.git] / lisp / emacs-lisp / debug.el
CommitLineData
231d8498 1;;; debug.el --- debuggers and related commands for Emacs -*- lexical-binding: t -*-
c0274f38 2
ba318903 3;; Copyright (C) 1985-1986, 1994, 2001-2014 Free Software Foundation,
ab422c4d 4;; Inc.
9750e079 5
34dc21db 6;; Maintainer: emacs-devel@gnu.org
e9571d2a 7;; Keywords: lisp, tools, maint
e5167999 8
0231f2dc
JB
9;; This file is part of GNU Emacs.
10
d6cba7ae 11;; GNU Emacs is free software: you can redistribute it and/or modify
0231f2dc 12;; it under the terms of the GNU General Public License as published by
d6cba7ae
GM
13;; the Free Software Foundation, either version 3 of the License, or
14;; (at your option) any later version.
0231f2dc
JB
15
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.
20
21;; You should have received a copy of the GNU General Public License
d6cba7ae 22;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
0231f2dc 23
e41b2db1
ER
24;;; Commentary:
25
07f3fdb1 26;; This is a major mode documented in the Emacs Lisp manual.
e41b2db1 27
e5167999 28;;; Code:
0231f2dc 29
bb9a622e
MB
30(require 'button)
31
666b9413
SE
32(defgroup debugger nil
33 "Debuggers and related commands for Emacs."
34 :prefix "debugger-"
35 :group 'debug)
8c1cd093 36
666b9413 37(defcustom debugger-mode-hook nil
cb711556 38 "Hooks run when `debugger-mode' is turned on."
666b9413 39 :type 'hook
cd32a7ba
DN
40 :group 'debugger
41 :version "20.3")
8c1cd093 42
63ca439e 43(defcustom debugger-batch-max-lines 40
cb711556 44 "Maximum lines to show in debugger buffer in a noninteractive Emacs.
63ca439e
GM
45When the debugger is entered and Emacs is running in batch mode,
46if the backtrace text has more than this many lines,
47the middle is discarded, and just the beginning and end are displayed."
48 :type 'integer
49 :group 'debugger
50 :version "21.1")
0231f2dc 51
fa2bcf43 52(defcustom debugger-bury-or-kill 'bury
57fc0fee
GM
53 "What to do with the debugger buffer when exiting `debug'.
54The value affects the behavior of operations on any window
55previously showing the debugger buffer.
fa2bcf43
MR
56
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.
60
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.
66
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.
73
74`kill' means to kill the debugger buffer.
75
76The value used here is passed to `quit-restore-window'."
77 :type '(choice
78 (const :tag "Keep alive" nil)
37ab5092
MR
79 (const :tag "Append" append)
80 (const :tag "Bury" bury)
81 (const :tag "Kill" kill))
fa2bcf43 82 :group 'debugger
68146aa5 83 :version "24.3")
fa2bcf43 84
15cf150d
LK
85(defvar debugger-step-after-exit nil
86 "Non-nil means \"single-step\" after the debugger exits.")
2eeeb0d2
RS
87
88(defvar debugger-value nil
89 "This is the value for the debugger to return, when it returns.")
90
91(defvar debugger-old-buffer nil
92 "This is the buffer that was current when the debugger was entered.")
93
fa2bcf43
MR
94(defvar debugger-previous-window nil
95 "This is the window last showing the debugger buffer.")
96
4dece104
MR
97(defvar debugger-previous-window-height nil
98 "The last recorded height of `debugger-previous-window'.")
99
25c58854
RS
100(defvar debugger-previous-backtrace nil
101 "The contents of the previous backtrace (including text properties).
102This is to optimize `debugger-make-xrefs'.")
103
cf1c8cd9 104(defvar debugger-outer-match-data)
9b530428
SM
105(defvar debugger-will-be-back nil
106 "Non-nil if we expect to get back in the debugger soon.")
35cf010d 107
b6b77a90
LK
108(defvar inhibit-debug-on-entry nil
109 "Non-nil means that debug-on-entry is disabled.")
110
111(defvar debugger-jumping-flag nil
112 "Non-nil means that debug-on-entry is disabled.
9b54d453
LK
113This variable is used by `debugger-jump', `debugger-step-through',
114and `debugger-reenable' to temporarily disable debug-on-entry.")
cf9a1b69 115
d48f0f00 116(defvar inhibit-trace) ;Not yet implemented.
77932668 117
e24e27be
SM
118(defvar debugger-args nil
119 "Arguments with which the debugger was called.
120It is a list expected to take the form (CAUSE . REST)
121where 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'.")
127
0231f2dc
JB
128;;;###autoload
129(setq debugger 'debug)
130;;;###autoload
231d8498 131(defun debug (&rest args)
a7c33da2 132 "Enter debugger. \\<debugger-mode-map>`\\[debugger-continue]' returns from the debugger.
0231f2dc
JB
133Arguments are mainly for use when this is called from the internals
134of the evaluator.
135
136You may call with no args, or you may pass nil as the first arg and
137any other args you like. In that case, the list of args after the
138first will be printed into the backtrace buffer."
73e78cf1 139 (interactive)
e734f584
RS
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
e227544d
SM
146 (debugger-previous-state
147 (if (get-buffer "*Backtrace*")
148 (with-current-buffer (get-buffer "*Backtrace*")
149 (list major-mode (buffer-string)))))
231d8498 150 (debugger-args args)
72f16325 151 (debugger-buffer (get-buffer-create "*Backtrace*"))
96e8d411 152 (debugger-old-buffer (current-buffer))
fa2bcf43 153 (debugger-window nil)
e734f584 154 (debugger-step-after-exit nil)
9b530428 155 (debugger-will-be-back nil)
e734f584
RS
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))
385480e5 161 (debugger-with-timeout-suspend (with-timeout-suspend)))
e734f584
RS
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
cf9a1b69
SM
167 (inhibit-trace t)
168 (inhibit-debug-on-entry t)
12cf32ce 169 unread-command-events
e734f584
RS
170 unread-post-input-method-events
171 last-input-event last-command-event last-nonmenu-event
172 last-event-frame
173 overriding-local-map
174 load-read-function
175 ;; If we are inside a minibuffer, allow nesting
176 ;; so that we don't get an error from the `e' command.
177 (enable-recursive-minibuffers
178 (or enable-recursive-minibuffers (> (minibuffer-depth) 0)))
179 (standard-input t) (standard-output t)
180 inhibit-redisplay
88ded8ac
MR
181 (cursor-in-echo-area nil)
182 (window-configuration (current-window-configuration)))
e734f584
RS
183 (unwind-protect
184 (save-excursion
fa2bcf43
MR
185 (when (eq (car debugger-args) 'debug)
186 ;; Skip the frames for backtrace-debug, byte-code,
231d8498 187 ;; debug--implement-debug-on-entry and the advice's `apply'.
fa2bcf43
MR
188 (backtrace-debug 4 t)
189 ;; Place an extra debug-on-exit for macro's.
190 (when (eq 'lambda (car-safe (cadr (backtrace-frame 4))))
191 (backtrace-debug 5 t)))
192 (pop-to-buffer
193 debugger-buffer
194 `((display-buffer-reuse-window
195 display-buffer-in-previous-window)
196 . (,(when debugger-previous-window
197 `(previous-window . ,debugger-previous-window)))))
198 (setq debugger-window (selected-window))
4dece104
MR
199 (if (eq debugger-previous-window debugger-window)
200 (when debugger-jumping-flag
201 ;; Try to restore previous height of debugger
202 ;; window.
203 (condition-case nil
204 (window-resize
205 debugger-window
206 (- debugger-previous-window-height
880e6158 207 (window-total-height debugger-window)))
4dece104
MR
208 (error nil)))
209 (setq debugger-previous-window debugger-window))
fa2bcf43
MR
210 (debugger-mode)
211 (debugger-setup-buffer debugger-args)
212 (when noninteractive
213 ;; If the backtrace is long, save the beginning
214 ;; and the end, but discard the middle.
215 (when (> (count-lines (point-min) (point-max))
216 debugger-batch-max-lines)
63ca439e 217 (goto-char (point-min))
fa2bcf43
MR
218 (forward-line (/ 2 debugger-batch-max-lines))
219 (let ((middlestart (point)))
220 (goto-char (point-max))
221 (forward-line (- (/ 2 debugger-batch-max-lines)
222 debugger-batch-max-lines))
223 (delete-region middlestart (point)))
224 (insert "...\n"))
225 (goto-char (point-min))
226 (message "%s" (buffer-string))
227 (kill-emacs -1))
228 (message "")
229 (let ((standard-output nil)
230 (buffer-read-only t))
35cf010d 231 (message "")
fa2bcf43
MR
232 ;; Make sure we unbind buffer-read-only in the right buffer.
233 (save-excursion
234 (recursive-edit))))
fb0104da
MR
235 (when (and (window-live-p debugger-window)
236 (eq (window-buffer debugger-window) debugger-buffer))
237 ;; Record height of debugger window.
238 (setq debugger-previous-window-height
880e6158 239 (window-total-height debugger-window)))
88ded8ac
MR
240 (if debugger-will-be-back
241 ;; Restore previous window configuration (Bug#12623).
242 (set-window-configuration window-configuration)
243 (when (and (window-live-p debugger-window)
244 (eq (window-buffer debugger-window) debugger-buffer))
245 (progn
88ded8ac
MR
246 ;; Unshow debugger-buffer.
247 (quit-restore-window debugger-window debugger-bury-or-kill)
248 ;; Restore current buffer (Bug#12502).
249 (set-buffer debugger-old-buffer))))
fa2bcf43
MR
250 ;; Restore previous state of debugger-buffer in case we were
251 ;; in a recursive invocation of the debugger, otherwise just
252 ;; erase the buffer and put it into fundamental mode.
253 (when (buffer-live-p debugger-buffer)
254 (with-current-buffer debugger-buffer
255 (let ((inhibit-read-only t))
256 (erase-buffer)
257 (if (null debugger-previous-state)
258 (fundamental-mode)
259 (insert (nth 1 debugger-previous-state))
260 (funcall (nth 0 debugger-previous-state))))))
385480e5 261 (with-timeout-unsuspend debugger-with-timeout-suspend)
e734f584 262 (set-match-data debugger-outer-match-data)))
e734f584
RS
263 (setq debug-on-next-call debugger-step-after-exit)
264 debugger-value)))
0231f2dc 265\f
231d8498 266(defun debugger-setup-buffer (args)
63ca439e
GM
267 "Initialize the `*Backtrace*' buffer for entry to the debugger.
268That buffer should be current already."
269 (setq buffer-read-only nil)
270 (erase-buffer)
c61dc887 271 (set-buffer-multibyte t) ;Why was it nil ? -stef
49c23b70 272 (setq buffer-undo-list t)
63ca439e
GM
273 (let ((standard-output (current-buffer))
274 (print-escape-newlines t)
275 (print-level 8)
276 (print-length 50))
277 (backtrace))
278 (goto-char (point-min))
279 (delete-region (point)
280 (progn
281 (search-forward "\n debug(")
231d8498
SM
282 (forward-line (if (eq (car args) 'debug)
283 ;; Remove debug--implement-debug-on-entry
284 ;; and the advice's `apply' frame.
285 3
439368ed 286 1))
63ca439e
GM
287 (point)))
288 (insert "Debugger entered")
289 ;; lambda is for debug-on-call when a function call is next.
290 ;; debug is for debug-on-entry function called.
10fa0ed3
SM
291 (let ((pos (point)))
292 (pcase (car args)
293 ((or `lambda `debug)
294 (insert "--entering a function:\n")
295 (setq pos (1- (point))))
296 ;; Exiting a function.
297 (`exit
298 (insert "--returning value: ")
299 (setq pos (point))
300 (setq debugger-value (nth 1 args))
301 (prin1 debugger-value (current-buffer))
302 (insert ?\n)
303 (delete-char 1)
304 (insert ? )
305 (beginning-of-line))
306 ;; Debugger entered for an error.
307 (`error
308 (insert "--Lisp error: ")
309 (setq pos (point))
310 (prin1 (nth 1 args) (current-buffer))
311 (insert ?\n))
312 ;; debug-on-call, when the next thing is an eval.
313 (`t
314 (insert "--beginning evaluation of function call form:\n")
315 (setq pos (1- (point))))
316 ;; User calls debug directly.
317 (_
318 (insert ": ")
319 (setq pos (point))
320 (prin1 (if (eq (car args) 'nil)
321 (cdr args) args)
322 (current-buffer))
323 (insert ?\n)))
324 ;; Place point on "stack frame 0" (bug#15101).
325 (goto-char pos))
27bde5f0
RS
326 ;; After any frame that uses eval-buffer,
327 ;; insert a line that states the buffer position it's reading at.
328 (save-excursion
245f0222
RS
329 (let ((tem eval-buffer-list))
330 (while (and tem
331 (re-search-forward "^ eval-\\(buffer\\|region\\)(" nil t))
332 (end-of-line)
333 (insert (format " ; Reading at buffer position %d"
334 ;; This will get the wrong result
335 ;; if there are two nested eval-region calls
336 ;; for the same buffer. That's not a very useful case.
337 (with-current-buffer (car tem)
338 (point))))
339 (pop tem))))
cc1bde62
SS
340 (debugger-make-xrefs))
341
342(defun debugger-make-xrefs (&optional buffer)
dc64809a 343 "Attach cross-references to function names in the `*Backtrace*' buffer."
cc1bde62 344 (interactive "b")
9a529312 345 (with-current-buffer (or buffer (current-buffer))
8e39b2e8
GM
346 (save-excursion
347 (setq buffer (current-buffer))
348 (let ((inhibit-read-only t)
5f66aa05
GM
349 (old-end (point-min)) (new-end (point-min)))
350 ;; If we saved an old backtrace, find the common part
351 ;; between the new and the old.
352 ;; Compare line by line, starting from the end,
353 ;; because that's the part that is likely to be unchanged.
354 (if debugger-previous-backtrace
355 (let (old-start new-start (all-match t))
356 (goto-char (point-max))
357 (with-temp-buffer
358 (insert debugger-previous-backtrace)
359 (while (and all-match (not (bobp)))
360 (setq old-end (point))
361 (forward-line -1)
362 (setq old-start (point))
363 (with-current-buffer buffer
364 (setq new-end (point))
365 (forward-line -1)
366 (setq new-start (point)))
367 (if (not (zerop
368 (let ((case-fold-search nil))
369 (compare-buffer-substrings
370 (current-buffer) old-start old-end
371 buffer new-start new-end))))
372 (setq all-match nil))))
373 ;; Now new-end is the position of the start of the
374 ;; unchanged part in the current buffer, and old-end is
375 ;; the position of that same text in the saved old
376 ;; backtrace. But we must subtract (point-min) since strings are
377 ;; indexed in origin 0.
25c58854 378
5f66aa05
GM
379 ;; Replace the unchanged part of the backtrace
380 ;; with the text from debugger-previous-backtrace,
381 ;; since that already has the proper xrefs.
382 ;; With this optimization, we only need to scan
383 ;; the changed part of the backtrace.
384 (delete-region new-end (point-max))
385 (goto-char (point-max))
386 (insert (substring debugger-previous-backtrace
387 (- old-end (point-min))))
388 ;; Make the unchanged part of the backtrace inaccessible
389 ;; so it won't be scanned.
390 (narrow-to-region (point-min) new-end)))
a1506d29 391
5f66aa05
GM
392 ;; Scan the new part of the backtrace, inserting xrefs.
393 (goto-char (point-min))
394 (while (progn
395 (goto-char (+ (point) 2))
396 (skip-syntax-forward "^w_")
397 (not (eobp)))
398 (let* ((beg (point))
399 (end (progn (skip-syntax-forward "w_") (point)))
400 (sym (intern-soft (buffer-substring-no-properties
401 beg end)))
402 (file (and sym (symbol-file sym 'defun))))
403 (when file
404 (goto-char beg)
405 ;; help-xref-button needs to operate on something matched
406 ;; by a regexp, so set that up for it.
407 (re-search-forward "\\(\\sw\\|\\s_\\)+")
408 (help-xref-button 0 'help-function-def sym file)))
409 (forward-line 1))
410 (widen))
8e39b2e8 411 (setq debugger-previous-backtrace (buffer-string)))))
63ca439e 412\f
0231f2dc
JB
413(defun debugger-step-through ()
414 "Proceed, stepping through subexpressions of this expression.
415Enter another debugger on next entry to eval, apply or funcall."
416 (interactive)
417 (setq debugger-step-after-exit t)
9b54d453 418 (setq debugger-jumping-flag t)
9b530428 419 (setq debugger-will-be-back t)
9b54d453 420 (add-hook 'post-command-hook 'debugger-reenable)
0231f2dc
JB
421 (message "Proceeding, will debug on next eval or call.")
422 (exit-recursive-edit))
423
424(defun debugger-continue ()
425 "Continue, evaluating this expression without stopping."
426 (interactive)
094e0928
GM
427 (unless debugger-may-continue
428 (error "Cannot continue"))
0231f2dc 429 (message "Continuing.")
9b530428
SM
430 (save-excursion
431 ;; Check to see if we've flagged some frame for debug-on-exit, in which
432 ;; case we'll probably come back to the debugger soon.
433 (goto-char (point-min))
434 (if (re-search-forward "^\\* " nil t)
435 (setq debugger-will-be-back t)))
0231f2dc
JB
436 (exit-recursive-edit))
437
438(defun debugger-return-value (val)
439 "Continue, specifying value to return.
440This is only useful when the value returned from the debugger
441will be used, such as in a debug on exit from a frame."
442 (interactive "XReturn value (evaluated): ")
e24e27be
SM
443 (when (memq (car debugger-args) '(t lambda error debug))
444 (error "Cannot return a value %s"
445 (if (eq (car debugger-args) 'error)
446 "from an error" "at function entrance")))
0231f2dc
JB
447 (setq debugger-value val)
448 (princ "Returning " t)
449 (prin1 debugger-value)
9b530428
SM
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)))
0231f2dc
JB
456 (exit-recursive-edit))
457
458(defun debugger-jump ()
459 "Continue to exit from this frame, with all debug-on-entry suspended."
460 (interactive)
27bde5f0 461 (debugger-frame)
b6b77a90
LK
462 (setq debugger-jumping-flag t)
463 (add-hook 'post-command-hook 'debugger-reenable)
0231f2dc 464 (message "Continuing through this frame")
9b530428 465 (setq debugger-will-be-back t)
0231f2dc
JB
466 (exit-recursive-edit))
467
468(defun debugger-reenable ()
b6b77a90
LK
469 "Turn all debug-on-entry functions back on.
470This function is put on `post-command-hook' by `debugger-jump' and
471removes itself from that hook."
472 (setq debugger-jumping-flag nil)
473 (remove-hook 'post-command-hook 'debugger-reenable))
0231f2dc 474
56ea7291 475(defun debugger-frame-number (&optional skip-base)
0231f2dc
JB
476 "Return number of frames in backtrace before the one point points at."
477 (save-excursion
478 (beginning-of-line)
56ea7291
SM
479 (if (looking-at " *;;;\\|[a-z]")
480 (error "This line is not a function call"))
0231f2dc
JB
481 (let ((opoint (point))
482 (count 0))
56ea7291
SM
483 (unless skip-base
484 (while (not (eq (cadr (backtrace-frame count)) 'debug))
485 (setq count (1+ count)))
486 ;; Skip debug--implement-debug-on-entry frame.
487 (when (eq 'debug--implement-debug-on-entry
488 (cadr (backtrace-frame (1+ count))))
489 (setq count (+ 2 count))))
0231f2dc 490 (goto-char (point-min))
439368ed
LK
491 (when (looking-at "Debugger entered--\\(Lisp error\\|returning value\\):")
492 (goto-char (match-end 0))
493 (forward-sexp 1))
0231f2dc
JB
494 (forward-line 1)
495 (while (progn
496 (forward-char 2)
f345395c
HE
497 (cond ((debugger--locals-visible-p)
498 (goto-char (next-single-char-property-change
499 (point) 'locals-visible)))
500 ((= (following-char) ?\()
501 (forward-sexp 1))
502 (t
503 (forward-sexp 2)))
0231f2dc
JB
504 (forward-line 1)
505 (<= (point) opoint))
65fe45f2
RS
506 (if (looking-at " *;;;")
507 (forward-line 1))
0231f2dc
JB
508 (setq count (1+ count)))
509 count)))
510
0231f2dc
JB
511(defun debugger-frame ()
512 "Request entry to debugger when this frame exits.
513Applies to the frame whose line point is on in the backtrace."
514 (interactive)
27bde5f0 515 (backtrace-debug (debugger-frame-number) t)
56ea7291 516 (beginning-of-line)
0231f2dc 517 (if (= (following-char) ? )
9b530428 518 (let ((inhibit-read-only t))
0231f2dc
JB
519 (delete-char 1)
520 (insert ?*)))
521 (beginning-of-line))
522
523(defun debugger-frame-clear ()
c519f68f 524 "Do not enter debugger when this frame exits.
0231f2dc
JB
525Applies to the frame whose line point is on in the backtrace."
526 (interactive)
27bde5f0 527 (backtrace-debug (debugger-frame-number) nil)
56ea7291 528 (beginning-of-line)
0231f2dc 529 (if (= (following-char) ?*)
9b530428 530 (let ((inhibit-read-only t))
0231f2dc
JB
531 (delete-char 1)
532 (insert ? )))
533 (beginning-of-line))
534
8c1cd093
KH
535(defmacro debugger-env-macro (&rest body)
536 "Run BODY in original environment."
f291fe60 537 (declare (indent 0))
6c2599ed 538 `(save-excursion
56ea7291 539 (if (null (buffer-live-p debugger-old-buffer))
6c2599ed
SS
540 ;; old buffer deleted
541 (setq debugger-old-buffer (current-buffer)))
542 (set-buffer debugger-old-buffer)
56ea7291
SM
543 (set-match-data debugger-outer-match-data)
544 (prog1
545 (progn ,@body)
546 (setq debugger-outer-match-data (match-data)))))
8c1cd093 547
f345395c
HE
548(defun debugger--backtrace-base ()
549 "Return the function name that marks the top of the backtrace.
550See `backtrace-frame'."
551 (cond ((eq 'debug--implement-debug-on-entry
552 (cadr (backtrace-frame 1 'debug)))
553 'debug--implement-debug-on-entry)
554 (t 'debug)))
555
10fa0ed3 556(defun debugger-eval-expression (exp &optional nframe)
56ea7291
SM
557 "Eval an expression, in an environment like that outside the debugger.
558The environment used is the one when entering the activation frame at point."
8782c06b 559 (interactive
10fa0ed3
SM
560 (list (read--expression "Eval in stack frame: ")))
561 (let ((nframe (or nframe
562 (condition-case nil (1+ (debugger-frame-number 'skip-base))
563 (error 0)))) ;; If on first line.
f345395c 564 (base (debugger--backtrace-base)))
56ea7291
SM
565 (debugger-env-macro
566 (let ((val (backtrace-eval exp nframe base)))
567 (prog1
568 (prin1 val t)
569 (let ((str (eval-expression-print-format val)))
570 (if str (princ str t))))))))
f345395c
HE
571
572(defun debugger--locals-visible-p ()
573 "Are the local variables of the current stack frame visible?"
574 (save-excursion
575 (move-to-column 2)
576 (get-text-property (point) 'locals-visible)))
577
578(defun debugger--insert-locals (locals)
579 "Insert the local variables LOCALS at point."
580 (cond ((null locals)
581 (insert "\n [no locals]"))
582 (t
583 (let ((print-escape-newlines t))
584 (dolist (s+v locals)
585 (let ((symbol (car s+v))
586 (value (cdr s+v)))
587 (insert "\n ")
588 (prin1 symbol (current-buffer))
589 (insert " = ")
590 (prin1 value (current-buffer))))))))
591
592(defun debugger--show-locals ()
593 "For the frame at point, insert locals and add text properties."
594 (let* ((nframe (1+ (debugger-frame-number 'skip-base)))
595 (base (debugger--backtrace-base))
596 (locals (backtrace--locals nframe base))
597 (inhibit-read-only t))
598 (save-excursion
599 (let ((start (progn
600 (move-to-column 2)
601 (point))))
602 (end-of-line)
603 (debugger--insert-locals locals)
604 (add-text-properties start (point) '(locals-visible t))))))
605
606(defun debugger--hide-locals ()
607 "Delete local variables and remove the text property."
608 (let* ((col (current-column))
609 (end (progn
610 (move-to-column 2)
611 (next-single-char-property-change (point) 'locals-visible)))
612 (start (previous-single-char-property-change end 'locals-visible))
613 (inhibit-read-only t))
614 (remove-text-properties start end '(locals-visible))
615 (goto-char start)
616 (end-of-line)
617 (delete-region (point) end)
618 (move-to-column col)))
619
620(defun debugger-toggle-locals ()
621 "Show or hide local variables of the current stack frame."
622 (interactive)
623 (cond ((debugger--locals-visible-p)
624 (debugger--hide-locals))
625 (t
626 (debugger--show-locals))))
627
0231f2dc 628\f
78d54dee 629(defvar debugger-mode-map
b2371818
DN
630 (let ((map (make-keymap))
631 (menu-map (make-sparse-keymap)))
78d54dee
SM
632 (set-keymap-parent map button-buffer-map)
633 (suppress-keymap map)
634 (define-key map "-" 'negative-argument)
635 (define-key map "b" 'debugger-frame)
636 (define-key map "c" 'debugger-continue)
637 (define-key map "j" 'debugger-jump)
638 (define-key map "r" 'debugger-return-value)
639 (define-key map "u" 'debugger-frame-clear)
640 (define-key map "d" 'debugger-step-through)
641 (define-key map "l" 'debugger-list-functions)
642 (define-key map "h" 'describe-mode)
643 (define-key map "q" 'top-level)
644 (define-key map "e" 'debugger-eval-expression)
09a7c0fe 645 (define-key map "v" 'debugger-toggle-locals) ; "v" is for "variables".
78d54dee
SM
646 (define-key map " " 'next-line)
647 (define-key map "R" 'debugger-record-expression)
245f0222 648 (define-key map "\C-m" 'debug-help-follow)
78d54dee 649 (define-key map [mouse-2] 'push-button)
b2371818
DN
650 (define-key map [menu-bar debugger] (cons "Debugger" menu-map))
651 (define-key menu-map [deb-top]
652 '(menu-item "Quit" top-level
f6ec6415 653 :help "Quit debugging and return to top level"))
b2371818
DN
654 (define-key menu-map [deb-s0] '("--"))
655 (define-key menu-map [deb-descr]
656 '(menu-item "Describe Debugger Mode" describe-mode
657 :help "Display documentation for debugger-mode"))
658 (define-key menu-map [deb-hfol]
659 '(menu-item "Help Follow" debug-help-follow
660 :help "Follow cross-reference"))
661 (define-key menu-map [deb-nxt]
662 '(menu-item "Next Line" next-line
663 :help "Move cursor down"))
664 (define-key menu-map [deb-s1] '("--"))
665 (define-key menu-map [deb-lfunc]
666 '(menu-item "List debug on entry functions" debugger-list-functions
667 :help "Display a list of all the functions now set to debug on entry"))
668 (define-key menu-map [deb-fclear]
669 '(menu-item "Cancel debug frame" debugger-frame-clear
670 :help "Do not enter debugger when this frame exits"))
671 (define-key menu-map [deb-frame]
672 '(menu-item "Debug frame" debugger-frame
673 :help "Request entry to debugger when this frame exits"))
674 (define-key menu-map [deb-s2] '("--"))
675 (define-key menu-map [deb-ret]
676 '(menu-item "Return value..." debugger-return-value
677 :help "Continue, specifying value to return."))
678 (define-key menu-map [deb-rec]
679 '(menu-item "Display and Record Expression" debugger-record-expression
680 :help "Display a variable's value and record it in `*Backtrace-record*' buffer"))
681 (define-key menu-map [deb-eval]
682 '(menu-item "Eval Expression..." debugger-eval-expression
683 :help "Eval an expression, in an environment like that outside the debugger"))
684 (define-key menu-map [deb-jump]
685 '(menu-item "Jump" debugger-jump
686 :help "Continue to exit from this frame, with all debug-on-entry suspended"))
687 (define-key menu-map [deb-cont]
688 '(menu-item "Continue" debugger-continue
231d8498 689 :help "Continue, evaluating this expression without stopping"))
b2371818
DN
690 (define-key menu-map [deb-step]
691 '(menu-item "Step through" debugger-step-through
231d8498 692 :help "Proceed, stepping through subexpressions of this expression"))
78d54dee 693 map))
028d38a2
RS
694
695(put 'debugger-mode 'mode-class 'special)
696
1b3b87df 697(define-derived-mode debugger-mode fundamental-mode "Debugger"
028d38a2
RS
698 "Mode for backtrace buffers, selected in debugger.
699\\<debugger-mode-map>
700A line starts with `*' if exiting that frame will call the debugger.
701Type \\[debugger-frame] or \\[debugger-frame-clear] to set or remove the `*'.
702
703When in debugger due to frame being exited,
704use the \\[debugger-return-value] command to override the value
705being returned from that frame.
706
707Use \\[debug-on-entry] and \\[cancel-debug-on-entry] to control
708which functions will enter the debugger when called.
709
710Complete list of commands:
711\\{debugger-mode-map}"
028d38a2
RS
712 (setq truncate-lines t)
713 (set-syntax-table emacs-lisp-mode-syntax-table)
1b3b87df 714 (use-local-map debugger-mode-map))
245f0222 715\f
666b9413 716(defcustom debugger-record-buffer "*Debugger-record*"
cb711556 717 "Buffer name for expression values, for \\[debugger-record-expression]."
666b9413 718 :type 'string
cd32a7ba
DN
719 :group 'debugger
720 :version "20.3")
8c1cd093
KH
721
722(defun debugger-record-expression (exp)
723 "Display a variable's value and record it in `*Backtrace-record*' buffer."
724 (interactive
10fa0ed3 725 (list (read--expression "Record Eval: ")))
8c1cd093
KH
726 (let* ((buffer (get-buffer-create debugger-record-buffer))
727 (standard-output buffer))
728 (princ (format "Debugger Eval (%s): " exp))
729 (princ (debugger-eval-expression exp))
730 (terpri))
731
732 (with-current-buffer (get-buffer debugger-record-buffer)
8e71c318 733 (message "%s"
be940bc5
SM
734 (buffer-substring (line-beginning-position 0)
735 (line-end-position 0)))))
0231f2dc 736
f63b822e
GM
737(declare-function help-xref-interned "help-mode" (symbol))
738
245f0222
RS
739(defun debug-help-follow (&optional pos)
740 "Follow cross-reference at POS, defaulting to point.
741
742For the cross-reference format, see `help-make-xrefs'."
743 (interactive "d")
744 (require 'help-mode)
a5f1e154
LT
745 ;; Ideally we'd just do (call-interactively 'help-follow) except that this
746 ;; assumes we're already in a *Help* buffer and reuses it, so it ends up
747 ;; incorrectly "reusing" the *Backtrace* buffer to show the help info.
245f0222
RS
748 (unless pos
749 (setq pos (point)))
750 (unless (push-button pos)
751 ;; check if the symbol under point is a function or variable
752 (let ((sym
753 (intern
754 (save-excursion
755 (goto-char pos) (skip-syntax-backward "w_")
756 (buffer-substring (point)
757 (progn (skip-syntax-forward "w_")
758 (point)))))))
759 (when (or (boundp sym) (fboundp sym) (facep sym))
1fe3c8f5 760 (help-xref-interned sym)))))
0231f2dc 761\f
449808f7
LK
762;; When you change this, you may also need to change the number of
763;; frames that the debugger skips.
231d8498 764(defun debug--implement-debug-on-entry (&rest _ignore)
449808f7
LK
765 "Conditionally call the debugger.
766A call to this function is inserted by `debug-on-entry' to cause
767functions to break on entry."
768 (if (or inhibit-debug-on-entry debugger-jumping-flag)
769 nil
770 (funcall debugger 'debug)))
771
0231f2dc
JB
772;;;###autoload
773(defun debug-on-entry (function)
774 "Request FUNCTION to invoke debugger each time it is called.
8ac3941d 775
8e71c318 776When called interactively, prompt for FUNCTION in the minibuffer.
8ac3941d
LK
777
778This works by modifying the definition of FUNCTION. If you tell the
779debugger to continue, FUNCTION's execution proceeds. If FUNCTION is a
780normal function or a macro written in Lisp, you can also step through
781its execution. FUNCTION can also be a primitive that is not a special
782form, in which case stepping is not possible. Break-on-entry for
783primitive functions only works when that function is called from Lisp.
784
0231f2dc 785Use \\[cancel-debug-on-entry] to cancel the effect of this command.
2512acba 786Redefining FUNCTION also cancels it."
ce5ce46d
LK
787 (interactive
788 (let ((fn (function-called-at-point)) val)
231d8498 789 (when (special-form-p fn)
ce5ce46d 790 (setq fn nil))
3731a850 791 (setq val (completing-read
ce5ce46d
LK
792 (if fn
793 (format "Debug on entry to function (default %s): " fn)
794 "Debug on entry to function: ")
795 obarray
796 #'(lambda (symbol)
797 (and (fboundp symbol)
231d8498 798 (not (special-form-p symbol))))
ce5ce46d
LK
799 t nil nil (symbol-name fn)))
800 (list (if (equal val "") fn (intern val)))))
cb3a1380
SM
801 (advice-add function :before #'debug--implement-debug-on-entry
802 '((depth . -100)))
0231f2dc
JB
803 function)
804
231d8498
SM
805(defun debug--function-list ()
806 "List of functions currently set for debug on entry."
807 (let ((funs '()))
808 (mapatoms
809 (lambda (s)
810 (when (advice-member-p #'debug--implement-debug-on-entry s)
811 (push s funs))))
812 funs))
813
0231f2dc
JB
814;;;###autoload
815(defun cancel-debug-on-entry (&optional function)
816 "Undo effect of \\[debug-on-entry] on FUNCTION.
dd72a03a 817If FUNCTION is nil, cancel debug-on-entry for all functions.
8e71c318
LT
818When called interactively, prompt for FUNCTION in the minibuffer.
819To specify a nil argument interactively, exit with an empty minibuffer."
10a4c11f
JB
820 (interactive
821 (list (let ((name
922a9de3 822 (completing-read
5b76833f 823 "Cancel debug on entry to function (default all functions): "
231d8498 824 (mapcar #'symbol-name (debug--function-list)) nil t)))
dd72a03a
LK
825 (when name
826 (unless (string= name "")
827 (intern name))))))
231d8498 828 (if function
0231f2dc 829 (progn
231d8498 830 (advice-remove function #'debug--implement-debug-on-entry)
0231f2dc 831 function)
d5081c1e 832 (message "Canceling debug-on-entry for all functions")
231d8498 833 (mapcar #'cancel-debug-on-entry (debug--function-list))))
0231f2dc
JB
834
835(defun debugger-list-functions ()
836 "Display a list of all the functions now set to debug on entry."
837 (interactive)
78d54dee 838 (require 'help-mode)
32226619
JB
839 (help-setup-xref '(debugger-list-functions)
840 (called-interactively-p 'interactive))
78d54dee
SM
841 (with-output-to-temp-buffer (help-buffer)
842 (with-current-buffer standard-output
231d8498
SM
843 (let ((funs (debug--function-list)))
844 (if (null funs)
845 (princ "No debug-on-entry functions now\n")
846 (princ "Functions set to debug on entry:\n\n")
847 (dolist (fun funs)
848 (make-text-button (point) (progn (prin1 fun) (point))
849 'type 'help-function
850 'help-args (list fun))
851 (terpri))
852 (terpri)
853 (princ "Note: if you have redefined a function, then it may no longer\n")
854 (princ "be set to debug on entry, even if it is in the list."))))))
c0274f38 855
896546cd
RS
856(provide 'debug)
857
c0274f38 858;;; debug.el ends here