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