* admin/gitmerge.el (gitmerge-missing):
[emacs.git] / doc / lispref / debugging.texi
blobfe3446ada2d83732349717af541fb61468760e5e
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1994, 1998-1999, 2001-2017 Free Software
4 @c Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @node Debugging
7 @chapter Debugging Lisp Programs
8 @cindex debugging lisp programs
10   There are several ways to find and investigate problems in an Emacs
11 Lisp program.
13 @itemize @bullet
14 @item
15 If a problem occurs when you run the program, you can use the built-in
16 Emacs Lisp debugger to suspend the Lisp evaluator, and examine and/or
17 alter its internal state.
19 @item
20 You can use Edebug, a source-level debugger for Emacs Lisp.
22 @item
23 If a syntactic problem is preventing Lisp from even reading the
24 program, you can locate it using Lisp editing commands.
26 @item
27 You can look at the error and warning messages produced by the byte
28 compiler when it compiles the program.  @xref{Compiler Errors}.
30 @item
31 You can use the Testcover package to perform coverage testing on the
32 program.
34 @item
35 You can use the ERT package to write regression tests for the program.
36 @xref{Top,the ERT manual,, ert, ERT: Emacs Lisp Regression Testing}.
38 @item
39 You can profile the program to get hints about how to make it more efficient.
40 @end itemize
42   Other useful tools for debugging input and output problems are the
43 dribble file (@pxref{Terminal Input}) and the @code{open-termscript}
44 function (@pxref{Terminal Output}).
46 @menu
47 * Debugger::            A debugger for the Emacs Lisp evaluator.
48 * Edebug::              A source-level Emacs Lisp debugger.
49 * Syntax Errors::       How to find syntax errors.
50 * Test Coverage::       Ensuring you have tested all branches in your code.
51 * Profiling::           Measuring the resources that your code uses.
52 @end menu
54 @node Debugger
55 @section The Lisp Debugger
56 @cindex debugger for Emacs Lisp
57 @cindex Lisp debugger
58 @cindex break
60   The ordinary @dfn{Lisp debugger} provides the ability to suspend
61 evaluation of a form.  While evaluation is suspended (a state that is
62 commonly known as a @dfn{break}), you may examine the run time stack,
63 examine the values of local or global variables, or change those values.
64 Since a break is a recursive edit, all the usual editing facilities of
65 Emacs are available; you can even run programs that will enter the
66 debugger recursively.  @xref{Recursive Editing}.
68 @menu
69 * Error Debugging::       Entering the debugger when an error happens.
70 * Infinite Loops::        Stopping and debugging a program that doesn't exit.
71 * Function Debugging::    Entering it when a certain function is called.
72 * Variable Debugging::    Entering it when a variable is modified.
73 * Explicit Debug::        Entering it at a certain point in the program.
74 * Using Debugger::        What the debugger does; what you see while in it.
75 * Debugger Commands::     Commands used while in the debugger.
76 * Invoking the Debugger:: How to call the function @code{debug}.
77 * Internals of Debugger:: Subroutines of the debugger, and global variables.
78 @end menu
80 @node Error Debugging
81 @subsection Entering the Debugger on an Error
82 @cindex error debugging
83 @cindex debugging errors
85   The most important time to enter the debugger is when a Lisp error
86 happens.  This allows you to investigate the immediate causes of the
87 error.
89   However, entry to the debugger is not a normal consequence of an
90 error.  Many commands signal Lisp errors when invoked inappropriately,
91 and during ordinary editing it would be very inconvenient to enter the
92 debugger each time this happens.  So if you want errors to enter the
93 debugger, set the variable @code{debug-on-error} to non-@code{nil}.
94 (The command @code{toggle-debug-on-error} provides an easy way to do
95 this.)
97 @defopt debug-on-error
98 This variable determines whether the debugger is called when an error
99 is signaled and not handled.  If @code{debug-on-error} is @code{t},
100 all kinds of errors call the debugger, except those listed in
101 @code{debug-ignored-errors} (see below).  If it is @code{nil}, none
102 call the debugger.
104 The value can also be a list of error conditions (@pxref{Signaling
105 Errors}).  Then the debugger is called only for error conditions in
106 this list (except those also listed in @code{debug-ignored-errors}).
107 For example, if you set @code{debug-on-error} to the list
108 @code{(void-variable)}, the debugger is only called for errors about a
109 variable that has no value.
111 Note that @code{eval-expression-debug-on-error} overrides this
112 variable in some cases; see below.
114 When this variable is non-@code{nil}, Emacs does not create an error
115 handler around process filter functions and sentinels.  Therefore,
116 errors in these functions also invoke the debugger.  @xref{Processes}.
117 @end defopt
119 @defopt debug-ignored-errors
120 This variable specifies errors which should not enter the debugger,
121 regardless of the value of @code{debug-on-error}.  Its value is a list
122 of error condition symbols and/or regular expressions.  If the error
123 has any of those condition symbols, or if the error message matches
124 any of the regular expressions, then that error does not enter the
125 debugger.
127 The normal value of this variable includes @code{user-error}, as well
128 as several errors that happen often during editing but rarely result
129 from bugs in Lisp programs.  However, ``rarely'' is not ``never''; if
130 your program fails with an error that matches this list, you may try
131 changing this list to debug the error.  The easiest way is usually to
132 set @code{debug-ignored-errors} to @code{nil}.
133 @end defopt
135 @defopt eval-expression-debug-on-error
136 If this variable has a non-@code{nil} value (the default), running the
137 command @code{eval-expression} causes @code{debug-on-error} to be
138 temporarily bound to @code{t}.  @xref{Lisp Eval,, Evaluating
139 Emacs-Lisp Expressions, emacs, The GNU Emacs Manual}.
141 If @code{eval-expression-debug-on-error} is @code{nil}, then the value
142 of @code{debug-on-error} is not changed during @code{eval-expression}.
143 @end defopt
145 @defopt debug-on-signal
146 Normally, errors caught by @code{condition-case} never invoke the
147 debugger.  The @code{condition-case} gets a chance to handle the error
148 before the debugger gets a chance.
150 If you change @code{debug-on-signal} to a non-@code{nil} value, the
151 debugger gets the first chance at every error, regardless of the
152 presence of @code{condition-case}.  (To invoke the debugger, the error
153 must still fulfill the criteria specified by @code{debug-on-error} and
154 @code{debug-ignored-errors}.)
156 @cindex emacsclient, getting a backtrace
157 @cindex backtrace from emacsclient's @option{--eval}
158 For example, setting this variable is useful to get a backtrace from
159 code evaluated by emacsclient's @option{--eval} option.  If Lisp code
160 evaluated by emacsclient signals an error while this variable is
161 non-@code{nil}, the backtrace will popup in the running Emacs.
163 @strong{Warning:} Setting this variable to non-@code{nil} may have
164 annoying effects.  Various parts of Emacs catch errors in the normal
165 course of affairs, and you may not even realize that errors happen
166 there.  If you need to debug code wrapped in @code{condition-case},
167 consider using @code{condition-case-unless-debug} (@pxref{Handling
168 Errors}).
169 @end defopt
171 @defopt debug-on-event
172 If you set @code{debug-on-event} to a special event (@pxref{Special
173 Events}), Emacs will try to enter the debugger as soon as it receives
174 this event, bypassing @code{special-event-map}.  At present, the only
175 supported values correspond to the signals @code{SIGUSR1} and
176 @code{SIGUSR2} (this is the default).  This can be helpful when
177 @code{inhibit-quit} is set and Emacs is not otherwise responding.
178 @end defopt
180 @cindex message, finding what causes a particular message
181 @defvar debug-on-message
182 If you set @code{debug-on-message} to a regular expression,
183 Emacs will enter the debugger if it displays a matching message in the
184 echo area.  For example, this can be useful when trying to find the
185 cause of a particular message.
186 @end defvar
188   To debug an error that happens during loading of the init
189 file, use the option @samp{--debug-init}.  This binds
190 @code{debug-on-error} to @code{t} while loading the init file, and
191 bypasses the @code{condition-case} which normally catches errors in the
192 init file.
194 @node Infinite Loops
195 @subsection Debugging Infinite Loops
196 @cindex infinite loops
197 @cindex loops, infinite
198 @cindex quitting from infinite loop
199 @cindex stopping an infinite loop
201   When a program loops infinitely and fails to return, your first
202 problem is to stop the loop.  On most operating systems, you can do
203 this with @kbd{C-g}, which causes a @dfn{quit}.  @xref{Quitting}.
205   Ordinary quitting gives no information about why the program was
206 looping.  To get more information, you can set the variable
207 @code{debug-on-quit} to non-@code{nil}.  Once you have the debugger
208 running in the middle of the infinite loop, you can proceed from the
209 debugger using the stepping commands.  If you step through the entire
210 loop, you may get enough information to solve the problem.
212   Quitting with @kbd{C-g} is not considered an error, and
213 @code{debug-on-error} has no effect on the handling of @kbd{C-g}.
214 Likewise, @code{debug-on-quit} has no effect on errors.
216 @defopt debug-on-quit
217 This variable determines whether the debugger is called when
218 @code{quit} is signaled and not handled.  If @code{debug-on-quit} is
219 non-@code{nil}, then the debugger is called whenever you quit (that
220 is, type @kbd{C-g}).  If @code{debug-on-quit} is @code{nil} (the
221 default), then the debugger is not called when you quit.
222 @end defopt
224 @node Function Debugging
225 @subsection Entering the Debugger on a Function Call
226 @cindex function call debugging
227 @cindex debugging specific functions
229   To investigate a problem that happens in the middle of a program, one
230 useful technique is to enter the debugger whenever a certain function is
231 called.  You can do this to the function in which the problem occurs,
232 and then step through the function, or you can do this to a function
233 called shortly before the problem, step quickly over the call to that
234 function, and then step through its caller.
236 @deffn Command debug-on-entry function-name
237 This function requests @var{function-name} to invoke the debugger each
238 time it is called.
240 Any function or macro defined as Lisp code may be set to break on
241 entry, regardless of whether it is interpreted code or compiled code.
242 If the function is a command, it will enter the debugger when called
243 from Lisp and when called interactively (after the reading of the
244 arguments).  You can also set debug-on-entry for primitive functions
245 (i.e., those written in C) this way, but it only takes effect when the
246 primitive is called from Lisp code.  Debug-on-entry is not allowed for
247 special forms.
249 When @code{debug-on-entry} is called interactively, it prompts for
250 @var{function-name} in the minibuffer.  If the function is already set
251 up to invoke the debugger on entry, @code{debug-on-entry} does nothing.
252 @code{debug-on-entry} always returns @var{function-name}.
254 Here's an example to illustrate use of this function:
256 @example
257 @group
258 (defun fact (n)
259   (if (zerop n) 1
260       (* n (fact (1- n)))))
261      @result{} fact
262 @end group
263 @group
264 (debug-on-entry 'fact)
265      @result{} fact
266 @end group
267 @group
268 (fact 3)
269 @end group
271 @group
272 ------ Buffer: *Backtrace* ------
273 Debugger entered--entering a function:
274 * fact(3)
275   eval((fact 3))
276   eval-last-sexp-1(nil)
277   eval-last-sexp(nil)
278   call-interactively(eval-last-sexp)
279 ------ Buffer: *Backtrace* ------
280 @end group
282 @end example
283 @end deffn
285 @deffn Command cancel-debug-on-entry &optional function-name
286 This function undoes the effect of @code{debug-on-entry} on
287 @var{function-name}.  When called interactively, it prompts for
288 @var{function-name} in the minibuffer.  If @var{function-name} is
289 omitted or @code{nil}, it cancels break-on-entry for all functions.
290 Calling @code{cancel-debug-on-entry} does nothing to a function which is
291 not currently set up to break on entry.
292 @end deffn
294 @node Variable Debugging
295 @subsection Entering the debugger when a variable is modified
296 @cindex variable write debugging
297 @cindex debugging changes to variables
299 Sometimes a problem with a function is due to a wrong setting of a
300 variable.  Setting up the debugger to trigger whenever the variable is
301 changed is a quick way to find the origin of the setting.
303 @deffn Command debug-on-variable-change variable
304 This function arranges for the debugger to be called whenever
305 @var{variable} is modified.
307 It is implemented using the watchpoint mechanism, so it inherits the
308 same characteristics and limitations: all aliases of @var{variable}
309 will be watched together, only dynamic variables can be watched, and
310 changes to the objects referenced by variables are not detected.  For
311 details, see @ref{Watching Variables}.
312 @end deffn
314 @deffn Command cancel-debug-on-variable-change &optional variable
315 This function undoes the effect of @code{debug-on-variable-change} on
316 @var{variable}.  When called interactively, it prompts for
317 @var{variable} in the minibuffer.  If @var{variable} is omitted or
318 @code{nil}, it cancels break-on-change for all variables.  Calling
319 @code{cancel-debug-on-variable-change} does nothing to a variable
320 which is not currently set up to break on change.
321 @end deffn
324 @node Explicit Debug
325 @subsection Explicit Entry to the Debugger
326 @cindex debugger, explicit entry
327 @cindex force entry to debugger
329   You can cause the debugger to be called at a certain point in your
330 program by writing the expression @code{(debug)} at that point.  To do
331 this, visit the source file, insert the text @samp{(debug)} at the
332 proper place, and type @kbd{C-M-x} (@code{eval-defun}, a Lisp mode key
333 binding).  @strong{Warning:} if you do this for temporary debugging
334 purposes, be sure to undo this insertion before you save the file!
336   The place where you insert @samp{(debug)} must be a place where an
337 additional form can be evaluated and its value ignored.  (If the value
338 of @code{(debug)} isn't ignored, it will alter the execution of the
339 program!)  The most common suitable places are inside a @code{progn} or
340 an implicit @code{progn} (@pxref{Sequencing}).
342   If you don't know exactly where in the source code you want to put
343 the debug statement, but you want to display a backtrace when a
344 certain message is displayed, you can set @code{debug-on-message} to a
345 regular expression matching the desired message.
347 @node Using Debugger
348 @subsection Using the Debugger
350   When the debugger is entered, it displays the previously selected
351 buffer in one window and a buffer named @file{*Backtrace*} in another
352 window.  The backtrace buffer contains one line for each level of Lisp
353 function execution currently going on.  At the beginning of this buffer
354 is a message describing the reason that the debugger was invoked (such
355 as the error message and associated data, if it was invoked due to an
356 error).
358 @vindex debugger-bury-or-kill
359   The backtrace buffer is read-only and uses a special major mode,
360 Debugger mode, in which letters are defined as debugger commands.  The
361 usual Emacs editing commands are available; thus, you can switch windows
362 to examine the buffer that was being edited at the time of the error,
363 switch buffers, visit files, or do any other sort of editing.  However,
364 the debugger is a recursive editing level (@pxref{Recursive Editing})
365 and it is wise to go back to the backtrace buffer and exit the debugger
366 (with the @kbd{q} command) when you are finished with it.  Exiting
367 the debugger gets out of the recursive edit and buries the backtrace
368 buffer.  (You can customize what the @kbd{q} command does with the
369 backtrace buffer by setting the variable @code{debugger-bury-or-kill}.
370 For example, set it to @code{kill} if you prefer to kill the buffer
371 rather than bury it.  Consult the variable's documentation for more
372 possibilities.)
374   When the debugger has been entered, the @code{debug-on-error}
375 variable is temporarily set according to
376 @code{eval-expression-debug-on-error}.  If the latter variable is
377 non-@code{nil}, @code{debug-on-error} will temporarily be set to
378 @code{t}.  This means that any further errors that occur while doing a
379 debugging session will (by default) trigger another backtrace.  If
380 this is not what you want, you can either set
381 @code{eval-expression-debug-on-error} to @code{nil}, or set
382 @code{debug-on-error} to @code{nil} in @code{debugger-mode-hook}.
384 @cindex current stack frame
385   The backtrace buffer shows you the functions that are executing and
386 their argument values.  It also allows you to specify a stack frame by
387 moving point to the line describing that frame.  (A stack frame is the
388 place where the Lisp interpreter records information about a particular
389 invocation of a function.)  The frame whose line point is on is
390 considered the @dfn{current frame}.  Some of the debugger commands
391 operate on the current frame.  If a line starts with a star, that means
392 that exiting that frame will call the debugger again.  This is useful
393 for examining the return value of a function.
395   If a function name is underlined, that means the debugger knows
396 where its source code is located.  You can click with the mouse on
397 that name, or move to it and type @key{RET}, to visit the source code.
399   The debugger itself must be run byte-compiled, since it makes
400 assumptions about how many stack frames are used for the debugger
401 itself.  These assumptions are false if the debugger is running
402 interpreted.
404 @node Debugger Commands
405 @subsection Debugger Commands
406 @cindex debugger command list
408   The debugger buffer (in Debugger mode) provides special commands in
409 addition to the usual Emacs commands.  The most important use of
410 debugger commands is for stepping through code, so that you can see
411 how control flows.  The debugger can step through the control
412 structures of an interpreted function, but cannot do so in a
413 byte-compiled function.  If you would like to step through a
414 byte-compiled function, replace it with an interpreted definition of
415 the same function.  (To do this, visit the source for the function and
416 type @kbd{C-M-x} on its definition.)  You cannot use the Lisp debugger
417 to step through a primitive function.
419 @c FIXME: Add @findex for the following commands?  --xfq
420   Here is a list of Debugger mode commands:
422 @table @kbd
423 @item c
424 Exit the debugger and continue execution.  This resumes execution of
425 the program as if the debugger had never been entered (aside from any
426 side-effects that you caused by changing variable values or data
427 structures while inside the debugger).
429 @item d
430 Continue execution, but enter the debugger the next time any Lisp
431 function is called.  This allows you to step through the
432 subexpressions of an expression, seeing what values the subexpressions
433 compute, and what else they do.
435 The stack frame made for the function call which enters the debugger in
436 this way will be flagged automatically so that the debugger will be
437 called again when the frame is exited.  You can use the @kbd{u} command
438 to cancel this flag.
440 @item b
441 Flag the current frame so that the debugger will be entered when the
442 frame is exited.  Frames flagged in this way are marked with stars
443 in the backtrace buffer.
445 @item u
446 Don't enter the debugger when the current frame is exited.  This
447 cancels a @kbd{b} command on that frame.  The visible effect is to
448 remove the star from the line in the backtrace buffer.
450 @item j
451 Flag the current frame like @kbd{b}.  Then continue execution like
452 @kbd{c}, but temporarily disable break-on-entry for all functions that
453 are set up to do so by @code{debug-on-entry}.
455 @item e
456 Read a Lisp expression in the minibuffer, evaluate it (with the
457 relevant lexical environment, if applicable), and print the
458 value in the echo area.  The debugger alters certain important
459 variables, and the current buffer, as part of its operation; @kbd{e}
460 temporarily restores their values from outside the debugger, so you can
461 examine and change them.  This makes the debugger more transparent.  By
462 contrast, @kbd{M-:} does nothing special in the debugger; it shows you
463 the variable values within the debugger.
465 @item R
466 Like @kbd{e}, but also save the result of evaluation in the
467 buffer @file{*Debugger-record*}.
469 @item q
470 Terminate the program being debugged; return to top-level Emacs
471 command execution.
473 If the debugger was entered due to a @kbd{C-g} but you really want
474 to quit, and not debug, use the @kbd{q} command.
476 @item r
477 Return a value from the debugger.  The value is computed by reading an
478 expression with the minibuffer and evaluating it.
480 The @kbd{r} command is useful when the debugger was invoked due to exit
481 from a Lisp call frame (as requested with @kbd{b} or by entering the
482 frame with @kbd{d}); then the value specified in the @kbd{r} command is
483 used as the value of that frame.  It is also useful if you call
484 @code{debug} and use its return value.  Otherwise, @kbd{r} has the same
485 effect as @kbd{c}, and the specified return value does not matter.
487 You can't use @kbd{r} when the debugger was entered due to an error.
489 @item l
490 Display a list of functions that will invoke the debugger when called.
491 This is a list of functions that are set to break on entry by means of
492 @code{debug-on-entry}.
494 @item v
495 Toggle the display of local variables of the current stack frame.
496 @end table
498 @node Invoking the Debugger
499 @subsection Invoking the Debugger
500 @cindex invoking lisp debugger
502   Here we describe in full detail the function @code{debug} that is used
503 to invoke the debugger.
505 @deffn Command debug &rest debugger-args
506 This function enters the debugger.  It switches buffers to a buffer
507 named @file{*Backtrace*} (or @file{*Backtrace*<2>} if it is the second
508 recursive entry to the debugger, etc.), and fills it with information
509 about the stack of Lisp function calls.  It then enters a recursive
510 edit, showing the backtrace buffer in Debugger mode.
512 The Debugger mode @kbd{c}, @kbd{d}, @kbd{j}, and @kbd{r} commands exit
513 the recursive edit; then @code{debug} switches back to the previous
514 buffer and returns to whatever called @code{debug}.  This is the only
515 way the function @code{debug} can return to its caller.
517 The use of the @var{debugger-args} is that @code{debug} displays the
518 rest of its arguments at the top of the @file{*Backtrace*} buffer, so
519 that the user can see them.  Except as described below, this is the
520 @emph{only} way these arguments are used.
522 However, certain values for first argument to @code{debug} have a
523 special significance.  (Normally, these values are used only by the
524 internals of Emacs, and not by programmers calling @code{debug}.)  Here
525 is a table of these special values:
527 @table @code
528 @item lambda
529 @cindex @code{lambda} in debug
530 A first argument of @code{lambda} means @code{debug} was called
531 because of entry to a function when @code{debug-on-next-call} was
532 non-@code{nil}.  The debugger displays @samp{Debugger
533 entered--entering a function:} as a line of text at the top of the
534 buffer.
536 @item debug
537 @code{debug} as first argument means @code{debug} was called because
538 of entry to a function that was set to debug on entry.  The debugger
539 displays the string @samp{Debugger entered--entering a function:},
540 just as in the @code{lambda} case.  It also marks the stack frame for
541 that function so that it will invoke the debugger when exited.
543 @item t
544 When the first argument is @code{t}, this indicates a call to
545 @code{debug} due to evaluation of a function call form when
546 @code{debug-on-next-call} is non-@code{nil}.  The debugger displays
547 @samp{Debugger entered--beginning evaluation of function call form:}
548 as the top line in the buffer.
550 @item exit
551 When the first argument is @code{exit}, it indicates the exit of a
552 stack frame previously marked to invoke the debugger on exit.  The
553 second argument given to @code{debug} in this case is the value being
554 returned from the frame.  The debugger displays @samp{Debugger
555 entered--returning value:} in the top line of the buffer, followed by
556 the value being returned.
558 @item error
559 @cindex @code{error} in debug
560 When the first argument is @code{error}, the debugger indicates that
561 it is being entered because an error or @code{quit} was signaled and
562 not handled, by displaying @samp{Debugger entered--Lisp error:}
563 followed by the error signaled and any arguments to @code{signal}.
564 For example,
566 @example
567 @group
568 (let ((debug-on-error t))
569   (/ 1 0))
570 @end group
572 @group
573 ------ Buffer: *Backtrace* ------
574 Debugger entered--Lisp error: (arith-error)
575   /(1 0)
577 ------ Buffer: *Backtrace* ------
578 @end group
579 @end example
581 If an error was signaled, presumably the variable
582 @code{debug-on-error} is non-@code{nil}.  If @code{quit} was signaled,
583 then presumably the variable @code{debug-on-quit} is non-@code{nil}.
585 @item nil
586 Use @code{nil} as the first of the @var{debugger-args} when you want
587 to enter the debugger explicitly.  The rest of the @var{debugger-args}
588 are printed on the top line of the buffer.  You can use this feature to
589 display messages---for example, to remind yourself of the conditions
590 under which @code{debug} is called.
591 @end table
592 @end deffn
594 @node Internals of Debugger
595 @subsection Internals of the Debugger
597   This section describes functions and variables used internally by the
598 debugger.
600 @defvar debugger
601 The value of this variable is the function to call to invoke the
602 debugger.  Its value must be a function of any number of arguments, or,
603 more typically, the name of a function.  This function should invoke
604 some kind of debugger.  The default value of the variable is
605 @code{debug}.
607 The first argument that Lisp hands to the function indicates why it
608 was called.  The convention for arguments is detailed in the description
609 of @code{debug} (@pxref{Invoking the Debugger}).
610 @end defvar
612 @deffn Command backtrace
613 @cindex run time stack
614 @cindex call stack
615 This function prints a trace of Lisp function calls currently active.
616 This is the function used by @code{debug} to fill up the
617 @file{*Backtrace*} buffer.  It is written in C, since it must have access
618 to the stack to determine which function calls are active.  The return
619 value is always @code{nil}.
621 In the following example, a Lisp expression calls @code{backtrace}
622 explicitly.  This prints the backtrace to the stream
623 @code{standard-output}, which, in this case, is the buffer
624 @samp{backtrace-output}.
626 Each line of the backtrace represents one function call.  The line shows
627 the values of the function's arguments if they are all known; if they
628 are still being computed, the line says so.  The arguments of special
629 forms are elided.
631 @smallexample
632 @group
633 (with-output-to-temp-buffer "backtrace-output"
634   (let ((var 1))
635     (save-excursion
636       (setq var (eval '(progn
637                          (1+ var)
638                          (list 'testing (backtrace))))))))
640      @result{} (testing nil)
641 @end group
643 @group
644 ----------- Buffer: backtrace-output ------------
645   backtrace()
646   (list ...computing arguments...)
647 @end group
648   (progn ...)
649   eval((progn (1+ var) (list (quote testing) (backtrace))))
650   (setq ...)
651   (save-excursion ...)
652   (let ...)
653   (with-output-to-temp-buffer ...)
654   eval((with-output-to-temp-buffer ...))
655   eval-last-sexp-1(nil)
656 @group
657   eval-last-sexp(nil)
658   call-interactively(eval-last-sexp)
659 ----------- Buffer: backtrace-output ------------
660 @end group
661 @end smallexample
662 @end deffn
664 @defvar debugger-stack-frame-as-list
665 If this variable is non-@code{nil}, every stack frame of the backtrace
666 is displayed as a list.  This aims at improving the backtrace
667 readability at the cost of special forms no longer being visually
668 different from regular function calls.
670 With @code{debugger-stack-frame-as-list} non-@code{nil}, the above
671 example would look as follows:
673 @smallexample
674 @group
675 ----------- Buffer: backtrace-output ------------
676   (backtrace)
677   (list ...computing arguments...)
678 @end group
679   (progn ...)
680   (eval (progn (1+ var) (list (quote testing) (backtrace))))
681   (setq ...)
682   (save-excursion ...)
683   (let ...)
684   (with-output-to-temp-buffer ...)
685   (eval (with-output-to-temp-buffer ...))
686   (eval-last-sexp-1 nil)
687 @group
688   (eval-last-sexp nil)
689   (call-interactively eval-last-sexp)
690 ----------- Buffer: backtrace-output ------------
691 @end group
692 @end smallexample
693 @end defvar
695 @defvar debug-on-next-call
696 @cindex @code{eval}, and debugging
697 @cindex @code{apply}, and debugging
698 @cindex @code{funcall}, and debugging
699 If this variable is non-@code{nil}, it says to call the debugger before
700 the next @code{eval}, @code{apply} or @code{funcall}.  Entering the
701 debugger sets @code{debug-on-next-call} to @code{nil}.
703 The @kbd{d} command in the debugger works by setting this variable.
704 @end defvar
706 @defun backtrace-debug level flag
707 This function sets the debug-on-exit flag of the stack frame @var{level}
708 levels down the stack, giving it the value @var{flag}.  If @var{flag} is
709 non-@code{nil}, this will cause the debugger to be entered when that
710 frame later exits.  Even a nonlocal exit through that frame will enter
711 the debugger.
713 This function is used only by the debugger.
714 @end defun
716 @defvar command-debug-status
717 This variable records the debugging status of the current interactive
718 command.  Each time a command is called interactively, this variable is
719 bound to @code{nil}.  The debugger can set this variable to leave
720 information for future debugger invocations during the same command
721 invocation.
723 The advantage of using this variable rather than an ordinary global
724 variable is that the data will never carry over to a subsequent command
725 invocation.
727 This variable is obsolete and will be removed in future versions.
728 @end defvar
730 @defun backtrace-frame frame-number &optional base
731 The function @code{backtrace-frame} is intended for use in Lisp
732 debuggers.  It returns information about what computation is happening
733 in the stack frame @var{frame-number} levels down.
735 If that frame has not evaluated the arguments yet, or is a special
736 form, the value is @code{(nil @var{function} @var{arg-forms}@dots{})}.
738 If that frame has evaluated its arguments and called its function
739 already, the return value is @code{(t @var{function}
740 @var{arg-values}@dots{})}.
742 In the return value, @var{function} is whatever was supplied as the
743 @sc{car} of the evaluated list, or a @code{lambda} expression in the
744 case of a macro call.  If the function has a @code{&rest} argument, that
745 is represented as the tail of the list @var{arg-values}.
747 If @var{base} is specified, @var{frame-number} counts relative to
748 the topmost frame whose @var{function} is @var{base}.
750 If @var{frame-number} is out of range, @code{backtrace-frame} returns
751 @code{nil}.
752 @end defun
754 @defun mapbacktrace function &optional base
755 The function @code{mapbacktrace} calls @var{function} once for each
756 frame in the backtrace, starting at the first frame whose function is
757 @var{base} (or from the top if @var{base} is omitted or @code{nil}).
759 @var{function} is called with four arguments: @var{evald}, @var{func},
760 @var{args}, and @var{flags}.
762 If a frame has not evaluated its arguments yet or is a special form,
763 @var{evald} is @code{nil} and @var{args} is a list of forms.
765 If a frame has evaluated its arguments and called its function
766 already, @var{evald} is @code{t} and @var{args} is a list of values.
767 @var{flags} is a plist of properties of the current frame: currently,
768 the only supported property is @code{:debug-on-exit}, which is
769 @code{t} if the stack frame's @code{debug-on-exit} flag is set.
770 @end defun
772 @include edebug.texi
774 @node Syntax Errors
775 @section Debugging Invalid Lisp Syntax
776 @cindex debugging invalid Lisp syntax
778   The Lisp reader reports invalid syntax, but cannot say where the real
779 problem is.  For example, the error @samp{End of file during parsing} in
780 evaluating an expression indicates an excess of open parentheses (or
781 square brackets).  The reader detects this imbalance at the end of the
782 file, but it cannot figure out where the close parenthesis should have
783 been.  Likewise, @samp{Invalid read syntax: ")"} indicates an excess close
784 parenthesis or missing open parenthesis, but does not say where the
785 missing parenthesis belongs.  How, then, to find what to change?
787   If the problem is not simply an imbalance of parentheses, a useful
788 technique is to try @kbd{C-M-e} at the beginning of each defun, and see
789 if it goes to the place where that defun appears to end.  If it does
790 not, there is a problem in that defun.
792 @cindex unbalanced parentheses
793 @cindex parenthesis mismatch, debugging
794   However, unmatched parentheses are the most common syntax errors in
795 Lisp, and we can give further advice for those cases.  (In addition,
796 just moving point through the code with Show Paren mode enabled might
797 find the mismatch.)
799 @menu
800 * Excess Open::     How to find a spurious open paren or missing close.
801 * Excess Close::    How to find a spurious close paren or missing open.
802 @end menu
804 @node Excess Open
805 @subsection Excess Open Parentheses
806 @cindex excess open parentheses
808   The first step is to find the defun that is unbalanced.  If there is
809 an excess open parenthesis, the way to do this is to go to the end of
810 the file and type @kbd{C-u C-M-u}.  This will move you to the
811 beginning of the first defun that is unbalanced.
813   The next step is to determine precisely what is wrong.  There is no
814 way to be sure of this except by studying the program, but often the
815 existing indentation is a clue to where the parentheses should have
816 been.  The easiest way to use this clue is to reindent with @kbd{C-M-q}
817 and see what moves.  @strong{But don't do this yet!}  Keep reading,
818 first.
820   Before you do this, make sure the defun has enough close parentheses.
821 Otherwise, @kbd{C-M-q} will get an error, or will reindent all the rest
822 of the file until the end.  So move to the end of the defun and insert a
823 close parenthesis there.  Don't use @kbd{C-M-e} to move there, since
824 that too will fail to work until the defun is balanced.
826   Now you can go to the beginning of the defun and type @kbd{C-M-q}.
827 Usually all the lines from a certain point to the end of the function
828 will shift to the right.  There is probably a missing close parenthesis,
829 or a superfluous open parenthesis, near that point.  (However, don't
830 assume this is true; study the code to make sure.)  Once you have found
831 the discrepancy, undo the @kbd{C-M-q} with @kbd{C-_}, since the old
832 indentation is probably appropriate to the intended parentheses.
834   After you think you have fixed the problem, use @kbd{C-M-q} again.  If
835 the old indentation actually fit the intended nesting of parentheses,
836 and you have put back those parentheses, @kbd{C-M-q} should not change
837 anything.
839 @node Excess Close
840 @subsection Excess Close Parentheses
841 @cindex excess close parentheses
843   To deal with an excess close parenthesis, first go to the beginning
844 of the file, then type @kbd{C-u -1 C-M-u} to find the end of the first
845 unbalanced defun.
847   Then find the actual matching close parenthesis by typing @kbd{C-M-f}
848 at the beginning of that defun.  This will leave you somewhere short of
849 the place where the defun ought to end.  It is possible that you will
850 find a spurious close parenthesis in that vicinity.
852   If you don't see a problem at that point, the next thing to do is to
853 type @kbd{C-M-q} at the beginning of the defun.  A range of lines will
854 probably shift left; if so, the missing open parenthesis or spurious
855 close parenthesis is probably near the first of those lines.  (However,
856 don't assume this is true; study the code to make sure.)  Once you have
857 found the discrepancy, undo the @kbd{C-M-q} with @kbd{C-_}, since the
858 old indentation is probably appropriate to the intended parentheses.
860   After you think you have fixed the problem, use @kbd{C-M-q} again.  If
861 the old indentation actually fits the intended nesting of parentheses,
862 and you have put back those parentheses, @kbd{C-M-q} should not change
863 anything.
865 @node Test Coverage
866 @section Test Coverage
867 @cindex coverage testing
869 @findex testcover-start
870 @findex testcover-mark-all
871 @findex testcover-next-mark
872   You can do coverage testing for a file of Lisp code by loading the
873 @code{testcover} library and using the command @kbd{M-x
874 testcover-start @key{RET} @var{file} @key{RET}} to instrument the
875 code.  Then test your code by calling it one or more times.  Then use
876 the command @kbd{M-x testcover-mark-all} to display colored highlights
877 on the code to show where coverage is insufficient.  The command
878 @kbd{M-x testcover-next-mark} will move point forward to the next
879 highlighted spot.
881   Normally, a red highlight indicates the form was never completely
882 evaluated; a brown highlight means it always evaluated to the same
883 value (meaning there has been little testing of what is done with the
884 result).  However, the red highlight is skipped for forms that can't
885 possibly complete their evaluation, such as @code{error}.  The brown
886 highlight is skipped for forms that are expected to always evaluate to
887 the same value, such as @code{(setq x 14)}.
889   For difficult cases, you can add do-nothing macros to your code to
890 give advice to the test coverage tool.
892 @defmac 1value form
893 Evaluate @var{form} and return its value, but inform coverage testing
894 that @var{form}'s value should always be the same.
895 @end defmac
897 @defmac noreturn form
898 Evaluate @var{form}, informing coverage testing that @var{form} should
899 never return.  If it ever does return, you get a run-time error.
900 @end defmac
902   Edebug also has a coverage testing feature (@pxref{Coverage
903 Testing}).  These features partly duplicate each other, and it would
904 be cleaner to combine them.
907 @node Profiling
908 @section Profiling
909 @cindex profiling
910 @cindex profile
911 @cindex measuring resource usage
912 @cindex memory usage
914 If your program is working correctly, but you want to make it run more
915 quickly or efficiently, the first thing to do is @dfn{profile} your
916 code so that you know how it is using resources.  If you find that one
917 particular function is responsible for a significant portion of the
918 runtime, you can start looking for ways to optimize that piece.
920 Emacs has built-in support for this.  To begin profiling, type
921 @kbd{M-x profiler-start}.  You can choose to profile by processor
922 usage, memory usage, or both.  After doing some work, type
923 @kbd{M-x profiler-report} to display a summary buffer for each
924 resource that you chose to profile.  The names of the report buffers
925 include the times at which the reports were generated, so you can
926 generate another report later on without erasing previous results.
927 When you have finished profiling, type @kbd{M-x profiler-stop} (there
928 is a small overhead associated with profiling).
930 The profiler report buffer shows, on each line, a function that was
931 called, followed by how much resource (processor or memory) it used in
932 absolute and percentage times since profiling started.  If a given
933 line has a @samp{+} symbol at the left-hand side, you can expand that
934 line by typing @key{RET}, in order to see the function(s) called by
935 the higher-level function.  Use a prefix argument (@key{C-u RET}) to
936 see the whole call tree below a function.  Pressing @key{RET} again
937 will collapse back to the original state.
939 Press @kbd{j} or @kbd{mouse-2} to jump to the definition of a function.
940 Press @kbd{d} to view a function's documentation.
941 You can save a profile to a file using @kbd{C-x C-w}.
942 You can compare two profiles using @kbd{=}.
944 @c FIXME reversed calltree?
946 @cindex @file{elp.el}
947 @cindex timing programs
948 The @file{elp} library offers an alternative approach.  See the file
949 @file{elp.el} for instructions.
951 @cindex @file{benchmark.el}
952 @cindex benchmarking
953 You can check the speed of individual Emacs Lisp forms using the
954 @file{benchmark} library.  See the functions @code{benchmark-run} and
955 @code{benchmark-run-compiled} in @file{benchmark.el}.
957 @c Not worth putting in the printed manual.
958 @ifnottex
959 @cindex --enable-profiling option of configure
960 To profile Emacs at the level of its C code, you can build it using the
961 @option{--enable-profiling} option of @command{configure}.  When Emacs
962 exits, it generates a file @file{gmon.out} that you can examine using
963 the @command{gprof} utility.  This feature is mainly useful for
964 debugging Emacs.  It actually stops the Lisp-level @kbd{M-x
965 profiler-@dots{}} commands described above from working.
966 @end ifnottex