debug.el 36 KB
Newer Older
Eric S. Raymond's avatar
Eric S. Raymond committed
1 2
;;; debug.el --- debuggers and related commands for Emacs

3
;; Copyright (C) 1985-1986, 1994, 2001-2012 Free Software Foundation, Inc.
Eric S. Raymond's avatar
Eric S. Raymond committed
4

Eric S. Raymond's avatar
Eric S. Raymond committed
5
;; Maintainer: FSF
Eric S. Raymond's avatar
Eric S. Raymond committed
6
;; Keywords: lisp, tools, maint
Eric S. Raymond's avatar
Eric S. Raymond committed
7

Jim Blandy's avatar
Jim Blandy committed
8 9
;; This file is part of GNU Emacs.

10
;; GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
11
;; it under the terms of the GNU General Public License as published by
12 13
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
14 15 16 17 18 19 20

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
21
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
Jim Blandy's avatar
Jim Blandy committed
22

23 24
;;; Commentary:

25
;; This is a major mode documented in the Emacs Lisp manual.
26

Eric S. Raymond's avatar
Eric S. Raymond committed
27
;;; Code:
Jim Blandy's avatar
Jim Blandy committed
28

Miles Bader's avatar
Miles Bader committed
29 30
(require 'button)

Stephen Eglen's avatar
Stephen Eglen committed
31 32 33 34
(defgroup debugger nil
  "Debuggers and related commands for Emacs."
  :prefix "debugger-"
  :group 'debug)
35

Stephen Eglen's avatar
Stephen Eglen committed
36
(defcustom debugger-mode-hook nil
37
  "Hooks run when `debugger-mode' is turned on."
Stephen Eglen's avatar
Stephen Eglen committed
38
  :type 'hook
Dan Nicolaescu's avatar
Dan Nicolaescu committed
39 40
  :group 'debugger
  :version "20.3")
41

42
(defcustom debugger-batch-max-lines 40
43
  "Maximum lines to show in debugger buffer in a noninteractive Emacs.
44 45 46 47 48 49
When the debugger is entered and Emacs is running in batch mode,
if the backtrace text has more than this many lines,
the middle is discarded, and just the beginning and end are displayed."
  :type 'integer
  :group 'debugger
  :version "21.1")
Jim Blandy's avatar
Jim Blandy committed
50

51 52 53 54 55
(defvar debug-function-list nil
  "List of functions currently set for debug on entry.")

(defvar debugger-step-after-exit nil
  "Non-nil means \"single-step\" after the debugger exits.")
56 57 58 59 60 61 62

(defvar debugger-value nil
  "This is the value for the debugger to return, when it returns.")

(defvar debugger-old-buffer nil
  "This is the buffer that was current when the debugger was entered.")

63 64 65 66
(defvar debugger-previous-backtrace nil
  "The contents of the previous backtrace (including text properties).
This is to optimize `debugger-make-xrefs'.")

67
(defvar debugger-outer-match-data)
68 69
(defvar debugger-outer-load-read-function)
(defvar debugger-outer-overriding-local-map)
70
(defvar debugger-outer-overriding-terminal-local-map)
71 72 73
(defvar debugger-outer-track-mouse)
(defvar debugger-outer-last-command)
(defvar debugger-outer-this-command)
Richard M. Stallman's avatar
Richard M. Stallman committed
74 75 76
;; unread-command-char is obsolete,
;; but we still save and restore it
;; in case some user program still tries to set it.
77 78
(defvar debugger-outer-unread-command-char)
(defvar debugger-outer-unread-command-events)
79
(defvar debugger-outer-unread-post-input-method-events)
80 81 82 83 84 85
(defvar debugger-outer-last-input-event)
(defvar debugger-outer-last-command-event)
(defvar debugger-outer-last-nonmenu-event)
(defvar debugger-outer-last-event-frame)
(defvar debugger-outer-standard-input)
(defvar debugger-outer-standard-output)
86
(defvar debugger-outer-inhibit-redisplay)
87
(defvar debugger-outer-cursor-in-echo-area)
88 89
(defvar debugger-will-be-back nil
  "Non-nil if we expect to get back in the debugger soon.")
90

91 92 93 94 95
(defvar inhibit-debug-on-entry nil
  "Non-nil means that debug-on-entry is disabled.")

(defvar debugger-jumping-flag nil
  "Non-nil means that debug-on-entry is disabled.
96 97
This variable is used by `debugger-jump', `debugger-step-through',
and `debugger-reenable' to temporarily disable debug-on-entry.")
98

99
(defvar inhibit-trace)                  ;Not yet implemented.
100

101 102 103 104 105 106 107 108 109 110
(defvar debugger-args nil
  "Arguments with which the debugger was called.
It is a list expected to take the form (CAUSE . REST)
where CAUSE can be:
- debug: called for entry to a flagged function.
- t: called because of debug-on-next-call.
- lambda: same thing but via `funcall'.
- exit: called because of exit of a flagged function.
- error: called because of `debug-on-error'.")

Jim Blandy's avatar
Jim Blandy committed
111 112 113 114
;;;###autoload
(setq debugger 'debug)
;;;###autoload
(defun debug (&rest debugger-args)
115
  "Enter debugger.  \\<debugger-mode-map>`\\[debugger-continue]' returns from the debugger.
Jim Blandy's avatar
Jim Blandy committed
116 117 118 119 120 121
Arguments are mainly for use when this is called from the internals
of the evaluator.

You may call with no args, or you may pass nil as the first arg and
any other args you like.  In that case, the list of args after the
first will be printed into the backtrace buffer."
122
  (interactive)
123 124 125 126 127 128 129 130
  (if inhibit-redisplay
      ;; Don't really try to enter debugger within an eval from redisplay.
      debugger-value
    (unless noninteractive
      (message "Entering debugger..."))
    (let (debugger-value
	  (debug-on-error nil)
	  (debug-on-quit nil)
131 132 133 134
	  (debugger-previous-state
           (if (get-buffer "*Backtrace*")
               (with-current-buffer (get-buffer "*Backtrace*")
                 (list major-mode (buffer-string)))))
135
	  (debugger-buffer (get-buffer-create "*Backtrace*"))
136 137
	  (debugger-old-buffer (current-buffer))
	  (debugger-step-after-exit nil)
138
          (debugger-will-be-back nil)
139 140 141 142 143 144 145 146 147 148 149 150
	  ;; Don't keep reading from an executing kbd macro!
	  (executing-kbd-macro nil)
	  ;; Save the outer values of these vars for the `e' command
	  ;; before we replace the values.
	  (debugger-outer-match-data (match-data))
	  (debugger-outer-load-read-function load-read-function)
	  (debugger-outer-overriding-local-map overriding-local-map)
	  (debugger-outer-overriding-terminal-local-map
	   overriding-terminal-local-map)
	  (debugger-outer-track-mouse track-mouse)
	  (debugger-outer-last-command last-command)
	  (debugger-outer-this-command this-command)
151 152
	  (debugger-outer-unread-command-char
	   (with-no-warnings unread-command-char))
153 154 155 156 157 158 159 160 161 162
	  (debugger-outer-unread-command-events unread-command-events)
	  (debugger-outer-unread-post-input-method-events
	   unread-post-input-method-events)
	  (debugger-outer-last-input-event last-input-event)
	  (debugger-outer-last-command-event last-command-event)
	  (debugger-outer-last-nonmenu-event last-nonmenu-event)
	  (debugger-outer-last-event-frame last-event-frame)
	  (debugger-outer-standard-input standard-input)
	  (debugger-outer-standard-output standard-output)
	  (debugger-outer-inhibit-redisplay inhibit-redisplay)
163 164
	  (debugger-outer-cursor-in-echo-area cursor-in-echo-area)
	  (debugger-with-timeout-suspend (with-timeout-suspend)))
165 166 167 168 169
      ;; Set this instead of binding it, so that `q'
      ;; will not restore it.
      (setq overriding-terminal-local-map nil)
      ;; Don't let these magic variables affect the debugger itself.
      (let ((last-command nil) this-command track-mouse
170 171
	    (inhibit-trace t)
	    (inhibit-debug-on-entry t)
172
	    unread-command-events
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
	    unread-post-input-method-events
	    last-input-event last-command-event last-nonmenu-event
	    last-event-frame
	    overriding-local-map
	    load-read-function
	    ;; If we are inside a minibuffer, allow nesting
	    ;; so that we don't get an error from the `e' command.
	    (enable-recursive-minibuffers
	     (or enable-recursive-minibuffers (> (minibuffer-depth) 0)))
	    (standard-input t) (standard-output t)
	    inhibit-redisplay
	    (cursor-in-echo-area nil))
	(unwind-protect
	    (save-excursion
	      (save-window-excursion
188
		(with-no-warnings
189 190 191 192 193 194 195 196
		  (setq unread-command-char -1))
		(when (eq (car debugger-args) 'debug)
		  ;; Skip the frames for backtrace-debug, byte-code,
		  ;; and implement-debug-on-entry.
		  (backtrace-debug 4 t)
		  ;; Place an extra debug-on-exit for macro's.
		  (when (eq 'lambda (car-safe (cadr (backtrace-frame 4))))
		    (backtrace-debug 5 t)))
197
                (pop-to-buffer debugger-buffer)
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
		(debugger-mode)
		(debugger-setup-buffer debugger-args)
		(when noninteractive
		  ;; If the backtrace is long, save the beginning
		  ;; and the end, but discard the middle.
		  (when (> (count-lines (point-min) (point-max))
			   debugger-batch-max-lines)
		    (goto-char (point-min))
		    (forward-line (/ 2 debugger-batch-max-lines))
		    (let ((middlestart (point)))
		      (goto-char (point-max))
		      (forward-line (- (/ 2 debugger-batch-max-lines)
				       debugger-batch-max-lines))
		      (delete-region middlestart (point)))
		    (insert "...\n"))
213
		  (goto-char (point-min))
Stefan Monnier's avatar
Stefan Monnier committed
214
		  (message "%s" (buffer-string))
215
		  (kill-emacs -1))
216
		(message "")
217
		(let ((standard-output nil)
218 219 220 221 222 223 224
		      (buffer-read-only t))
		  (message "")
		  ;; Make sure we unbind buffer-read-only in the right buffer.
		  (save-excursion
		    (recursive-edit)))))
	  ;; Kill or at least neuter the backtrace buffer, so that users
	  ;; don't try to execute debugger commands in an invalid context.
225
	  (if (get-buffer-window debugger-buffer 0)
226 227 228
	      ;; Still visible despite the save-window-excursion?  Maybe it
	      ;; it's in a pop-up frame.  It would be annoying to delete and
	      ;; recreate it every time the debugger stops, so instead we'll
229
	      ;; erase it (and maybe hide it) but keep it alive.
230 231
	      (with-current-buffer debugger-buffer
		(with-selected-window (get-buffer-window debugger-buffer 0)
232
                  (when (and (window-dedicated-p (selected-window))
233
                             (not debugger-will-be-back))
234 235
                    ;; If the window is not dedicated, burying the buffer
                    ;; will mean that the frame created for it is left
236
                    ;; around showing some random buffer, and next time we
237 238
                    ;; pop to the debugger buffer we'll create yet
                    ;; another frame.
239
                    ;; If debugger-will-be-back is non-nil, the frame
240 241 242
                    ;; would need to be de-iconified anyway immediately
                    ;; after when we re-enter the debugger, so iconifying it
                    ;; here would cause flashing.
243 244 245 246
                    ;; Drew Adams is not happy with this: he wants to frame
                    ;; to be left at the top-level, still working on how
                    ;; best to do that.
                    (bury-buffer))))
247 248 249 250
            (unless debugger-previous-state
              (kill-buffer debugger-buffer)))
          ;; Restore the previous state of the debugger-buffer, in case we were
          ;; in a recursive invocation of the debugger.
251
          (when (buffer-live-p debugger-buffer)
252 253 254
            (with-current-buffer debugger-buffer
              (let ((inhibit-read-only t))
                (erase-buffer)
255 256 257 258
                (if (null debugger-previous-state)
                    (fundamental-mode)
                  (insert (nth 1 debugger-previous-state))
                  (funcall (nth 0 debugger-previous-state))))))
259
	  (with-timeout-unsuspend debugger-with-timeout-suspend)
260 261 262 263 264 265 266 267 268 269
	  (set-match-data debugger-outer-match-data)))
      ;; Put into effect the modified values of these variables
      ;; in case the user set them with the `e' command.
      (setq load-read-function debugger-outer-load-read-function)
      (setq overriding-local-map debugger-outer-overriding-local-map)
      (setq overriding-terminal-local-map
	    debugger-outer-overriding-terminal-local-map)
      (setq track-mouse debugger-outer-track-mouse)
      (setq last-command debugger-outer-last-command)
      (setq this-command debugger-outer-this-command)
270
      (with-no-warnings
271
	(setq unread-command-char debugger-outer-unread-command-char))
272 273 274 275 276 277 278 279 280 281 282 283 284
      (setq unread-command-events debugger-outer-unread-command-events)
      (setq unread-post-input-method-events
	    debugger-outer-unread-post-input-method-events)
      (setq last-input-event debugger-outer-last-input-event)
      (setq last-command-event debugger-outer-last-command-event)
      (setq last-nonmenu-event debugger-outer-last-nonmenu-event)
      (setq last-event-frame debugger-outer-last-event-frame)
      (setq standard-input debugger-outer-standard-input)
      (setq standard-output debugger-outer-standard-output)
      (setq inhibit-redisplay debugger-outer-inhibit-redisplay)
      (setq cursor-in-echo-area debugger-outer-cursor-in-echo-area)
      (setq debug-on-next-call debugger-step-after-exit)
      debugger-value)))
Jim Blandy's avatar
Jim Blandy committed
285

286 287 288 289 290
(defun debugger-setup-buffer (debugger-args)
  "Initialize the `*Backtrace*' buffer for entry to the debugger.
That buffer should be current already."
  (setq buffer-read-only nil)
  (erase-buffer)
291
  (set-buffer-multibyte t)		;Why was it nil ?  -stef
292
  (setq buffer-undo-list t)
293 294 295 296 297 298 299 300 301
  (let ((standard-output (current-buffer))
	(print-escape-newlines t)
	(print-level 8)
	(print-length 50))
    (backtrace))
  (goto-char (point-min))
  (delete-region (point)
		 (progn
		   (search-forward "\n  debug(")
302
		   (forward-line (if (eq (car debugger-args) 'debug)
Lute Kamstra's avatar
Lute Kamstra committed
303
				     2	; Remove implement-debug-on-entry frame.
304
				   1))
305 306 307 308
		   (point)))
  (insert "Debugger entered")
  ;; lambda is for debug-on-call when a function call is next.
  ;; debug is for debug-on-entry function called.
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  (pcase (car debugger-args)
    ((or `lambda `debug)
     (insert "--entering a function:\n"))
    ;; Exiting a function.
    (`exit
     (insert "--returning value: ")
     (setq debugger-value (nth 1 debugger-args))
     (prin1 debugger-value (current-buffer))
     (insert ?\n)
     (delete-char 1)
     (insert ? )
     (beginning-of-line))
    ;; Debugger entered for an error.
    (`error
     (insert "--Lisp error: ")
     (prin1 (nth 1 debugger-args) (current-buffer))
     (insert ?\n))
    ;; debug-on-call, when the next thing is an eval.
    (`t
     (insert "--beginning evaluation of function call form:\n"))
    ;; User calls debug directly.
    (_
     (insert ": ")
     (prin1 (if (eq (car debugger-args) 'nil)
                (cdr debugger-args) debugger-args)
            (current-buffer))
     (insert ?\n)))
336 337 338
  ;; After any frame that uses eval-buffer,
  ;; insert a line that states the buffer position it's reading at.
  (save-excursion
339 340 341 342 343 344 345 346 347 348 349
    (let ((tem eval-buffer-list))
      (while (and tem
		  (re-search-forward "^  eval-\\(buffer\\|region\\)(" nil t))
	(end-of-line)
	(insert (format "  ; Reading at buffer position %d"
			;; This will get the wrong result
			;; if there are two nested eval-region calls
			;; for the same buffer.  That's not a very useful case.
			(with-current-buffer (car tem)
			  (point))))
	(pop tem))))
350 351 352
  (debugger-make-xrefs))

(defun debugger-make-xrefs (&optional buffer)
353
  "Attach cross-references to function names in the `*Backtrace*' buffer."
354
  (interactive "b")
355
  (with-current-buffer (or buffer (current-buffer))
356 357 358
    (save-excursion
      (setq buffer (current-buffer))
      (let ((inhibit-read-only t)
Glenn Morris's avatar
Glenn Morris committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	    (old-end (point-min)) (new-end (point-min)))
	;; If we saved an old backtrace, find the common part
	;; between the new and the old.
	;; Compare line by line, starting from the end,
	;; because that's the part that is likely to be unchanged.
	(if debugger-previous-backtrace
	    (let (old-start new-start (all-match t))
	      (goto-char (point-max))
	      (with-temp-buffer
		(insert debugger-previous-backtrace)
		(while (and all-match (not (bobp)))
		  (setq old-end (point))
		  (forward-line -1)
		  (setq old-start (point))
		  (with-current-buffer buffer
		    (setq new-end (point))
		    (forward-line -1)
		    (setq new-start (point)))
		  (if (not (zerop
			    (let ((case-fold-search nil))
			      (compare-buffer-substrings
			       (current-buffer) old-start old-end
			       buffer new-start new-end))))
		      (setq all-match nil))))
	      ;; Now new-end is the position of the start of the
	      ;; unchanged part in the current buffer, and old-end is
	      ;; the position of that same text in the saved old
	      ;; backtrace.  But we must subtract (point-min) since strings are
	      ;; indexed in origin 0.
388

Glenn Morris's avatar
Glenn Morris committed
389 390 391 392 393 394 395 396 397 398 399 400
	      ;; Replace the unchanged part of the backtrace
	      ;; with the text from debugger-previous-backtrace,
	      ;; since that already has the proper xrefs.
	      ;; With this optimization, we only need to scan
	      ;; the changed part of the backtrace.
	      (delete-region new-end (point-max))
	      (goto-char (point-max))
	      (insert (substring debugger-previous-backtrace
				 (- old-end (point-min))))
	      ;; Make the unchanged part of the backtrace inaccessible
	      ;; so it won't be scanned.
	      (narrow-to-region (point-min) new-end)))
401

Glenn Morris's avatar
Glenn Morris committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
	;; Scan the new part of the backtrace, inserting xrefs.
	(goto-char (point-min))
	(while (progn
		 (goto-char (+ (point) 2))
		 (skip-syntax-forward "^w_")
		 (not (eobp)))
	  (let* ((beg (point))
		 (end (progn (skip-syntax-forward "w_") (point)))
		 (sym (intern-soft (buffer-substring-no-properties
				    beg end)))
		 (file (and sym (symbol-file sym 'defun))))
	    (when file
	      (goto-char beg)
	      ;; help-xref-button needs to operate on something matched
	      ;; by a regexp, so set that up for it.
	      (re-search-forward "\\(\\sw\\|\\s_\\)+")
	      (help-xref-button 0 'help-function-def sym file)))
	  (forward-line 1))
	(widen))
421
      (setq debugger-previous-backtrace (buffer-string)))))
422

Jim Blandy's avatar
Jim Blandy committed
423 424 425 426 427
(defun debugger-step-through ()
  "Proceed, stepping through subexpressions of this expression.
Enter another debugger on next entry to eval, apply or funcall."
  (interactive)
  (setq debugger-step-after-exit t)
428
  (setq debugger-jumping-flag t)
429
  (setq debugger-will-be-back t)
430
  (add-hook 'post-command-hook 'debugger-reenable)
Jim Blandy's avatar
Jim Blandy committed
431 432 433 434 435 436
  (message "Proceeding, will debug on next eval or call.")
  (exit-recursive-edit))

(defun debugger-continue ()
  "Continue, evaluating this expression without stopping."
  (interactive)
437 438
  (unless debugger-may-continue
    (error "Cannot continue"))
Jim Blandy's avatar
Jim Blandy committed
439
  (message "Continuing.")
440 441 442 443 444 445
  (save-excursion
    ;; Check to see if we've flagged some frame for debug-on-exit, in which
    ;; case we'll probably come back to the debugger soon.
    (goto-char (point-min))
    (if (re-search-forward "^\\* " nil t)
        (setq debugger-will-be-back t)))
Jim Blandy's avatar
Jim Blandy committed
446 447 448 449 450 451 452
  (exit-recursive-edit))

(defun debugger-return-value (val)
  "Continue, specifying value to return.
This is only useful when the value returned from the debugger
will be used, such as in a debug on exit from a frame."
  (interactive "XReturn value (evaluated): ")
453 454 455 456
  (when (memq (car debugger-args) '(t lambda error debug))
    (error "Cannot return a value %s"
           (if (eq (car debugger-args) 'error)
               "from an error" "at function entrance")))
Jim Blandy's avatar
Jim Blandy committed
457 458 459
  (setq debugger-value val)
  (princ "Returning " t)
  (prin1 debugger-value)
460 461 462 463 464 465
  (save-excursion
    ;; Check to see if we've flagged some frame for debug-on-exit, in which
    ;; case we'll probably come back to the debugger soon.
    (goto-char (point-min))
    (if (re-search-forward "^\\* " nil t)
        (setq debugger-will-be-back t)))
Jim Blandy's avatar
Jim Blandy committed
466 467 468 469 470
  (exit-recursive-edit))

(defun debugger-jump ()
  "Continue to exit from this frame, with all debug-on-entry suspended."
  (interactive)
471
  (debugger-frame)
472 473
  (setq debugger-jumping-flag t)
  (add-hook 'post-command-hook 'debugger-reenable)
Jim Blandy's avatar
Jim Blandy committed
474
  (message "Continuing through this frame")
475
  (setq debugger-will-be-back t)
Jim Blandy's avatar
Jim Blandy committed
476 477 478
  (exit-recursive-edit))

(defun debugger-reenable ()
479 480 481 482 483
  "Turn all debug-on-entry functions back on.
This function is put on `post-command-hook' by `debugger-jump' and
removes itself from that hook."
  (setq debugger-jumping-flag nil)
  (remove-hook 'post-command-hook 'debugger-reenable))
Jim Blandy's avatar
Jim Blandy committed
484 485 486 487 488 489 490

(defun debugger-frame-number ()
  "Return number of frames in backtrace before the one point points at."
  (save-excursion
    (beginning-of-line)
    (let ((opoint (point))
	  (count 0))
491 492
      (while (not (eq (cadr (backtrace-frame count)) 'debug))
	(setq count (1+ count)))
Lute Kamstra's avatar
Lute Kamstra committed
493 494
      ;; Skip implement-debug-on-entry frame.
      (when (eq 'implement-debug-on-entry (cadr (backtrace-frame (1+ count))))
495
	(setq count (1+ count)))
Jim Blandy's avatar
Jim Blandy committed
496
      (goto-char (point-min))
497 498 499
      (when (looking-at "Debugger entered--\\(Lisp error\\|returning value\\):")
	(goto-char (match-end 0))
	(forward-sexp 1))
Jim Blandy's avatar
Jim Blandy committed
500 501 502 503 504 505 506 507
      (forward-line 1)
      (while (progn
	       (forward-char 2)
	       (if (= (following-char) ?\()
		   (forward-sexp 1)
		 (forward-sexp 2))
	       (forward-line 1)
	       (<= (point) opoint))
508 509
	(if (looking-at " *;;;")
	    (forward-line 1))
Jim Blandy's avatar
Jim Blandy committed
510 511 512 513 514 515 516
	(setq count (1+ count)))
      count)))

(defun debugger-frame ()
  "Request entry to debugger when this frame exits.
Applies to the frame whose line point is on in the backtrace."
  (interactive)
517 518 519 520
  (save-excursion
    (beginning-of-line)
    (if (looking-at " *;;;\\|[a-z]")
	(error "This line is not a function call")))
Jim Blandy's avatar
Jim Blandy committed
521
  (beginning-of-line)
522
  (backtrace-debug (debugger-frame-number) t)
Jim Blandy's avatar
Jim Blandy committed
523
  (if (= (following-char) ? )
524
      (let ((inhibit-read-only t))
Jim Blandy's avatar
Jim Blandy committed
525 526 527 528 529
	(delete-char 1)
	(insert ?*)))
  (beginning-of-line))

(defun debugger-frame-clear ()
530
  "Do not enter debugger when this frame exits.
Jim Blandy's avatar
Jim Blandy committed
531 532
Applies to the frame whose line point is on in the backtrace."
  (interactive)
533 534 535 536
  (save-excursion
    (beginning-of-line)
    (if (looking-at " *;;;\\|[a-z]")
	(error "This line is not a function call")))
Jim Blandy's avatar
Jim Blandy committed
537
  (beginning-of-line)
538
  (backtrace-debug (debugger-frame-number) nil)
Jim Blandy's avatar
Jim Blandy committed
539
  (if (= (following-char) ?*)
540
      (let ((inhibit-read-only t))
Jim Blandy's avatar
Jim Blandy committed
541 542 543 544
	(delete-char 1)
	(insert ? )))
  (beginning-of-line))

545 546
(defmacro debugger-env-macro (&rest body)
  "Run BODY in original environment."
Stefan Monnier's avatar
Stefan Monnier committed
547
  (declare (indent 0))
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
  `(save-excursion
    (if (null (buffer-name debugger-old-buffer))
        ;; old buffer deleted
        (setq debugger-old-buffer (current-buffer)))
    (set-buffer debugger-old-buffer)
    (let ((load-read-function debugger-outer-load-read-function)
          (overriding-terminal-local-map
           debugger-outer-overriding-terminal-local-map)
          (overriding-local-map debugger-outer-overriding-local-map)
          (track-mouse debugger-outer-track-mouse)
          (last-command debugger-outer-last-command)
          (this-command debugger-outer-this-command)
          (unread-command-events debugger-outer-unread-command-events)
          (unread-post-input-method-events
           debugger-outer-unread-post-input-method-events)
          (last-input-event debugger-outer-last-input-event)
          (last-command-event debugger-outer-last-command-event)
          (last-nonmenu-event debugger-outer-last-nonmenu-event)
          (last-event-frame debugger-outer-last-event-frame)
          (standard-input debugger-outer-standard-input)
          (standard-output debugger-outer-standard-output)
          (inhibit-redisplay debugger-outer-inhibit-redisplay)
          (cursor-in-echo-area debugger-outer-cursor-in-echo-area))
      (set-match-data debugger-outer-match-data)
572 573 574 575 576
      (prog1
	  (let ((save-ucc (with-no-warnings unread-command-char)))
	    (unwind-protect
		(progn
		  (with-no-warnings
577
		    (setq unread-command-char debugger-outer-unread-command-char))
578 579
		  (prog1 (progn ,@body)
		    (with-no-warnings
580
		      (setq debugger-outer-unread-command-char unread-command-char))))
581
	      (with-no-warnings
582
		(setq unread-command-char save-ucc))))
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        (setq debugger-outer-match-data (match-data))
        (setq debugger-outer-load-read-function load-read-function)
        (setq debugger-outer-overriding-terminal-local-map
              overriding-terminal-local-map)
        (setq debugger-outer-overriding-local-map overriding-local-map)
        (setq debugger-outer-track-mouse track-mouse)
        (setq debugger-outer-last-command last-command)
        (setq debugger-outer-this-command this-command)
        (setq debugger-outer-unread-command-events unread-command-events)
        (setq debugger-outer-unread-post-input-method-events
              unread-post-input-method-events)
        (setq debugger-outer-last-input-event last-input-event)
        (setq debugger-outer-last-command-event last-command-event)
        (setq debugger-outer-last-nonmenu-event last-nonmenu-event)
        (setq debugger-outer-last-event-frame last-event-frame)
        (setq debugger-outer-standard-input standard-input)
        (setq debugger-outer-standard-output standard-output)
        (setq debugger-outer-inhibit-redisplay inhibit-redisplay)
        (setq debugger-outer-cursor-in-echo-area cursor-in-echo-area)
        ))))
603

Jim Blandy's avatar
Jim Blandy committed
604
(defun debugger-eval-expression (exp)
605 606 607 608 609
  "Eval an expression, in an environment like that outside the debugger."
  (interactive
   (list (read-from-minibuffer "Eval: "
			       nil read-expression-map t
			       'read-expression-history)))
610
  (debugger-env-macro (eval-expression exp)))
Jim Blandy's avatar
Jim Blandy committed
611

612
(defvar debugger-mode-map
613 614
  (let ((map (make-keymap))
	(menu-map (make-sparse-keymap)))
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
    (set-keymap-parent map button-buffer-map)
    (suppress-keymap map)
    (define-key map "-" 'negative-argument)
    (define-key map "b" 'debugger-frame)
    (define-key map "c" 'debugger-continue)
    (define-key map "j" 'debugger-jump)
    (define-key map "r" 'debugger-return-value)
    (define-key map "u" 'debugger-frame-clear)
    (define-key map "d" 'debugger-step-through)
    (define-key map "l" 'debugger-list-functions)
    (define-key map "h" 'describe-mode)
    (define-key map "q" 'top-level)
    (define-key map "e" 'debugger-eval-expression)
    (define-key map " " 'next-line)
    (define-key map "R" 'debugger-record-expression)
630
    (define-key map "\C-m" 'debug-help-follow)
631
    (define-key map [mouse-2] 'push-button)
632 633 634
    (define-key map [menu-bar debugger] (cons "Debugger" menu-map))
    (define-key menu-map [deb-top]
      '(menu-item "Quit" top-level
Dan Nicolaescu's avatar
Dan Nicolaescu committed
635
		  :help "Quit debugging and return to top level"))
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
    (define-key menu-map [deb-s0] '("--"))
    (define-key menu-map [deb-descr]
      '(menu-item "Describe Debugger Mode" describe-mode
		  :help "Display documentation for debugger-mode"))
    (define-key menu-map [deb-hfol]
      '(menu-item "Help Follow" debug-help-follow
		  :help "Follow cross-reference"))
    (define-key menu-map [deb-nxt]
      '(menu-item "Next Line" next-line
		  :help "Move cursor down"))
    (define-key menu-map [deb-s1] '("--"))
    (define-key menu-map [deb-lfunc]
      '(menu-item "List debug on entry functions" debugger-list-functions
		  :help "Display a list of all the functions now set to debug on entry"))
    (define-key menu-map [deb-fclear]
      '(menu-item "Cancel debug frame" debugger-frame-clear
		  :help "Do not enter debugger when this frame exits"))
    (define-key menu-map [deb-frame]
      '(menu-item "Debug frame" debugger-frame
		  :help "Request entry to debugger when this frame exits"))
    (define-key menu-map [deb-s2] '("--"))
    (define-key menu-map [deb-ret]
      '(menu-item "Return value..." debugger-return-value
		  :help "Continue, specifying value to return."))
    (define-key menu-map [deb-rec]
      '(menu-item "Display and Record Expression" debugger-record-expression
		  :help "Display a variable's value and record it in `*Backtrace-record*' buffer"))
    (define-key menu-map [deb-eval]
      '(menu-item "Eval Expression..." debugger-eval-expression
		  :help "Eval an expression, in an environment like that outside the debugger"))
    (define-key menu-map [deb-jump]
      '(menu-item "Jump" debugger-jump
		  :help "Continue to exit from this frame, with all debug-on-entry suspended"))
    (define-key menu-map [deb-cont]
      '(menu-item "Continue" debugger-continue
		  :help "Continue, evaluating this expression without stopping"))
    (define-key menu-map [deb-step]
      '(menu-item "Step through" debugger-step-through
		  :help "Proceed, stepping through subexpressions of this expression"))
675
    map))
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700

(put 'debugger-mode 'mode-class 'special)

(defun debugger-mode ()
  "Mode for backtrace buffers, selected in debugger.
\\<debugger-mode-map>
A line starts with `*' if exiting that frame will call the debugger.
Type \\[debugger-frame] or \\[debugger-frame-clear] to set or remove the `*'.

When in debugger due to frame being exited,
use the \\[debugger-return-value] command to override the value
being returned from that frame.

Use \\[debug-on-entry] and \\[cancel-debug-on-entry] to control
which functions will enter the debugger when called.

Complete list of commands:
\\{debugger-mode-map}"
  (kill-all-local-variables)
  (setq major-mode 'debugger-mode)
  (setq mode-name "Debugger")
  (setq truncate-lines t)
  (set-syntax-table emacs-lisp-mode-syntax-table)
  (use-local-map debugger-mode-map)
  (run-mode-hooks 'debugger-mode-hook))
701

Stephen Eglen's avatar
Stephen Eglen committed
702
(defcustom debugger-record-buffer "*Debugger-record*"
703
  "Buffer name for expression values, for \\[debugger-record-expression]."
Stephen Eglen's avatar
Stephen Eglen committed
704
  :type 'string
Dan Nicolaescu's avatar
Dan Nicolaescu committed
705 706
  :group 'debugger
  :version "20.3")
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

(defun debugger-record-expression  (exp)
  "Display a variable's value and record it in `*Backtrace-record*' buffer."
  (interactive
   (list (read-from-minibuffer
	  "Record Eval: "
	  nil
	  read-expression-map t
	  'read-expression-history)))
  (let* ((buffer (get-buffer-create debugger-record-buffer))
	 (standard-output buffer))
    (princ (format "Debugger Eval (%s): " exp))
    (princ (debugger-eval-expression exp))
    (terpri))

  (with-current-buffer (get-buffer debugger-record-buffer)
723
    (message "%s"
724 725
	     (buffer-substring (line-beginning-position 0)
			       (line-end-position 0)))))
Jim Blandy's avatar
Jim Blandy committed
726

Glenn Morris's avatar
Glenn Morris committed
727 728
(declare-function help-xref-interned "help-mode" (symbol))

729 730 731 732 733 734
(defun debug-help-follow (&optional pos)
  "Follow cross-reference at POS, defaulting to point.

For the cross-reference format, see `help-make-xrefs'."
  (interactive "d")
  (require 'help-mode)
735 736 737
  ;; Ideally we'd just do (call-interactively 'help-follow) except that this
  ;; assumes we're already in a *Help* buffer and reuses it, so it ends up
  ;; incorrectly "reusing" the *Backtrace* buffer to show the help info.
738 739 740 741 742 743 744 745 746 747 748 749
  (unless pos
    (setq pos (point)))
  (unless (push-button pos)
    ;; check if the symbol under point is a function or variable
    (let ((sym
	   (intern
	    (save-excursion
	      (goto-char pos) (skip-syntax-backward "w_")
	      (buffer-substring (point)
				(progn (skip-syntax-forward "w_")
				       (point)))))))
      (when (or (boundp sym) (fboundp sym) (facep sym))
750
        (help-xref-interned sym)))))
Jim Blandy's avatar
Jim Blandy committed
751

Lute Kamstra's avatar
Lute Kamstra committed
752 753 754 755 756 757 758 759 760 761
;; When you change this, you may also need to change the number of
;; frames that the debugger skips.
(defun implement-debug-on-entry ()
  "Conditionally call the debugger.
A call to this function is inserted by `debug-on-entry' to cause
functions to break on entry."
  (if (or inhibit-debug-on-entry debugger-jumping-flag)
      nil
    (funcall debugger 'debug)))

762 763 764 765 766 767
(defun debugger-special-form-p (symbol)
  "Return whether SYMBOL is a special form."
  (and (fboundp symbol)
       (subrp (symbol-function symbol))
       (eq (cdr (subr-arity (symbol-function symbol))) 'unevalled)))

Jim Blandy's avatar
Jim Blandy committed
768 769 770
;;;###autoload
(defun debug-on-entry (function)
  "Request FUNCTION to invoke debugger each time it is called.
771

772
When called interactively, prompt for FUNCTION in the minibuffer.
773 774 775 776 777 778 779 780

This works by modifying the definition of FUNCTION.  If you tell the
debugger to continue, FUNCTION's execution proceeds.  If FUNCTION is a
normal function or a macro written in Lisp, you can also step through
its execution.  FUNCTION can also be a primitive that is not a special
form, in which case stepping is not possible.  Break-on-entry for
primitive functions only works when that function is called from Lisp.

Jim Blandy's avatar
Jim Blandy committed
781
Use \\[cancel-debug-on-entry] to cancel the effect of this command.
782
Redefining FUNCTION also cancels it."
783 784 785 786
  (interactive
   (let ((fn (function-called-at-point)) val)
     (when (debugger-special-form-p fn)
       (setq fn nil))
787
     (setq val (completing-read
788 789 790 791 792 793 794 795 796
		(if fn
		    (format "Debug on entry to function (default %s): " fn)
		  "Debug on entry to function: ")
		obarray
		#'(lambda (symbol)
		    (and (fboundp symbol)
			 (not (debugger-special-form-p symbol))))
		t nil nil (symbol-name fn)))
     (list (if (equal val "") fn (intern val)))))
797
  ;; FIXME: Use advice.el.
798
  (when (debugger-special-form-p function)
799
    (error "Function %s is a special form" function))
800
  (if (or (symbolp (symbol-function function))
801
	  (subrp (symbol-function function)))
802 803
      ;; The function is built-in or aliased to another function.
      ;; Create a wrapper in which we can add the debug call.
804
      (fset function `(lambda (&rest debug-on-entry-args)
805
			,(interactive-form (symbol-function function))
806
			(apply ',(symbol-function function)
807 808 809 810 811 812 813 814 815 816 817 818
			       debug-on-entry-args)))
    (when (eq (car-safe (symbol-function function)) 'autoload)
      ;; The function is autoloaded.  Load its real definition.
      (load (cadr (symbol-function function)) nil noninteractive nil t))
    (when (or (not (consp (symbol-function function)))
	      (and (eq (car (symbol-function function)) 'macro)
		   (not (consp (cdr (symbol-function function))))))
      ;; The function is byte-compiled.  Create a wrapper in which
      ;; we can add the debug call.
      (debug-convert-byte-code function)))
  (unless (consp (symbol-function function))
    (error "Definition of %s is not a list" function))
Lute Kamstra's avatar
Lute Kamstra committed
819
  (fset function (debug-on-entry-1 function t))
820 821
  (unless (memq function debug-function-list)
    (push function debug-function-list))
Jim Blandy's avatar
Jim Blandy committed
822 823 824 825 826
  function)

;;;###autoload
(defun cancel-debug-on-entry (&optional function)
  "Undo effect of \\[debug-on-entry] on FUNCTION.
827
If FUNCTION is nil, cancel debug-on-entry for all functions.
828 829
When called interactively, prompt for FUNCTION in the minibuffer.
To specify a nil argument interactively, exit with an empty minibuffer."
Jim Blandy's avatar
Jim Blandy committed
830 831
  (interactive
   (list (let ((name
832
		(completing-read
833
		 "Cancel debug on entry to function (default all functions): "
834
		 (mapcar 'symbol-name debug-function-list) nil t)))
835 836 837 838 839
	   (when name
	     (unless (string= name "")
	       (intern name))))))
  (if (and function
	   (not (string= function ""))) ; Pre 22.1 compatibility test.
Jim Blandy's avatar
Jim Blandy committed
840
      (progn
841
	(let ((defn (debug-on-entry-1 function nil)))
842
	  (condition-case nil
843 844 845 846 847
	      (when (and (equal (nth 1 defn) '(&rest debug-on-entry-args))
			 (eq (car (nth 3 defn)) 'apply))
		;; `defn' is a wrapper introduced in debug-on-entry.
		;; Get rid of it since we don't need it any more.
		(setq defn (nth 1 (nth 1 (nth 3 defn)))))
848
	    (error nil))
849
	  (fset function defn))
Jim Blandy's avatar
Jim Blandy committed
850 851 852 853 854
	(setq debug-function-list (delq function debug-function-list))
	function)
    (message "Cancelling debug-on-entry for all functions")
    (mapcar 'cancel-debug-on-entry debug-function-list)))

855 856 857 858 859 860
(defun debug-arglist (definition)
  ;; FIXME: copied from ad-arglist.
  "Return the argument list of DEFINITION."
  (require 'help-fns)
  (help-function-arglist definition 'preserve-names))

Jim Blandy's avatar
Jim Blandy committed
861
(defun debug-convert-byte-code (function)
862 863 864
  (let* ((defn (symbol-function function))
	 (macro (eq (car-safe defn) 'macro)))
    (when macro (setq defn (cdr defn)))
865 866
    (when (byte-code-function-p defn)
      (let* ((args (debug-arglist defn))
867
	     (body
868 869 870 871
              `((,(if (memq '&rest args) #'apply #'funcall)
                 ,defn
                 ,@(remq '&rest (remq '&optional args))))))
	(if (> (length defn) 5)
872 873
            ;; The mere presence of field 5 is sufficient to make
            ;; it interactive.
874
	    (push `(interactive ,(aref defn 5)) body))
875
	(if (and (> (length defn) 4) (aref defn 4))
876 877 878 879
	    ;; Use `documentation' here, to get the actual string,
	    ;; in case the compiled function has a reference
	    ;; to the .elc file.
	    (setq body (cons (documentation function) body)))
880
	(setq defn `(closure (t) ,args ,@body)))
881 882
      (when macro (setq defn (cons 'macro defn)))
      (fset function defn))))
Jim Blandy's avatar
Jim Blandy committed
883

Lute Kamstra's avatar
Lute Kamstra committed
884 885 886
(defun debug-on-entry-1 (function flag)
  (let* ((defn (symbol-function function))
	 (tail defn))
887
    (when (eq (car-safe tail) 'macro)
888
      (setq tail (cdr tail)))
889
    (if (not (memq (car-safe tail) '(closure lambda)))
890 891 892 893
	;; Only signal an error when we try to set debug-on-entry.
	;; When we try to clear debug-on-entry, we are now done.
	(when flag
	  (error "%s is not a user-defined Lisp function" function))
894
      (if (eq (car tail) 'closure) (setq tail (cdr tail)))
895
      (setq tail (cdr tail))
896 897 898 899 900 901
      ;; Skip the docstring.
      (when (and (stringp (cadr tail)) (cddr tail))
	(setq tail (cdr tail)))
      ;; Skip the interactive form.
      (when (eq 'interactive (car-safe (cadr tail)))
	(setq tail (cdr tail)))
Lute Kamstra's avatar
Lute Kamstra committed
902
      (unless (eq flag (equal (cadr tail) '(implement-debug-on-entry)))
903
	;; Add/remove debug statement as needed.
904 905 906
	(setcdr tail (if flag
                         (cons '(implement-debug-on-entry) (cdr tail))
                       (cddr tail)))))
907
    defn))
Jim Blandy's avatar
Jim Blandy committed
908 909 910 911

(defun debugger-list-functions ()
  "Display a list of all the functions now set to debug on entry."
  (interactive)
912
  (require 'help-mode)
913 914
  (help-setup-xref '(debugger-list-functions)
		   (called-interactively-p 'interactive))
915 916 917 918 919 920 921 922 923 924 925 926 927
  (with-output-to-temp-buffer (help-buffer)
    (with-current-buffer standard-output
      (if (null debug-function-list)
	  (princ "No debug-on-entry functions now\n")
	(princ "Functions set to debug on entry:\n\n")
	(dolist (fun debug-function-list)
	  (make-text-button (point) (progn (prin1 fun) (point))
			    'type 'help-function
			    'help-args (list fun))
	  (terpri))
	(terpri)
	(princ "Note: if you have redefined a function, then it may no longer\n")
	(princ "be set to debug on entry, even if it is in the list.")))))
Eric S. Raymond's avatar
Eric S. Raymond committed
928

Richard M. Stallman's avatar
Richard M. Stallman committed
929 930
(provide 'debug)

Eric S. Raymond's avatar
Eric S. Raymond committed
931
;;; debug.el ends here