Add a bit more about profiling to the lispref
[emacs.git] / doc / lispref / debugging.texi
blob3439a8ae152f9adc8857557fb52d044bd9df8f0b
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1994, 1998-1999, 2001-2012 Free Software Foundation, Inc.
4 @c See the file elisp.texi for copying conditions.
5 @node Debugging
6 @chapter Debugging Lisp Programs
8   There are several ways to find and investigate problems in an Emacs
9 Lisp program.
11 @itemize @bullet
12 @item
13 If a problem occurs when you run the program, you can use the built-in
14 Emacs Lisp debugger to suspend the Lisp evaluator, and examine and/or
15 alter its internal state.
17 @item
18 You can use Edebug, a source-level debugger for Emacs Lisp.
20 @item
21 If a syntactic problem is preventing Lisp from even reading the
22 program, you can locate it using Lisp editing commands.
24 @item
25 You can look at the error and warning messages produced by the byte
26 compiler when it compiles the program.  @xref{Compiler Errors}.
28 @item
29 You can use the Testcover package to perform coverage testing on the
30 program.
32 @item
33 You can use the ERT package to write regression tests for the program.
34 @xref{Top,the ERT manual,, ERT, ERT: Emacs Lisp Regression Testing}.
36 @item
37 You can profile the program to get hints about how to make it more efficient.
38 @end itemize
40   Other useful tools for debugging input and output problems are the
41 dribble file (@pxref{Terminal Input}) and the @code{open-termscript}
42 function (@pxref{Terminal Output}).
44 @menu
45 * Debugger::            A debugger for the Emacs Lisp evaluator.
46 * Edebug::              A source-level Emacs Lisp debugger.
47 * Syntax Errors::       How to find syntax errors.
48 * Test Coverage::       Ensuring you have tested all branches in your code.
49 * Profiling::           Measuring the resources that your code uses.
50 @end menu
52 @node Debugger
53 @section The Lisp Debugger
54 @cindex debugger for Emacs Lisp
55 @cindex Lisp debugger
56 @cindex break
58   The ordinary @dfn{Lisp debugger} provides the ability to suspend
59 evaluation of a form.  While evaluation is suspended (a state that is
60 commonly known as a @dfn{break}), you may examine the run time stack,
61 examine the values of local or global variables, or change those values.
62 Since a break is a recursive edit, all the usual editing facilities of
63 Emacs are available; you can even run programs that will enter the
64 debugger recursively.  @xref{Recursive Editing}.
66 @menu
67 * Error Debugging::       Entering the debugger when an error happens.
68 * Infinite Loops::        Stopping and debugging a program that doesn't exit.
69 * Function Debugging::    Entering it when a certain function is called.
70 * Explicit Debug::        Entering it at a certain point in the program.
71 * Using Debugger::        What the debugger does; what you see while in it.
72 * Debugger Commands::     Commands used while in the debugger.
73 * Invoking the Debugger:: How to call the function @code{debug}.
74 * Internals of Debugger:: Subroutines of the debugger, and global variables.
75 @end menu
77 @node Error Debugging
78 @subsection Entering the Debugger on an Error
79 @cindex error debugging
80 @cindex debugging errors
82   The most important time to enter the debugger is when a Lisp error
83 happens.  This allows you to investigate the immediate causes of the
84 error.
86   However, entry to the debugger is not a normal consequence of an
87 error.  Many commands signal Lisp errors when invoked inappropriately,
88 and during ordinary editing it would be very inconvenient to enter the
89 debugger each time this happens.  So if you want errors to enter the
90 debugger, set the variable @code{debug-on-error} to non-@code{nil}.
91 (The command @code{toggle-debug-on-error} provides an easy way to do
92 this.)
94 @defopt debug-on-error
95 This variable determines whether the debugger is called when an error
96 is signaled and not handled.  If @code{debug-on-error} is @code{t},
97 all kinds of errors call the debugger, except those listed in
98 @code{debug-ignored-errors} (see below).  If it is @code{nil}, none
99 call the debugger.
101 The value can also be a list of error conditions (@pxref{Signaling
102 Errors}).  Then the debugger is called only for error conditions in
103 this list (except those also listed in @code{debug-ignored-errors}).
104 For example, if you set @code{debug-on-error} to the list
105 @code{(void-variable)}, the debugger is only called for errors about a
106 variable that has no value.
108 Note that @code{eval-expression-debug-on-error} overrides this
109 variable in some cases; see below.
111 When this variable is non-@code{nil}, Emacs does not create an error
112 handler around process filter functions and sentinels.  Therefore,
113 errors in these functions also invoke the debugger.  @xref{Processes}.
114 @end defopt
116 @defopt debug-ignored-errors
117 This variable specifies errors which should not enter the debugger,
118 regardless of the value of @code{debug-on-error}.  Its value is a list
119 of error condition symbols and/or regular expressions.  If the error
120 has any of those condition symbols, or if the error message matches
121 any of the regular expressions, then that error does not enter the
122 debugger.
124 The normal value of this variable includes @code{user-error}, as well
125 as several errors that happen often during editing but rarely result
126 from bugs in Lisp programs.  However, ``rarely'' is not ``never''; if
127 your program fails with an error that matches this list, you may try
128 changing this list to debug the error.  The easiest way is usually to
129 set @code{debug-ignored-errors} to @code{nil}.
130 @end defopt
132 @defopt eval-expression-debug-on-error
133 If this variable has a non-@code{nil} value (the default), running the
134 command @code{eval-expression} causes @code{debug-on-error} to be
135 temporarily bound to to @code{t}.  @xref{Lisp Eval,, Evaluating
136 Emacs-Lisp Expressions, emacs, The GNU Emacs Manual}.
138 If @code{eval-expression-debug-on-error} is @code{nil}, then the value
139 of @code{debug-on-error} is not changed during @code{eval-expression}.
140 @end defopt
142 @defvar debug-on-signal
143 Normally, errors caught by @code{condition-case} never invoke the
144 debugger.  The @code{condition-case} gets a chance to handle the error
145 before the debugger gets a chance.
147 If you change @code{debug-on-signal} to a non-@code{nil} value, the
148 debugger gets the first chance at every error, regardless of the
149 presence of @code{condition-case}.  (To invoke the debugger, the error
150 must still fulfill the criteria specified by @code{debug-on-error} and
151 @code{debug-ignored-errors}.)
153 @strong{Warning:} Setting this variable to non-@code{nil} may have
154 annoying effects.  Various parts of Emacs catch errors in the normal
155 course of affairs, and you may not even realize that errors happen
156 there.  If you need to debug code wrapped in @code{condition-case},
157 consider using @code{condition-case-unless-debug} (@pxref{Handling
158 Errors}).
159 @end defvar
161 @defopt debug-on-event
162 If you set @code{debug-on-event} to a special event (@pxref{Special
163 Events}), Emacs will try to enter the debugger as soon as it receives
164 this event, bypassing @code{special-event-map}.  At present, the only
165 supported values correspond to the signals @code{SIGUSR1} and
166 @code{SIGUSR2} (this is the default).  This can be helpful when
167 @code{inhibit-quit} is set and Emacs is not otherwise responding.
168 @end defopt
170 @cindex message, finding what causes a particular message
171 @defvar debug-on-message
172 If you set @code{debug-on-message} to a regular expression,
173 Emacs will enter the debugger if it displays a matching message in the
174 echo area.  For example, this can be useful when trying to find the
175 cause of a particular message.
176 @end defvar
178   To debug an error that happens during loading of the init
179 file, use the option @samp{--debug-init}.  This binds
180 @code{debug-on-error} to @code{t} while loading the init file, and
181 bypasses the @code{condition-case} which normally catches errors in the
182 init file.
184 @node Infinite Loops
185 @subsection Debugging Infinite Loops
186 @cindex infinite loops
187 @cindex loops, infinite
188 @cindex quitting from infinite loop
189 @cindex stopping an infinite loop
191   When a program loops infinitely and fails to return, your first
192 problem is to stop the loop.  On most operating systems, you can do
193 this with @kbd{C-g}, which causes a @dfn{quit}.  @xref{Quitting}.
195   Ordinary quitting gives no information about why the program was
196 looping.  To get more information, you can set the variable
197 @code{debug-on-quit} to non-@code{nil}.  Once you have the debugger
198 running in the middle of the infinite loop, you can proceed from the
199 debugger using the stepping commands.  If you step through the entire
200 loop, you may get enough information to solve the problem.
202   Quitting with @kbd{C-g} is not considered an error, and
203 @code{debug-on-error} has no effect on the handling of @kbd{C-g}.
204 Likewise, @code{debug-on-quit} has no effect on errors.
206 @defopt debug-on-quit
207 This variable determines whether the debugger is called when
208 @code{quit} is signaled and not handled.  If @code{debug-on-quit} is
209 non-@code{nil}, then the debugger is called whenever you quit (that
210 is, type @kbd{C-g}).  If @code{debug-on-quit} is @code{nil} (the
211 default), then the debugger is not called when you quit.
212 @end defopt
214 @node Function Debugging
215 @subsection Entering the Debugger on a Function Call
216 @cindex function call debugging
217 @cindex debugging specific functions
219   To investigate a problem that happens in the middle of a program, one
220 useful technique is to enter the debugger whenever a certain function is
221 called.  You can do this to the function in which the problem occurs,
222 and then step through the function, or you can do this to a function
223 called shortly before the problem, step quickly over the call to that
224 function, and then step through its caller.
226 @deffn Command debug-on-entry function-name
227 This function requests @var{function-name} to invoke the debugger each
228 time it is called.  It works by inserting the form
229 @code{(implement-debug-on-entry)} into the function definition as the
230 first form.
232 Any function or macro defined as Lisp code may be set to break on
233 entry, regardless of whether it is interpreted code or compiled code.
234 If the function is a command, it will enter the debugger when called
235 from Lisp and when called interactively (after the reading of the
236 arguments).  You can also set debug-on-entry for primitive functions
237 (i.e., those written in C) this way, but it only takes effect when the
238 primitive is called from Lisp code.  Debug-on-entry is not allowed for
239 special forms.
241 When @code{debug-on-entry} is called interactively, it prompts for
242 @var{function-name} in the minibuffer.  If the function is already set
243 up to invoke the debugger on entry, @code{debug-on-entry} does nothing.
244 @code{debug-on-entry} always returns @var{function-name}.
246 @strong{Warning:} if you redefine a function after using
247 @code{debug-on-entry} on it, the code to enter the debugger is
248 discarded by the redefinition.  In effect, redefining the function
249 cancels the break-on-entry feature for that function.
251 Here's an example to illustrate use of this function:
253 @example
254 @group
255 (defun fact (n)
256   (if (zerop n) 1
257       (* n (fact (1- n)))))
258      @result{} fact
259 @end group
260 @group
261 (debug-on-entry 'fact)
262      @result{} fact
263 @end group
264 @group
265 (fact 3)
266 @end group
268 @group
269 ------ Buffer: *Backtrace* ------
270 Debugger entered--entering a function:
271 * fact(3)
272   eval((fact 3))
273   eval-last-sexp-1(nil)
274   eval-last-sexp(nil)
275   call-interactively(eval-last-sexp)
276 ------ Buffer: *Backtrace* ------
277 @end group
279 @group
280 (symbol-function 'fact)
281      @result{} (lambda (n)
282           (debug (quote debug))
283           (if (zerop n) 1 (* n (fact (1- n)))))
284 @end group
285 @end example
286 @end deffn
288 @deffn Command cancel-debug-on-entry &optional function-name
289 This function undoes the effect of @code{debug-on-entry} on
290 @var{function-name}.  When called interactively, it prompts for
291 @var{function-name} in the minibuffer.  If @var{function-name} is
292 omitted or @code{nil}, it cancels break-on-entry for all functions.
293 Calling @code{cancel-debug-on-entry} does nothing to a function which is
294 not currently set up to break on entry.
295 @end deffn
297 @node Explicit Debug
298 @subsection Explicit Entry to the Debugger
300   You can cause the debugger to be called at a certain point in your
301 program by writing the expression @code{(debug)} at that point.  To do
302 this, visit the source file, insert the text @samp{(debug)} at the
303 proper place, and type @kbd{C-M-x} (@code{eval-defun}, a Lisp mode key
304 binding).  @strong{Warning:} if you do this for temporary debugging
305 purposes, be sure to undo this insertion before you save the file!
307   The place where you insert @samp{(debug)} must be a place where an
308 additional form can be evaluated and its value ignored.  (If the value
309 of @code{(debug)} isn't ignored, it will alter the execution of the
310 program!)  The most common suitable places are inside a @code{progn} or
311 an implicit @code{progn} (@pxref{Sequencing}).
313   If you don't know exactly where in the source code you want to put
314 the debug statement, but you want to display a backtrace when a
315 certain message is displayed, you can set @code{debug-on-message} to a
316 regular expression matching the desired message.
318 @node Using Debugger
319 @subsection Using the Debugger
321   When the debugger is entered, it displays the previously selected
322 buffer in one window and a buffer named @file{*Backtrace*} in another
323 window.  The backtrace buffer contains one line for each level of Lisp
324 function execution currently going on.  At the beginning of this buffer
325 is a message describing the reason that the debugger was invoked (such
326 as the error message and associated data, if it was invoked due to an
327 error).
329 @vindex debugger-bury-or-kill
330   The backtrace buffer is read-only and uses a special major mode,
331 Debugger mode, in which letters are defined as debugger commands.  The
332 usual Emacs editing commands are available; thus, you can switch windows
333 to examine the buffer that was being edited at the time of the error,
334 switch buffers, visit files, or do any other sort of editing.  However,
335 the debugger is a recursive editing level (@pxref{Recursive Editing})
336 and it is wise to go back to the backtrace buffer and exit the debugger
337 (with the @kbd{q} command) when you are finished with it.  Exiting
338 the debugger gets out of the recursive edit and buries the backtrace
339 buffer.  (You can customize what the @kbd{q} command does with the
340 backtrace buffer by setting the variable @code{debugger-bury-or-kill}.
341 For example, set it to @code{kill} if you prefer to kill the buffer
342 rather than bury it.  Consult the variable's documentation for more
343 possibilities.)
345   When the debugger has been entered, the @code{debug-on-error}
346 variable is temporarily set according to
347 @code{eval-expression-debug-on-error}.  If the latter variable is
348 non-@code{nil}, @code{debug-on-error} will temporarily be set to
349 @code{t}.  This means that any further errors that occur while doing a
350 debugging session will (by default) trigger another backtrace.  If
351 this is not what you want, you can either set
352 @code{eval-expression-debug-on-error} to @code{nil}, or set
353 @code{debug-on-error} to @code{nil} in @code{debugger-mode-hook}.
355 @cindex current stack frame
356   The backtrace buffer shows you the functions that are executing and
357 their argument values.  It also allows you to specify a stack frame by
358 moving point to the line describing that frame.  (A stack frame is the
359 place where the Lisp interpreter records information about a particular
360 invocation of a function.)  The frame whose line point is on is
361 considered the @dfn{current frame}.  Some of the debugger commands
362 operate on the current frame.  If a line starts with a star, that means
363 that exiting that frame will call the debugger again.  This is useful
364 for examining the return value of a function.
366   If a function name is underlined, that means the debugger knows
367 where its source code is located.  You can click with the mouse on
368 that name, or move to it and type @key{RET}, to visit the source code.
370   The debugger itself must be run byte-compiled, since it makes
371 assumptions about how many stack frames are used for the debugger
372 itself.  These assumptions are false if the debugger is running
373 interpreted.
375 @node Debugger Commands
376 @subsection Debugger Commands
377 @cindex debugger command list
379   The debugger buffer (in Debugger mode) provides special commands in
380 addition to the usual Emacs commands.  The most important use of
381 debugger commands is for stepping through code, so that you can see
382 how control flows.  The debugger can step through the control
383 structures of an interpreted function, but cannot do so in a
384 byte-compiled function.  If you would like to step through a
385 byte-compiled function, replace it with an interpreted definition of
386 the same function.  (To do this, visit the source for the function and
387 type @kbd{C-M-x} on its definition.)  You cannot use the Lisp debugger
388 to step through a primitive function.
390   Here is a list of Debugger mode commands:
392 @table @kbd
393 @item c
394 Exit the debugger and continue execution.  This resumes execution of
395 the program as if the debugger had never been entered (aside from any
396 side-effects that you caused by changing variable values or data
397 structures while inside the debugger).
399 @item d
400 Continue execution, but enter the debugger the next time any Lisp
401 function is called.  This allows you to step through the
402 subexpressions of an expression, seeing what values the subexpressions
403 compute, and what else they do.
405 The stack frame made for the function call which enters the debugger in
406 this way will be flagged automatically so that the debugger will be
407 called again when the frame is exited.  You can use the @kbd{u} command
408 to cancel this flag.
410 @item b
411 Flag the current frame so that the debugger will be entered when the
412 frame is exited.  Frames flagged in this way are marked with stars
413 in the backtrace buffer.
415 @item u
416 Don't enter the debugger when the current frame is exited.  This
417 cancels a @kbd{b} command on that frame.  The visible effect is to
418 remove the star from the line in the backtrace buffer.
420 @item j
421 Flag the current frame like @kbd{b}.  Then continue execution like
422 @kbd{c}, but temporarily disable break-on-entry for all functions that
423 are set up to do so by @code{debug-on-entry}.
425 @item e
426 Read a Lisp expression in the minibuffer, evaluate it, and print the
427 value in the echo area.  The debugger alters certain important
428 variables, and the current buffer, as part of its operation; @kbd{e}
429 temporarily restores their values from outside the debugger, so you can
430 examine and change them.  This makes the debugger more transparent.  By
431 contrast, @kbd{M-:} does nothing special in the debugger; it shows you
432 the variable values within the debugger.
434 @item R
435 Like @kbd{e}, but also save the result of evaluation in the
436 buffer @file{*Debugger-record*}.
438 @item q
439 Terminate the program being debugged; return to top-level Emacs
440 command execution.
442 If the debugger was entered due to a @kbd{C-g} but you really want
443 to quit, and not debug, use the @kbd{q} command.
445 @item r
446 Return a value from the debugger.  The value is computed by reading an
447 expression with the minibuffer and evaluating it.
449 The @kbd{r} command is useful when the debugger was invoked due to exit
450 from a Lisp call frame (as requested with @kbd{b} or by entering the
451 frame with @kbd{d}); then the value specified in the @kbd{r} command is
452 used as the value of that frame.  It is also useful if you call
453 @code{debug} and use its return value.  Otherwise, @kbd{r} has the same
454 effect as @kbd{c}, and the specified return value does not matter.
456 You can't use @kbd{r} when the debugger was entered due to an error.
458 @item l
459 Display a list of functions that will invoke the debugger when called.
460 This is a list of functions that are set to break on entry by means of
461 @code{debug-on-entry}.  @strong{Warning:} if you redefine such a
462 function and thus cancel the effect of @code{debug-on-entry}, it may
463 erroneously show up in this list.
464 @end table
466 @node Invoking the Debugger
467 @subsection Invoking the Debugger
469   Here we describe in full detail the function @code{debug} that is used
470 to invoke the debugger.
472 @deffn Command debug &rest debugger-args
473 This function enters the debugger.  It switches buffers to a buffer
474 named @file{*Backtrace*} (or @file{*Backtrace*<2>} if it is the second
475 recursive entry to the debugger, etc.), and fills it with information
476 about the stack of Lisp function calls.  It then enters a recursive
477 edit, showing the backtrace buffer in Debugger mode.
479 The Debugger mode @kbd{c}, @kbd{d}, @kbd{j}, and @kbd{r} commands exit
480 the recursive edit; then @code{debug} switches back to the previous
481 buffer and returns to whatever called @code{debug}.  This is the only
482 way the function @code{debug} can return to its caller.
484 The use of the @var{debugger-args} is that @code{debug} displays the
485 rest of its arguments at the top of the @file{*Backtrace*} buffer, so
486 that the user can see them.  Except as described below, this is the
487 @emph{only} way these arguments are used.
489 However, certain values for first argument to @code{debug} have a
490 special significance.  (Normally, these values are used only by the
491 internals of Emacs, and not by programmers calling @code{debug}.)  Here
492 is a table of these special values:
494 @table @code
495 @item lambda
496 @cindex @code{lambda} in debug
497 A first argument of @code{lambda} means @code{debug} was called
498 because of entry to a function when @code{debug-on-next-call} was
499 non-@code{nil}.  The debugger displays @samp{Debugger
500 entered--entering a function:} as a line of text at the top of the
501 buffer.
503 @item debug
504 @code{debug} as first argument means @code{debug} was called because
505 of entry to a function that was set to debug on entry.  The debugger
506 displays the string @samp{Debugger entered--entering a function:},
507 just as in the @code{lambda} case.  It also marks the stack frame for
508 that function so that it will invoke the debugger when exited.
510 @item t
511 When the first argument is @code{t}, this indicates a call to
512 @code{debug} due to evaluation of a function call form when
513 @code{debug-on-next-call} is non-@code{nil}.  The debugger displays
514 @samp{Debugger entered--beginning evaluation of function call form:}
515 as the top line in the buffer.
517 @item exit
518 When the first argument is @code{exit}, it indicates the exit of a
519 stack frame previously marked to invoke the debugger on exit.  The
520 second argument given to @code{debug} in this case is the value being
521 returned from the frame.  The debugger displays @samp{Debugger
522 entered--returning value:} in the top line of the buffer, followed by
523 the value being returned.
525 @item error
526 @cindex @code{error} in debug
527 When the first argument is @code{error}, the debugger indicates that
528 it is being entered because an error or @code{quit} was signaled and
529 not handled, by displaying @samp{Debugger entered--Lisp error:}
530 followed by the error signaled and any arguments to @code{signal}.
531 For example,
533 @example
534 @group
535 (let ((debug-on-error t))
536   (/ 1 0))
537 @end group
539 @group
540 ------ Buffer: *Backtrace* ------
541 Debugger entered--Lisp error: (arith-error)
542   /(1 0)
544 ------ Buffer: *Backtrace* ------
545 @end group
546 @end example
548 If an error was signaled, presumably the variable
549 @code{debug-on-error} is non-@code{nil}.  If @code{quit} was signaled,
550 then presumably the variable @code{debug-on-quit} is non-@code{nil}.
552 @item nil
553 Use @code{nil} as the first of the @var{debugger-args} when you want
554 to enter the debugger explicitly.  The rest of the @var{debugger-args}
555 are printed on the top line of the buffer.  You can use this feature to
556 display messages---for example, to remind yourself of the conditions
557 under which @code{debug} is called.
558 @end table
559 @end deffn
561 @node Internals of Debugger
562 @subsection Internals of the Debugger
564   This section describes functions and variables used internally by the
565 debugger.
567 @defvar debugger
568 The value of this variable is the function to call to invoke the
569 debugger.  Its value must be a function of any number of arguments, or,
570 more typically, the name of a function.  This function should invoke
571 some kind of debugger.  The default value of the variable is
572 @code{debug}.
574 The first argument that Lisp hands to the function indicates why it
575 was called.  The convention for arguments is detailed in the description
576 of @code{debug} (@pxref{Invoking the Debugger}).
577 @end defvar
579 @deffn Command backtrace
580 @cindex run time stack
581 @cindex call stack
582 This function prints a trace of Lisp function calls currently active.
583 This is the function used by @code{debug} to fill up the
584 @file{*Backtrace*} buffer.  It is written in C, since it must have access
585 to the stack to determine which function calls are active.  The return
586 value is always @code{nil}.
588 In the following example, a Lisp expression calls @code{backtrace}
589 explicitly.  This prints the backtrace to the stream
590 @code{standard-output}, which, in this case, is the buffer
591 @samp{backtrace-output}.
593 Each line of the backtrace represents one function call.  The line shows
594 the values of the function's arguments if they are all known; if they
595 are still being computed, the line says so.  The arguments of special
596 forms are elided.
598 @smallexample
599 @group
600 (with-output-to-temp-buffer "backtrace-output"
601   (let ((var 1))
602     (save-excursion
603       (setq var (eval '(progn
604                          (1+ var)
605                          (list 'testing (backtrace))))))))
607      @result{} (testing nil)
608 @end group
610 @group
611 ----------- Buffer: backtrace-output ------------
612   backtrace()
613   (list ...computing arguments...)
614 @end group
615   (progn ...)
616   eval((progn (1+ var) (list (quote testing) (backtrace))))
617   (setq ...)
618   (save-excursion ...)
619   (let ...)
620   (with-output-to-temp-buffer ...)
621   eval((with-output-to-temp-buffer ...))
622   eval-last-sexp-1(nil)
623 @group
624   eval-last-sexp(nil)
625   call-interactively(eval-last-sexp)
626 ----------- Buffer: backtrace-output ------------
627 @end group
628 @end smallexample
629 @end deffn
631 @defvar debug-on-next-call
632 @cindex @code{eval}, and debugging
633 @cindex @code{apply}, and debugging
634 @cindex @code{funcall}, and debugging
635 If this variable is non-@code{nil}, it says to call the debugger before
636 the next @code{eval}, @code{apply} or @code{funcall}.  Entering the
637 debugger sets @code{debug-on-next-call} to @code{nil}.
639 The @kbd{d} command in the debugger works by setting this variable.
640 @end defvar
642 @defun backtrace-debug level flag
643 This function sets the debug-on-exit flag of the stack frame @var{level}
644 levels down the stack, giving it the value @var{flag}.  If @var{flag} is
645 non-@code{nil}, this will cause the debugger to be entered when that
646 frame later exits.  Even a nonlocal exit through that frame will enter
647 the debugger.
649 This function is used only by the debugger.
650 @end defun
652 @defvar command-debug-status
653 This variable records the debugging status of the current interactive
654 command.  Each time a command is called interactively, this variable is
655 bound to @code{nil}.  The debugger can set this variable to leave
656 information for future debugger invocations during the same command
657 invocation.
659 The advantage of using this variable rather than an ordinary global
660 variable is that the data will never carry over to a subsequent command
661 invocation.
662 @end defvar
664 @defun backtrace-frame frame-number
665 The function @code{backtrace-frame} is intended for use in Lisp
666 debuggers.  It returns information about what computation is happening
667 in the stack frame @var{frame-number} levels down.
669 If that frame has not evaluated the arguments yet, or is a special
670 form, the value is @code{(nil @var{function} @var{arg-forms}@dots{})}.
672 If that frame has evaluated its arguments and called its function
673 already, the return value is @code{(t @var{function}
674 @var{arg-values}@dots{})}.
676 In the return value, @var{function} is whatever was supplied as the
677 @sc{car} of the evaluated list, or a @code{lambda} expression in the
678 case of a macro call.  If the function has a @code{&rest} argument, that
679 is represented as the tail of the list @var{arg-values}.
681 If @var{frame-number} is out of range, @code{backtrace-frame} returns
682 @code{nil}.
683 @end defun
685 @include edebug.texi
687 @node Syntax Errors
688 @section Debugging Invalid Lisp Syntax
689 @cindex debugging invalid Lisp syntax
691   The Lisp reader reports invalid syntax, but cannot say where the real
692 problem is.  For example, the error ``End of file during parsing'' in
693 evaluating an expression indicates an excess of open parentheses (or
694 square brackets).  The reader detects this imbalance at the end of the
695 file, but it cannot figure out where the close parenthesis should have
696 been.  Likewise, ``Invalid read syntax: ")"'' indicates an excess close
697 parenthesis or missing open parenthesis, but does not say where the
698 missing parenthesis belongs.  How, then, to find what to change?
700   If the problem is not simply an imbalance of parentheses, a useful
701 technique is to try @kbd{C-M-e} at the beginning of each defun, and see
702 if it goes to the place where that defun appears to end.  If it does
703 not, there is a problem in that defun.
705 @cindex unbalanced parentheses
706 @cindex parenthesis mismatch, debugging
707   However, unmatched parentheses are the most common syntax errors in
708 Lisp, and we can give further advice for those cases.  (In addition,
709 just moving point through the code with Show Paren mode enabled might
710 find the mismatch.)
712 @menu
713 * Excess Open::     How to find a spurious open paren or missing close.
714 * Excess Close::    How to find a spurious close paren or missing open.
715 @end menu
717 @node Excess Open
718 @subsection Excess Open Parentheses
720   The first step is to find the defun that is unbalanced.  If there is
721 an excess open parenthesis, the way to do this is to go to the end of
722 the file and type @kbd{C-u C-M-u}.  This will move you to the
723 beginning of the first defun that is unbalanced.
725   The next step is to determine precisely what is wrong.  There is no
726 way to be sure of this except by studying the program, but often the
727 existing indentation is a clue to where the parentheses should have
728 been.  The easiest way to use this clue is to reindent with @kbd{C-M-q}
729 and see what moves.  @strong{But don't do this yet!}  Keep reading,
730 first.
732   Before you do this, make sure the defun has enough close parentheses.
733 Otherwise, @kbd{C-M-q} will get an error, or will reindent all the rest
734 of the file until the end.  So move to the end of the defun and insert a
735 close parenthesis there.  Don't use @kbd{C-M-e} to move there, since
736 that too will fail to work until the defun is balanced.
738   Now you can go to the beginning of the defun and type @kbd{C-M-q}.
739 Usually all the lines from a certain point to the end of the function
740 will shift to the right.  There is probably a missing close parenthesis,
741 or a superfluous open parenthesis, near that point.  (However, don't
742 assume this is true; study the code to make sure.)  Once you have found
743 the discrepancy, undo the @kbd{C-M-q} with @kbd{C-_}, since the old
744 indentation is probably appropriate to the intended parentheses.
746   After you think you have fixed the problem, use @kbd{C-M-q} again.  If
747 the old indentation actually fit the intended nesting of parentheses,
748 and you have put back those parentheses, @kbd{C-M-q} should not change
749 anything.
751 @node Excess Close
752 @subsection Excess Close Parentheses
754   To deal with an excess close parenthesis, first go to the beginning
755 of the file, then type @kbd{C-u -1 C-M-u} to find the end of the first
756 unbalanced defun.
758   Then find the actual matching close parenthesis by typing @kbd{C-M-f}
759 at the beginning of that defun.  This will leave you somewhere short of
760 the place where the defun ought to end.  It is possible that you will
761 find a spurious close parenthesis in that vicinity.
763   If you don't see a problem at that point, the next thing to do is to
764 type @kbd{C-M-q} at the beginning of the defun.  A range of lines will
765 probably shift left; if so, the missing open parenthesis or spurious
766 close parenthesis is probably near the first of those lines.  (However,
767 don't assume this is true; study the code to make sure.)  Once you have
768 found the discrepancy, undo the @kbd{C-M-q} with @kbd{C-_}, since the
769 old indentation is probably appropriate to the intended parentheses.
771   After you think you have fixed the problem, use @kbd{C-M-q} again.  If
772 the old indentation actually fits the intended nesting of parentheses,
773 and you have put back those parentheses, @kbd{C-M-q} should not change
774 anything.
776 @node Test Coverage
777 @section Test Coverage
778 @cindex coverage testing
780 @findex testcover-start
781 @findex testcover-mark-all
782 @findex testcover-next-mark
783   You can do coverage testing for a file of Lisp code by loading the
784 @code{testcover} library and using the command @kbd{M-x
785 testcover-start @key{RET} @var{file} @key{RET}} to instrument the
786 code.  Then test your code by calling it one or more times.  Then use
787 the command @kbd{M-x testcover-mark-all} to display colored highlights
788 on the code to show where coverage is insufficient.  The command
789 @kbd{M-x testcover-next-mark} will move point forward to the next
790 highlighted spot.
792   Normally, a red highlight indicates the form was never completely
793 evaluated; a brown highlight means it always evaluated to the same
794 value (meaning there has been little testing of what is done with the
795 result).  However, the red highlight is skipped for forms that can't
796 possibly complete their evaluation, such as @code{error}.  The brown
797 highlight is skipped for forms that are expected to always evaluate to
798 the same value, such as @code{(setq x 14)}.
800   For difficult cases, you can add do-nothing macros to your code to
801 give advice to the test coverage tool.
803 @defmac 1value form
804 Evaluate @var{form} and return its value, but inform coverage testing
805 that @var{form}'s value should always be the same.
806 @end defmac
808 @defmac noreturn form
809 Evaluate @var{form}, informing coverage testing that @var{form} should
810 never return.  If it ever does return, you get a run-time error.
811 @end defmac
813   Edebug also has a coverage testing feature (@pxref{Coverage
814 Testing}).  These features partly duplicate each other, and it would
815 be cleaner to combine them.
818 @node Profiling
819 @section Profiling
820 @cindex profiling
821 @cindex measuring resource usage
822 @cindex memory usage
824 If your program is working correctly, but you want to make it run more
825 quickly or efficiently, the first thing to do is @dfn{profile} your
826 code so that you know how it is using resources.  If you find that one
827 particular function is responsible for a significant portion of the
828 runtime, you can start looking for ways to optimize that piece.
830 Emacs has built-in support for this.  To begin profiling, type
831 @kbd{M-x profiler-start}.  You can choose to profile by processor
832 usage, memory usage, or both.  After doing some work, type
833 @kbd{M-x profiler-report} to display a summary buffer for each
834 resource that you chose to profile.  The names of the report buffers
835 include the times at which the reports were generated, so you can
836 generate another report later on without erasing previous results.
837 When you have finished profiling, type @kbd{M-x profiler-stop} (there
838 is a small overhead associated with profiling).
840 The profiler report buffer shows, on each line, a function that was
841 called, followed by how much resource (processor or memory) it used in
842 absolute and percentage times since profiling started.  If a given
843 line has a @samp{+} symbol at the left-hand side, you can expand that
844 line by typing @key{RET}, in order to see the function(s) called by
845 the higher-level function.  Pressing @key{RET} again will collapse
846 back to the original state.
848 Press @kbd{j} or @kbd{mouse-2} to jump to the definition of a function.
849 Press @kbd{d} to view a function's documentation.
850 You can save a profile to a file using @kbd{C-x C-w}.
851 You can compare two profiles using @kbd{=}.
853 @c FIXME reversed calltree?
855 @cindex @file{elp.el}
856 @cindex timing programs
857 The @file{elp} library offers an alternative approach.  See the file
858 @file{elp.el} for instructions.
860 @cindex @file{benchmark.el}
861 @cindex benchmarking
862 You can check the speed of individual Emacs Lisp forms using the
863 @file{benchmark} library.  See the functions @code{benchmark-run} and
864 @code{benchmark-run-compiled} in @file{benchmark.el}.
866 @c Not worth putting in the printed manual.
867 @ifnottex
868 @cindex --enable-profiling option of configure
869 For low-level profiling of Emacs itself, you can build it using the
870 @option{--enable-profiling} option of @command{configure}.  When Emacs
871 exits, it generates a file @file{gmon.out} that you can examine using
872 the @command{gprof} utility.  This feature is mainly useful for
873 debugging Emacs.  It actually stops the Lisp-level @kbd{M-x
874 profiler-@dots{}} commands described above from working.
875 @end ifnottex