There are several ways to find and investigate problems in an Emacs Lisp program.
trace-function-foreground and
trace-function-background for tracing function calls, and
trace-values for adding values of select variables to the
trace. For the details, see the documentation of these facilities in
trace.el.
Other useful tools for debugging input and output problems are the
dribble file (see Terminal Input) and the open-termscript
function (see Terminal Output).
The ordinary Lisp debugger provides the ability to suspend evaluation of a form. While evaluation is suspended (a state that is commonly known as a break), you may examine the run time stack, examine the values of local or global variables, or change those values. Since a break is a recursive edit, all the usual editing facilities of Emacs are available; you can even run programs that will enter the debugger recursively. See Recursive Editing.
The most important time to enter the debugger is when a Lisp error happens. This allows you to investigate the immediate causes of the error.
However, entry to the debugger is not a normal consequence of an
error. Many commands signal Lisp errors when invoked inappropriately,
and during ordinary editing it would be very inconvenient to enter the
debugger each time this happens. So if you want errors to enter the
debugger, set the variable debug-on-error to non-nil.
(The command toggle-debug-on-error provides an easy way to do
this.)
Note that, for technical reasons, you cannot use the facilities defined in this subsection to debug errors in Lisp that the redisplay code has invoked. See Debugging Redisplay Errors, for help with these.
This variable determines whether the debugger is called when an error
is signaled and not handled. If debug-on-error is t,
all kinds of errors call the debugger, except those listed in
debug-ignored-errors (see below). If it is nil, none
call the debugger.
The value can also be a list of error conditions (see How to Signal an Error). Then the debugger is called only for error conditions in
this list (except those also listed in debug-ignored-errors).
For example, if you set debug-on-error to the list
(void-variable), the debugger is only called for errors about a
variable that has no value.
Note that eval-expression-debug-on-error overrides this
variable in some cases; see below.
When this variable is non-nil, Emacs does not create an error
handler around process filter functions and sentinels. Therefore,
errors in these functions also invoke the debugger. See Processes.
This variable specifies errors which should not enter the debugger,
regardless of the value of debug-on-error. Its value is a list
of error condition symbols and/or regular expressions. If the error
has any of those condition symbols, or if the error message matches
any of the regular expressions, then that error does not enter the
debugger.
The normal value of this variable includes user-error, as well
as several errors that happen often during editing but rarely result
from bugs in Lisp programs. However, “rarely” is not “never”; if
your program fails with an error that matches this list, you may try
changing this list to debug the error. The easiest way is usually to
set debug-ignored-errors to nil.
If this variable has a non-nil value (the default), running the
command eval-expression causes debug-on-error to be
temporarily bound to t. See Evaluating
Emacs Lisp Expressions in The GNU Emacs Manual.
If eval-expression-debug-on-error is nil, then the value
of debug-on-error is not changed during eval-expression.
Normally, errors caught by condition-case never invoke the
debugger. The condition-case gets a chance to handle the error
before the debugger gets a chance.
If you change debug-on-signal to a non-nil value, the
debugger gets the first chance at every error, regardless of the
presence of condition-case. (To invoke the debugger, the error
must still fulfill the criteria specified by debug-on-error and
debug-ignored-errors.)
For example, setting this variable is useful to get a backtrace from
code evaluated by emacsclient’s --eval option. If Lisp code
evaluated by emacsclient signals an error while this variable is
non-nil, the backtrace will popup in the running Emacs.
Warning: Setting this variable to non-nil may have
annoying effects. Various parts of Emacs catch errors in the normal
course of affairs, and you may not even realize that errors happen
there. If you need to debug code wrapped in condition-case,
consider using condition-case-unless-debug (see Writing Code to Handle Errors).
If you set debug-on-event to a special event (see Special Events), Emacs will try to enter the debugger as soon as it receives
this event, bypassing special-event-map. At present, the only
supported values correspond to the signals SIGUSR1 and
SIGUSR2 (this is the default). This can be helpful when
inhibit-quit is set and Emacs is not otherwise responding.
If you set debug-on-message to a regular expression,
Emacs will enter the debugger if it displays a matching message in the
echo area. For example, this can be useful when trying to find the
cause of a particular message.
You can evaluate forms in the current stack frame in the
‘*Backtrace*’ buffer with the e command, and while
edebugging you can use the e and C-x C-e commands to do
something similar. By default, the debugger is inhibited by these
commands (because (re-)entering the debugger at this point will
usually take you out of the debugging context you’re in). Set
debug-allow-recursive-debug to a non-nil value to allow
these commands to enter the debugger recursively.
To debug an error that happens during loading of the init
file, use the option ‘--debug-init’. This binds
debug-on-error to t while loading the init file, and
bypasses the condition-case which normally catches errors in the
init file.
When an error occurs in Lisp code which redisplay has invoked, Emacs’s usual debugging mechanisms are unusable, for technical reasons. This subsection describes how to get a backtrace from such an error, which should be helpful in debugging it.
These directions apply to Lisp forms used, for example, in
:eval mode line constructs (see The Data Structure of the Mode Line), and in all
hooks invoked from redisplay, such as:
fontification-functions (see Automatic Face Assignment).
window-scroll-functions (see Hooks for Window Scrolling and Changes).
Note that if you have had an error in a hook function called from
redisplay, the error handling might have removed this function from
the hook. You will thus need to reinitialize that hook somehow,
perhaps with add-hook, to be able to replay the bug.
To generate a backtrace in these circumstances, set the variable
backtrace-on-redisplay-error to non-nil. When the error
occurs, Emacs will dump the backtrace to the buffer
*Redisplay-trace*, but won’t automatically display it in a
window. This is to avoid needlessly corrupting the redisplay you are
debugging. You will thus need to display the buffer yourself, with a
command such as switch-to-buffer-other-frame C-x 5 b.
Set this variable to non-nil to enable the generation of a
backtrace when an error occurs in any Lisp called from redisplay.
When a program loops infinitely and fails to return, your first problem is to stop the loop. On most operating systems, you can do this with C-g, which causes a quit. See Quitting.
Ordinary quitting gives no information about why the program was
looping. To get more information, you can set the variable
debug-on-quit to non-nil. Once you have the debugger
running in the middle of the infinite loop, you can proceed from the
debugger using the stepping commands. If you step through the entire
loop, you may get enough information to solve the problem.
Quitting with C-g is not considered an error, and
debug-on-error has no effect on the handling of C-g.
Likewise, debug-on-quit has no effect on errors.
This variable determines whether the debugger is called when
quit is signaled and not handled. If debug-on-quit is
non-nil, then the debugger is called whenever you quit (that
is, type C-g). If debug-on-quit is nil (the
default), then the debugger is not called when you quit.
To investigate a problem that happens in the middle of a program, one useful technique is to enter the debugger whenever a certain function is called. You can do this to the function in which the problem occurs, and then step through the function, or you can do this to a function called shortly before the problem, step quickly over the call to that function, and then step through its caller.
This function requests function-name to invoke the debugger each time it is called.
Any function or macro defined as Lisp code may be set to break on entry, regardless of whether it is interpreted code or compiled code. If the function is a command, it will enter the debugger when called from Lisp and when called interactively (after the reading of the arguments). You can also set debug-on-entry for primitive functions (i.e., those written in C) this way, but it only takes effect when the primitive is called from Lisp code. Debug-on-entry is not allowed for special forms.
When debug-on-entry is called interactively, it prompts for
function-name in the minibuffer. If the function is already set
up to invoke the debugger on entry, debug-on-entry does nothing.
debug-on-entry always returns function-name.
Here’s an example to illustrate use of this function:
(defun fact (n)
(if (zerop n) 1
(* n (fact (1- n)))))
⇒ fact
(debug-on-entry 'fact)
⇒ fact
(fact 3)
------ Buffer: *Backtrace* ------ Debugger entered--entering a function: * fact(3) eval((fact 3)) eval-last-sexp-1(nil) eval-last-sexp(nil) call-interactively(eval-last-sexp) ------ Buffer: *Backtrace* ------
This function undoes the effect of debug-on-entry on
function-name. When called interactively, it prompts for
function-name in the minibuffer. If function-name is
omitted or nil, it cancels break-on-entry for all functions.
Calling cancel-debug-on-entry does nothing to a function which is
not currently set up to break on entry.
Sometimes a problem with a function is due to a wrong setting of a variable. Setting up the debugger to trigger whenever the variable is changed is a quick way to find the origin of the setting.
This function arranges for the debugger to be called whenever variable is modified.
It is implemented using the watchpoint mechanism, so it inherits the same characteristics and limitations: all aliases of variable will be watched together, only dynamic variables can be watched, and changes to the objects referenced by variables are not detected. For details, see Running a function when a variable is changed..
This function undoes the effect of debug-on-variable-change on
variable. When called interactively, it prompts for
variable in the minibuffer. If variable is omitted or
nil, it cancels break-on-change for all variables. Calling
cancel-debug-on-variable-change does nothing to a variable
which is not currently set up to break on change.
You can cause the debugger to be called at a certain point in your
program by writing the expression (debug) at that point. To do
this, visit the source file, insert the text ‘(debug)’ at the
proper place, and type C-M-x (eval-defun, a Lisp mode key
binding). Warning: if you do this for temporary debugging
purposes, be sure to undo this insertion before you save the file!
The place where you insert ‘(debug)’ must be a place where an
additional form can be evaluated and its value ignored. (If the value
of (debug) isn’t ignored, it will alter the execution of the
program!) The most common suitable places are inside a progn or
an implicit progn (see Sequencing).
If you don’t know exactly where in the source code you want to put
the debug statement, but you want to display a backtrace when a
certain message is displayed, you can set debug-on-message to a
regular expression matching the desired message.
When the debugger is entered, it displays the previously selected buffer in one window and a buffer named *Backtrace* in another window. The backtrace buffer contains one line for each level of Lisp function execution currently going on. At the beginning of this buffer is a message describing the reason that the debugger was invoked (such as the error message and associated data, if it was invoked due to an error).
The backtrace buffer is read-only and uses a special major mode,
Debugger mode, in which letters are defined as debugger commands. The
usual Emacs editing commands are available; thus, you can switch windows
to examine the buffer that was being edited at the time of the error,
switch buffers, visit files, or do any other sort of editing. However,
the debugger is a recursive editing level (see Recursive Editing)
and it is wise to go back to the backtrace buffer and exit the debugger
(with the q command) when you are finished with it. Exiting
the debugger gets out of the recursive edit and buries the backtrace
buffer. (You can customize what the q command does with the
backtrace buffer by setting the variable debugger-bury-or-kill.
For example, set it to kill if you prefer to kill the buffer
rather than bury it. Consult the variable’s documentation for more
possibilities.)
When the debugger has been entered, the debug-on-error
variable is temporarily set according to
eval-expression-debug-on-error. If the latter variable is
non-nil, debug-on-error will temporarily be set to
t. However, further errors that occur while debugging won’t
(by default) trigger another debugger, because inhibit-debugger
will also be bound to non-nil.
The debugger itself must be run byte-compiled, since it makes assumptions about the state of the Lisp interpreter. These assumptions are false if the debugger is running interpreted.
Debugger mode is derived from Backtrace mode, which is also used to show backtraces by Edebug and ERT. (see Edebug, and the ERT manual in ERT: Emacs Lisp Regression Testing.)
The backtrace buffer shows you the functions that are executing and their argument values. When a backtrace buffer is created, it shows each stack frame on one, possibly very long, line. (A stack frame is the place where the Lisp interpreter records information about a particular invocation of a function.) The most recently called function will be at the top.
In a backtrace you can specify a stack frame by moving point to a line describing that frame. The frame whose line point is on is considered the current frame.
If a function name is underlined, that means Emacs knows where its
source code is located. You can click with the mouse on that name, or
move to it and type RET, to visit the source code. You can also
type RET while point is on any name of a function or variable
which is not underlined, to see help information for that symbol in a
help buffer, if any exists. The xref-find-definitions command,
bound to M-., can also be used on any identifier in a backtrace
(see Looking Up Identifiers in The GNU Emacs Manual).
In backtraces, the tails of long lists and the ends of long strings,
vectors or structures, as well as objects which are deeply nested,
will be printed as underlined “...”. You can click with the mouse
on a “...”, or type RET while point is on it, to show the part
of the object that was hidden. To control how much abbreviation is
done, customize backtrace-line-length.
Here is a list of commands for navigating and viewing backtraces:
Toggle the display of local variables of the current stack frame.
Move to the beginning of the frame, or to the beginning of the previous frame.
Move to the beginning of the next frame.
Add line breaks and indentation to the top-level Lisp form at point to make it more readable.
Collapse the top-level Lisp form at point back to a single line.
Toggle print-circle for the frame at point.
Toggle print-gensym for the frame at point.
Expand all the forms abbreviated with “...” in the frame at point.
The debugger buffer (in Debugger mode) provides special commands in addition to the usual Emacs commands and to the Backtrace mode commands described in the previous section. The most important use of debugger commands is for stepping through code, so that you can see how control flows. The debugger can step through the control structures of an interpreted function, but cannot do so in a byte-compiled function. If you would like to step through a byte-compiled function, replace it with an interpreted definition of the same function. (To do this, visit the source for the function and type C-M-x on its definition.) You cannot use the Lisp debugger to step through a primitive function.
Some of the debugger commands operate on the current frame. If a frame starts with a star, that means that exiting that frame will call the debugger again. This is useful for examining the return value of a function.
Here is a list of Debugger mode commands:
Exit the debugger and continue execution. This resumes execution of the program as if the debugger had never been entered (aside from any side-effects that you caused by changing variable values or data structures while inside the debugger).
Continue execution, but enter the debugger the next time any Lisp function is called. This allows you to step through the subexpressions of an expression, seeing what values the subexpressions compute, and what else they do.
The stack frame made for the function call which enters the debugger in this way will be flagged automatically so that the debugger will be called again when the frame is exited. You can use the u command to cancel this flag.
Flag the current frame so that the debugger will be entered when the frame is exited. Frames flagged in this way are marked with stars in the backtrace buffer.
Don’t enter the debugger when the current frame is exited. This cancels a b command on that frame. The visible effect is to remove the star from the line in the backtrace buffer.
Flag the current frame like b. Then continue execution like
c, but temporarily disable break-on-entry for all functions that
are set up to do so by debug-on-entry.
Read a Lisp expression in the minibuffer, evaluate it (with the
relevant lexical environment, if applicable), and print the
value in the echo area. The debugger alters certain important
variables, and the current buffer, as part of its operation; e
temporarily restores their values from outside the debugger, so you can
examine and change them. This makes the debugger more transparent. By
contrast, M-: does nothing special in the debugger; it shows you
the variable values within the debugger. By default, this command
suppresses the debugger during evaluation, so that an error in the
evaluated expression won’t add a new error on top of the existing one.
Set the debug-allow-recursive-debug user option to a
non-nil value to override this.
Like e, but also save the result of evaluation in the buffer *Debugger-record*.
Terminate the program being debugged; return to top-level Emacs command execution.
If the debugger was entered due to a C-g but you really want to quit, and not debug, use the q command.
Return a value from the debugger. The value is computed by reading an expression with the minibuffer and evaluating it.
The r command is useful when the debugger was invoked due to exit
from a Lisp call frame (as requested with b or by entering the
frame with d); then the value specified in the r command is
used as the value of that frame. It is also useful if you call
debug and use its return value. Otherwise, r has the same
effect as c, and the specified return value does not matter.
You can’t use r when the debugger was entered due to an error.
Display a list of functions that will invoke the debugger when called.
This is a list of functions that are set to break on entry by means of
debug-on-entry.
Here we describe in full detail the function debug that is used
to invoke the debugger.
This function enters the debugger. In interactive sessions, it
switches to a buffer named *Backtrace* (or
*Backtrace*<2> if it is the second recursive entry to the
debugger, etc.), and fills it with information about the stack of Lisp
function calls. It then enters a recursive edit, showing the
backtrace buffer in Debugger mode. In batch mode (more generally,
when noninteractive is non-nil, see Batch Mode),
this function shows the Lisp backtrace on the standard error stream.
Binding backtrace-on-error-noninteractive to nil
suppresses the backtrace in batch mode, see below.
The Debugger mode c, d, j, and r commands exit
the recursive edit; then debug switches back to the previous
buffer and returns to whatever called debug. This is the only
way the function debug can return to its caller.
The use of the debugger-args is that debug displays the
rest of its arguments at the top of the *Backtrace* buffer, so
that the user can see them. Except as described below, this is the
only way these arguments are used.
However, certain values for first argument to debug have a
special significance. (Normally, these values are used only by the
internals of Emacs, and not by programmers calling debug.) Here
is a table of these special values:
lambda ¶A first argument of lambda means debug was called
because of entry to a function when debug-on-next-call was
non-nil. The debugger displays ‘Debugger
entered--entering a function:’ as a line of text at the top of the
buffer.
debugdebug as first argument means debug was called because
of entry to a function that was set to debug on entry. The debugger
displays the string ‘Debugger entered--entering a function:’,
just as in the lambda case. It also marks the stack frame for
that function so that it will invoke the debugger when exited.
tWhen the first argument is t, this indicates a call to
debug due to evaluation of a function call form when
debug-on-next-call is non-nil. The debugger displays
‘Debugger entered--beginning evaluation of function call form:’
as the top line in the buffer.
exitWhen the first argument is exit, it indicates the exit of a
stack frame previously marked to invoke the debugger on exit. The
second argument given to debug in this case is the value being
returned from the frame. The debugger displays ‘Debugger
entered--returning value:’ in the top line of the buffer, followed by
the value being returned.
error ¶When the first argument is error, the debugger indicates that
it is being entered because an error or quit was signaled and
not handled, by displaying ‘Debugger entered--Lisp error:’
followed by the error signaled and any arguments to signal.
For example,
(let ((debug-on-error t)) (/ 1 0))
------ Buffer: *Backtrace* ------ Debugger entered--Lisp error: (arith-error) /(1 0) ... ------ Buffer: *Backtrace* ------
If an error was signaled, presumably the variable
debug-on-error is non-nil. If quit was signaled,
then presumably the variable debug-on-quit is non-nil.
nilUse nil as the first of the debugger-args when you want
to enter the debugger explicitly. The rest of the debugger-args
are printed on the top line of the buffer. You can use this feature to
display messages—for example, to remind yourself of the conditions
under which debug is called.
If this variable is non-nil, the default, entering the debugger
in batch mode shows the backtrace of Lisp functions calls. Binding
the variable to the nil value suppresses the backtrace and
shows only the error message.
This section describes functions and variables used internally by the debugger.
The value of this variable is the function to call to invoke the
debugger. Its value must be a function of any number of arguments, or,
more typically, the name of a function. This function should invoke
some kind of debugger. The default value of the variable is
debug.
The first argument that Lisp hands to the function indicates why it
was called. The convention for arguments is detailed in the description
of debug (see Invoking the Debugger).
This function prints a trace of Lisp function calls currently active.
The trace is identical to the one that debug would show in the
*Backtrace* buffer. The return value is always nil.
In the following example, a Lisp expression calls backtrace
explicitly. This prints the backtrace to the stream
standard-output, which, in this case, is the buffer
‘backtrace-output’.
Each line of the backtrace represents one function call. The line shows the function followed by a list of the values of the function’s arguments if they are all known; if they are still being computed, the line consists of a list containing the function and its unevaluated arguments. Long lists or deeply nested structures may be elided.
(with-output-to-temp-buffer "backtrace-output"
(let ((var 1))
(save-excursion
(setq var (eval '(progn
(1+ var)
(list 'testing (backtrace))))))))
⇒ (testing nil)
----------- Buffer: backtrace-output ------------ backtrace() (list 'testing (backtrace))
(progn ...) eval((progn (1+ var) (list 'testing (backtrace)))) (setq ...) (save-excursion ...) (let ...) (with-output-to-temp-buffer ...) eval((with-output-to-temp-buffer ...)) eval-last-sexp-1(nil)
eval-last-sexp(nil) call-interactively(eval-last-sexp) ----------- Buffer: backtrace-output ------------
If this variable is non-nil, every stack frame of the backtrace
is displayed as a list. This aims at improving the backtrace
readability at the cost of special forms no longer being visually
different from regular function calls.
With debugger-stack-frame-as-list non-nil, the above
example would look as follows:
----------- Buffer: backtrace-output ------------ (backtrace) (list 'testing (backtrace))
(progn ...) (eval (progn (1+ var) (list 'testing (backtrace)))) (setq ...) (save-excursion ...) (let ...) (with-output-to-temp-buffer ...) (eval (with-output-to-temp-buffer ...)) (eval-last-sexp-1 nil)
(eval-last-sexp nil) (call-interactively eval-last-sexp) ----------- Buffer: backtrace-output ------------
If this variable is non-nil, it says to call the debugger before
the next eval, apply or funcall. Entering the
debugger sets debug-on-next-call to nil.
The d command in the debugger works by setting this variable.
This function sets the debug-on-exit flag of the stack frame level
levels down the stack, giving it the value flag. If flag is
non-nil, this will cause the debugger to be entered when that
frame later exits. Even a nonlocal exit through that frame will enter
the debugger.
This function is used only by the debugger.
This variable records the debugging status of the current interactive
command. Each time a command is called interactively, this variable is
bound to nil. The debugger can set this variable to leave
information for future debugger invocations during the same command
invocation.
The advantage of using this variable rather than an ordinary global variable is that the data will never carry over to a subsequent command invocation.
This variable is obsolete and will be removed in future versions.
The function backtrace-frame is intended for use in Lisp
debuggers. It returns information about what computation is happening
in the stack frame frame-number levels down.
If that frame has not evaluated the arguments yet, or is a special
form, the value is (nil function arg-forms…).
If that frame has evaluated its arguments and called its function
already, the return value is (t function
arg-values…).
In the return value, function is whatever was supplied as the
CAR of the evaluated list, or a lambda expression in the
case of a macro call. If the function has a &rest argument, that
is represented as the tail of the list arg-values.
If base is specified, frame-number counts relative to the topmost frame whose function is base.
If frame-number is out of range, backtrace-frame returns
nil.
The function mapbacktrace calls function once for each
frame in the backtrace, starting at the first frame whose function is
base (or from the top if base is omitted or nil).
function is called with four arguments: evald, func, args, and flags.
If a frame has not evaluated its arguments yet or is a special form,
evald is nil and args is a list of forms.
If a frame has evaluated its arguments and called its function
already, evald is t and args is a list of values.
flags is a plist of properties of the current frame: currently,
the only supported property is :debug-on-exit, which is
t if the stack frame’s debug-on-exit flag is set.
Edebug is a source-level debugger for Emacs Lisp programs, with which you can:
The first three sections below should tell you enough about Edebug to start using it.
To debug a Lisp program with Edebug, you must first instrument
the Lisp code that you want to debug. A simple way to do this is to
first move point into the definition of a function or macro and then do
C-u C-M-x (eval-defun with a prefix argument).
See Instrumenting for Edebug, for alternative ways to instrument code.
Once a function is instrumented, any call to the function activates Edebug. Depending on which Edebug execution mode you have selected, activating Edebug may stop execution and let you step through the function, or it may update the display and continue execution while checking for debugging commands. The default execution mode is step, which stops execution. See Edebug Execution Modes.
When you are done debugging and want to run the function without instrumentation, you can remove the instrumentation using one of the methods described in Instrumenting for Edebug.
Within Edebug, you normally view an Emacs buffer showing the source of the Lisp code you are debugging. This is referred to as the source code buffer, and it is temporarily read-only.
An arrow in the left fringe indicates the line where the function is executing. Point initially shows where within the line the function is executing, but this ceases to be true if you move point yourself.
If you instrument the definition of fac (shown below) and then
execute (fac 3), here is what you would normally see. Point is
at the open-parenthesis before if.
(defun fac (n)
=>∗(if (< 0 n)
(* n (fac (1- n)))
1))
The places within a function where Edebug can stop execution are called
stop points. These occur both before and after each subexpression
that is a list, and also after each variable reference.
Here we use periods to show the stop points in the function
fac:
(defun fac (n)
.(if .(< 0 n.).
.(* n. .(fac .(1- n.).).).
1).)
The special commands of Edebug are available in the source code buffer
in addition to the commands of Emacs Lisp mode. For example, you can
type the Edebug command SPC to execute until the next stop point.
If you type SPC once after entry to fac, here is the
display you will see:
(defun fac (n)
=>(if ∗(< 0 n)
(* n (fac (1- n)))
1))
When Edebug stops execution after an expression, it displays the expression’s value in the echo area.
Other frequently used commands are b to set a breakpoint at a stop point, g to execute until a breakpoint is reached, and q to exit Edebug and return to the top-level command loop. Type ? to display a list of all Edebug commands.
In order to use Edebug to debug Lisp code, you must first instrument the code. Instrumenting code inserts additional code into it, to invoke Edebug at the proper places.
When you invoke command C-M-x (eval-defun) with a
prefix argument on a function definition, it instruments the
definition before evaluating it. (This does not modify the source
code itself.) If the variable edebug-all-defs is
non-nil, that inverts the meaning of the prefix argument: in
this case, C-M-x instruments the definition unless it has
a prefix argument. The default value of edebug-all-defs is
nil. The command M-x edebug-all-defs toggles the value
of the variable edebug-all-defs.
If edebug-all-defs is non-nil, then the commands
eval-region, and eval-buffer also instrument any
definitions they evaluate. Similarly, edebug-all-forms
controls whether eval-region should instrument any form,
even non-defining forms. This doesn’t apply to loading or evaluations
in the minibuffer. The command M-x edebug-all-forms toggles
this option.
Another command, M-x edebug-eval-top-level-form, is available to
instrument any top-level form regardless of the values of
edebug-all-defs and edebug-all-forms.
edebug-defun is an alias for edebug-eval-top-level-form.
While Edebug is active, the command I
(edebug-instrument-callee) instruments the definition of the
function or macro called by the list form after point, if it is not already
instrumented. This is possible only if Edebug knows where to find the
source for that function; for this reason, after loading Edebug,
eval-region records the position of every definition it
evaluates, even if not instrumenting it. See also the i command
(see Jumping), which steps into the call after instrumenting the
function.
Edebug knows how to instrument all the standard special forms,
interactive forms with an expression argument, anonymous lambda
expressions, and other defining forms. However, Edebug cannot determine
on its own what a user-defined macro will do with the arguments of a
macro call, so you must provide that information using Edebug
specifications; for details, see Edebug and Macros.
When Edebug is about to instrument code for the first time in a
session, it runs the hook edebug-setup-hook, then sets it to
nil. You can use this to load Edebug specifications
associated with a package you are using, but only when you use Edebug.
If Edebug detects a syntax error while instrumenting, it leaves point
at the erroneous code and signals an invalid-read-syntax error.
Example:
error→ Invalid read syntax: "Expected lambda expression"
One potential reason for such a failure to instrument is that some macro definitions are not yet known to Emacs. To work around this, load the file which defines the function you are about to instrument.
To remove instrumentation from a definition, simply re-evaluate its
definition in a way that does not instrument. There are two ways of
evaluating forms that never instrument them: from a file with
load, and from the minibuffer with eval-expression
(M-:). In addition, C-M-x without prefix argument and with
edebug-all-defs set to nil also evaluates the function’s
definition without instrumenting it.
A different way to remove the instrumentation from a definition is
to use the edebug-remove-instrumentation command. It also
allows removing the instrumentation from everything that has been
instrumented.
See Evaluation, for other evaluation functions available inside of Edebug.
Edebug supports several execution modes for running the program you are debugging. We call these alternatives Edebug execution modes; do not confuse them with major or minor modes. The current Edebug execution mode determines how far Edebug continues execution before stopping—whether it stops at each stop point, or continues to the next breakpoint, for example—and how much Edebug displays the progress of the evaluation before it stops.
Normally, you specify the Edebug execution mode by typing a command to continue the program in a certain mode. Here is a table of these commands; all except for S resume execution of the program, at least for a certain distance.
Stop: don’t execute any more of the program, but wait for more
Edebug commands (edebug-stop).
Step: stop at the next stop point encountered (edebug-step-mode).
Next: stop at the next stop point encountered after an expression
(edebug-next-mode). Also see edebug-forward-sexp in
Jumping.
Trace: pause (normally one second) at each Edebug stop point
(edebug-trace-mode).
Rapid trace: update the display at each stop point, but don’t actually
pause (edebug-Trace-fast-mode).
Go: run until the next breakpoint (edebug-go-mode). See Edebug Breakpoints.
Continue: pause one second at each breakpoint, and then continue
(edebug-continue-mode).
Rapid continue: move point to each breakpoint, but don’t pause
(edebug-Continue-fast-mode).
Go non-stop: ignore breakpoints (edebug-Go-nonstop-mode). You
can still stop the program by typing S, or any editing command.
In general, the execution modes earlier in the above list run the program more slowly or stop sooner than the modes later in the list.
When you enter a new Edebug level, Edebug will normally stop at the
first instrumented function it encounters. If you prefer to stop only
at a break point, or not at all (for example, when gathering coverage
data), change the value of edebug-initial-mode from its default
step to go, or Go-nonstop, or one of its other
values (see Edebug Options). You can do this readily with
C-x C-a C-m (edebug-set-initial-mode):
This command, bound to C-x C-a C-m, sets
edebug-initial-mode. It prompts you for a key to indicate the
mode. You should enter one of the eight keys listed above, which sets
the corresponding mode.
Note that you may reenter the same Edebug level several times if, for example, an instrumented function is called several times from one command.
While executing or tracing, you can interrupt the execution by typing any Edebug command. Edebug stops the program at the next stop point and then executes the command you typed. For example, typing t during execution switches to trace mode at the next stop point. You can use S to stop execution without doing anything else.
If your function happens to read input, a character you type intending to interrupt execution may be read by the function instead. You can avoid such unintended results by paying attention to when your program wants input.
Keyboard macros containing the commands in this section do not
completely work: exiting from Edebug, to resume the program, loses track
of the keyboard macro. This is not easy to fix. Also, defining or
executing a keyboard macro outside of Edebug does not affect commands
inside Edebug. This is usually an advantage. See also the
edebug-continue-kbd-macro option in Edebug Options.
This option specifies how many seconds to wait between execution steps in trace mode or continue mode. The default is 1 second.
The commands described in this section execute until they reach a specified location. All except i make a temporary breakpoint to establish the place to stop, then switch to go mode (see Edebug Execution Modes). Any other breakpoint reached before the intended stop point will also stop execution. See Edebug Breakpoints, for the details on breakpoints.
These commands may fail to work as expected in case of nonlocal exit, as that can bypass the temporary breakpoint where you expected the program to stop.
Proceed to the stop point near where point is (edebug-goto-here).
Run the program for one expression
(edebug-forward-sexp).
Run the program until the end of the containing sexp (edebug-step-out).
Step into the function or macro called by the form after point
(edebug-step-in).
The h command proceeds to the stop point at or after the current location of point, using a temporary breakpoint.
The f command runs the program forward over one expression. More
precisely, it sets a temporary breakpoint at the position that
forward-sexp would reach, then executes in go mode so that
the program will stop at breakpoints.
With a prefix argument n, the temporary breakpoint is placed n sexps beyond point. If the containing list ends before n more elements, then the place to stop is after the containing expression.
You must check that the position forward-sexp finds is a place
that the program will really get to. In cond, for example,
this may not be true.
For flexibility, the f command does forward-sexp starting
at point, rather than at the stop point. If you want to execute one
expression from the current stop point, first type w
(edebug-where) to move point there, and then type f.
The o command continues out of an expression. It places a temporary breakpoint at the end of the sexp containing point. If the containing sexp is a function definition itself, o continues until just before the last sexp in the definition. If that is where you are now, it returns from the function and then stops. In other words, this command does not exit the currently executing function unless you are positioned after the last sexp of that function.
Normally, the h, f, and o commands display “Break”
and pause for edebug-sit-for-seconds before showing the result
of the form just evaluated. You can avoid this pause by setting
edebug-sit-on-break to nil. See Edebug Options.
The i command steps into the function or macro called by the list form after point, and stops at its first stop point. Note that the form need not be the one about to be evaluated. But if the form is a function call about to be evaluated, remember to use this command before any of the arguments are evaluated, since otherwise it will be too late.
The i command instruments the function or macro it’s supposed to step into, if it isn’t instrumented already. This is convenient, but keep in mind that the function or macro remains instrumented unless you explicitly arrange to deinstrument it.
Some miscellaneous Edebug commands are described here.
Display the help message for Edebug (edebug-help).
Abort one level back to the previous command level
(abort-recursive-edit). See Recursive Editing.
Return to the top level editor command loop (top-level). This
exits all recursive editing levels, including all levels of Edebug
activity. However, instrumented code protected with
unwind-protect or condition-case forms may resume
debugging.
Like q, but don’t stop even for protected code
(edebug-top-level-nonstop).
Redisplay the most recently known expression result in the echo area
(edebug-previous-result).
Display a backtrace, excluding Edebug’s own functions for clarity
(edebug-pop-to-backtrace).
See Backtraces, for a description of backtraces and the commands which work on them.
If you would like to see Edebug’s functions in the backtrace, use M-x edebug-backtrace-show-instrumentation. To hide them again use M-x edebug-backtrace-hide-instrumentation.
If a backtrace frame starts with ‘>’ that means that Edebug knows where the source code for the frame is located. Use s to jump to the source code for the current frame.
The backtrace buffer is killed automatically when you continue execution.
You can invoke commands from Edebug that activate Edebug again recursively. Whenever Edebug is active, you can quit to the top level with q or abort one recursive edit level with C-]. You can display a backtrace of all the pending evaluations with d.
Edebug’s step mode (see Edebug Execution Modes) stops execution when the next stop point is reached. There are three other ways to stop Edebug execution once it has started: breakpoints, the global break condition, and source breakpoints.
While using Edebug, you can specify breakpoints in the program you are testing: these are places where execution should stop. You can set a breakpoint at any stop point, as defined in Using Edebug. For setting and unsetting breakpoints, the stop point that is affected is the first one at or after point in the source code buffer. Here are the Edebug commands for breakpoints:
Set a breakpoint at the stop point at or after point
(edebug-set-breakpoint). If you use a prefix argument, the
breakpoint is temporary—it turns off the first time it stops the
program. An overlay with the edebug-enabled-breakpoint or
edebug-disabled-breakpoint faces is put at the breakpoint.
Unset the breakpoint (if any) at the stop point at or after
point (edebug-unset-breakpoint).
Unset any breakpoints in the current form
(edebug-unset-breakpoints).
Toggle whether to disable the breakpoint near point
(edebug-toggle-disable-breakpoint). This command is mostly
useful if the breakpoint is conditional and it would take some work to
recreate the condition.
Set a conditional breakpoint which stops the program only if
evaluating condition produces a non-nil value
(edebug-set-conditional-breakpoint). With a prefix argument,
the breakpoint is temporary.
Set edebug-global-break-condition to condition.
Move point to the next breakpoint in the current definition
(edebug-next-breakpoint).
While in Edebug, you can set a breakpoint with b and unset one with u. First move point to the Edebug stop point of your choice, then type b or u to set or unset a breakpoint there. Unsetting a breakpoint where none has been set has no effect.
Re-evaluating or reinstrumenting a definition removes all of its previous breakpoints.
A conditional breakpoint tests a condition each time the program
gets there. Any errors that occur as a result of evaluating the
condition are ignored, as if the result were nil. To set a
conditional breakpoint, use x, and specify the condition
expression in the minibuffer. Setting a conditional breakpoint at a
stop point that has a previously established conditional breakpoint puts
the previous condition expression in the minibuffer so you can edit it.
(You can also use X to set the global break condition, to be
evaluated at every stop point, see Global Break Condition.)
You can make a conditional or unconditional breakpoint temporary by using a prefix argument with the command to set the breakpoint. When a temporary breakpoint stops the program, it is automatically unset.
Edebug always stops or pauses at a breakpoint, except when the Edebug mode is Go-nonstop. In that mode, it ignores breakpoints entirely.
To find out where your breakpoints are, use the B command, which moves point to the next breakpoint following point, within the same function, or to the first breakpoint if there are no following breakpoints. This command does not continue execution—it just moves point in the buffer.
A global break condition stops execution when a specified
condition is satisfied, no matter where that may occur. Edebug
evaluates the global break condition at every stop point; if it
evaluates to a non-nil value, then execution stops or pauses
depending on the execution mode (see Edebug Execution Modes), as if
a breakpoint had been hit. If evaluating the condition gets an error,
execution does not stop.
The condition expression is stored in
edebug-global-break-condition. You can specify a new expression
using the X command from the source code buffer while Edebug is
active, or using C-x X X from any buffer at any time, as long as
Edebug is loaded (edebug-set-global-break-condition).
The global break condition is the simplest way to find where in your
code some event occurs, but it makes code run much more slowly. So you
should reset the condition to nil when not using it.
All breakpoints in a definition are forgotten each time you
reinstrument it. If you wish to make a breakpoint that won’t be
forgotten, you can write a source breakpoint, which is simply a
call to the function edebug in your source code. You can, of
course, make such a call conditional. For example, in the fac
function, you can insert the first line as shown below, to stop when the
argument reaches zero:
(defun fac (n)
(if (= n 0) (edebug))
(if (< 0 n)
(* n (fac (1- n)))
1))
When the fac definition is instrumented and the function is
called, the call to edebug acts as a breakpoint. Depending on
the execution mode (see Edebug Execution Modes), Edebug stops or
pauses there.
If no instrumented code is being executed when edebug is called,
that function calls debug.
Emacs normally displays an error message when an error is signaled and
not handled with condition-case. While Edebug is active and
executing instrumented code, it normally responds to all unhandled
errors. You can customize this with the options edebug-on-error
and edebug-on-quit; see Edebug Options.
When Edebug responds to an error, it shows the last stop point encountered before the error. This may be the location of a call to a function which was not instrumented, and within which the error actually occurred. For an unbound variable error, the last known stop point might be quite distant from the offending variable reference. In that case, you might want to display a full backtrace (see Miscellaneous Edebug Commands).
If you change debug-on-error or debug-on-quit while
Edebug is active, these changes will be forgotten when Edebug becomes
inactive. Furthermore, during Edebug’s recursive edit, these variables
are bound to the values they had outside of Edebug.
These Edebug commands let you view aspects of the buffer and window status as they were before entry to Edebug. The outside window configuration is the collection of windows and contents that were in effect outside of Edebug.
Switch to viewing the outside window configuration
(edebug-view-outside). Type C-x X w to return to Edebug.
Temporarily display the outside current buffer with point at its
outside position (edebug-bounce-point), pausing for one second
before returning to Edebug. With a prefix argument n, pause for
n seconds instead.
Temporarily display the outside current buffer with the outside point
corresponding to the previously-evaluated value
(edebug-bounce-to-previous-value), pausing for one second
before returning to Edebug. With a prefix argument n, pause for
n seconds instead.
Move point back to the current stop point in the source code buffer
(edebug-where).
If you use this command in a different window displaying the same buffer, that window will be used instead to display the current definition in the future.
Toggle whether Edebug saves and restores the outside window
configuration (edebug-toggle-save-windows).
With a prefix argument, W only toggles saving and restoring of the selected window. To specify a window that is not displaying the source code buffer, you must use C-x X W from the global keymap.
You can view the outside window configuration with v or just bounce to the point in the current buffer with p, even if it is not normally displayed.
You can also bounce to buffer positions other than the current point. Suppose you are debugging the form
(make-overlay beg end)
and you would like to know where beg and end are located
in the outside buffer. Then you could either evaluate these, for
example, with C-x C-e, or step over them with n, and
immediately after that press P, to bounce to the position you have
previously evaluated. The previous value for the purpose of the P
command is what Edebug has evaluated before its last stop point or what
you have evaluated in the context outside of Edebug, for example, with
C-x C-e.
After moving point, you may wish to jump back to the stop point. You can do that with w from a source code buffer. You can jump back to the stop point in the source code buffer from any buffer using C-x X w.
Each time you use W to turn saving off, Edebug forgets the saved outside window configuration—so that even if you turn saving back on, the current window configuration remains unchanged when you next exit Edebug (by continuing the program). However, the automatic redisplay of *edebug* and *edebug-trace* may conflict with the buffers you wish to see unless you have enough windows open.
While within Edebug, you can evaluate expressions as if Edebug were not running. Edebug tries to be invisible to the expression’s evaluation and printing. Evaluation of expressions that cause side effects will work as expected, except for changes to data that Edebug explicitly saves and restores. See The Outside Context, for details on this process.
Evaluate expression exp in the context outside of Edebug
(edebug-eval-expression). That is, Edebug tries to minimize
its interference with the evaluation. The result is shown in the echo
area, or, if this command is given a prefix, pop up a new buffer and
pretty-print the result there.
By default, this command
suppresses the debugger during evaluation, so that an error in the
evaluated expression won’t add a new error on top of the existing one.
Set the debug-allow-recursive-debug user option (see Entering the Debugger on an Error) to a non-nil value to override this.
Evaluate expression exp in the context of Edebug itself
(eval-expression).
Evaluate the expression before point, in the context outside of Edebug
(edebug-eval-last-sexp) and show the value in the minibuffer.
With the prefix argument of zero (C-u 0 C-x C-e), don’t shorten
long items (like strings and lists) when showing the value, due to
edebug-print-length and edebug-print-level
(see Printing in Edebug). Any other prefix will result in the value
being pretty-printed in a separate buffer instead of the minibuffer.
See Evaluation List Buffer, for additional Edebug features related to evaluating lists of expressions interactively.
Edebug supports evaluation of expressions containing references to
lexically bound symbols created by the following constructs in
cl-lib.el: cl-macrolet and cl-symbol-macrolet.
You can use the evaluation list buffer, called *edebug*, to evaluate expressions interactively. You can also set up the evaluation list of expressions to be evaluated automatically each time Edebug updates the display.
Switch to the evaluation list buffer *edebug*
(edebug-visit-eval-list).
In the *edebug* buffer you can use the commands of Lisp Interaction mode (see Lisp Interaction in The GNU Emacs Manual) as well as these special commands:
Evaluate the expression before point, in the outside context, and
insert the value in the buffer (edebug-eval-print-last-sexp).
With prefix argument of zero (C-u 0 C-j), don’t shorten long
items (like strings and lists) due to edebug-print-length and
edebug-print-level (see Printing in Edebug).
Evaluate the expression before point, in the context outside of Edebug
(edebug-eval-last-sexp).
Build a new evaluation list from the contents of the buffer
(edebug-update-eval-list).
Delete the evaluation list group that point is in
(edebug-delete-eval-item).
Switch back to the source code buffer at the current stop point
(edebug-where).
You can evaluate expressions in the evaluation list window with C-j or C-x C-e, just as you would in *scratch*; but they are evaluated in the context outside of Edebug.
The expressions you enter interactively (and their results) are lost when you continue execution; but you can set up an evaluation list consisting of expressions to be evaluated each time execution stops.
To do this, write one or more evaluation list groups in the evaluation list buffer. An evaluation list group consists of one or more Lisp expressions. Groups are separated by comment lines.
The command C-c C-u (edebug-update-eval-list) rebuilds the
evaluation list, scanning the buffer and using the first expression of
each group. (The idea is that the second expression of the group is the
value previously computed and displayed.)
Each entry to Edebug redisplays the evaluation list by inserting each expression in the buffer, followed by its current value. It also inserts comment lines so that each expression becomes its own group. Thus, if you type C-c C-u again without changing the buffer text, the evaluation list is effectively unchanged.
If an error occurs during an evaluation from the evaluation list, the error message is displayed in a string as if it were the result. Therefore, expressions using variables that are not currently valid do not interrupt your debugging.
Here is an example of what the evaluation list window looks like after several expressions have been added to it:
(current-buffer) #<buffer *scratch*> ;---------------------------------------------------------------
(selected-window) #<window 16 on *scratch*> ;---------------------------------------------------------------
(point) 196 ;---------------------------------------------------------------
bad-var "Symbol's value as variable is void: bad-var" ;---------------------------------------------------------------
(recursion-depth) 0 ;---------------------------------------------------------------
this-command eval-last-sexp ;---------------------------------------------------------------
To delete a group, move point into it and type C-c C-d, or simply delete the text for the group and update the evaluation list with C-c C-u. To add a new expression to the evaluation list, insert the expression at a suitable place, insert a new comment line, then type C-c C-u. You need not insert dashes in the comment line—its contents don’t matter.
After selecting *edebug*, you can return to the source code buffer with C-c C-w (see Edebug Views). The *edebug* buffer is killed when you continue execution, and recreated next time it is needed.
If an expression in your program produces a value containing circular list structure, you may get an error when Edebug attempts to print it.
One way to cope with circular structure is to set print-length
or print-level to truncate the printing. Edebug does this for
you; it binds print-length and print-level to the values
of the variables edebug-print-length and
edebug-print-level (so long as they have non-nil
values). See Variables Affecting Output.
If non-nil, Edebug binds print-length to this value while
printing results. The default value is 50.
If non-nil, Edebug binds print-level to this value while
printing results. The default value is 50.
You can also print circular structures and structures that share
elements more informatively by binding print-circle
to a non-nil value.
Here is an example of code that creates a circular structure:
(setq a (list 'x 'y)) (setcar a a)
If print-circle is non-nil, printing functions (e.g.,
prin1) will print a as ‘#1=(#1# y)’. The
‘#1=’ notation labels the structure that follows it with the
label ‘1’, and the ‘#1#’ notation references the previously
labeled structure. This notation is used for any shared elements of
lists or vectors.
If non-nil, Edebug binds print-circle to this value while
printing results. The default value is t.
For further details about how printing can be customized, see see Output Functions.
Edebug can record an execution trace, storing it in a buffer named
*edebug-trace*. This is a log of function calls and returns,
showing the function names and their arguments and values. To enable
trace recording, set edebug-trace to a non-nil value
(see Edebug Options).
Making a trace buffer is not the same thing as using trace execution mode (see Edebug Execution Modes).
When trace recording is enabled, each function entry and exit adds lines to the trace buffer. A function entry record consists of ‘::::{’, followed by the function name and argument values. A function exit record consists of ‘::::}’, followed by the function name and result of the function.
The number of ‘:’s in an entry shows its recursion depth. You can use the braces in the trace buffer to find the matching beginning or end of function calls.
You can customize trace recording for function entry and exit by
redefining the functions edebug-print-trace-before and
edebug-print-trace-after.
This macro requests additional trace information around the execution
of the body forms. The argument string specifies text
to put in the trace buffer, after the ‘{’ or ‘}’. All
the arguments are evaluated, and edebug-tracing returns the
value of the last form in body.
This function inserts text in the trace buffer. It computes the text
with (apply 'format format-string format-args).
It also appends a newline to separate entries.
edebug-tracing and edebug-trace insert lines in the
trace buffer whenever they are called, even if Edebug is not active.
Adding text to the trace buffer also scrolls its window to show the last
lines inserted.
Edebug provides rudimentary coverage testing and display of execution frequency.
Coverage testing works by comparing the result of each expression with the previous result; each form in the program is considered covered if it has returned two different values since you began testing coverage in the current Emacs session. Thus, to do coverage testing on your program, execute it under various conditions and note whether it behaves correctly; Edebug will tell you when you have tried enough different conditions that each form has returned two different values.
Coverage testing makes execution slower, so it is only done if
edebug-test-coverage is non-nil (see Edebug Options).
Frequency counting is performed for all executions of an instrumented
function, even if the execution mode is Go-nonstop, and regardless of
whether coverage testing is enabled.
Use C-x X = (edebug-display-freq-count) to display both
the coverage information and the frequency counts for a definition.
Just = (edebug-temp-display-freq-count) displays the same
information temporarily, only until you type another key.
This command displays the frequency count data for each line of the current definition.
It inserts frequency counts as comment lines after each line of code.
You can undo all insertions with one undo command. The counts
appear under the ‘(’ before an expression or the ‘)’ after
an expression, or on the last character of a variable. To simplify
the display, a count is not shown if it is equal to the count of an
earlier expression on the same line.
The character ‘=’ following the count for an expression says that the expression has returned the same value each time it was evaluated. In other words, it is not yet covered for coverage testing purposes.
To clear the frequency count and coverage data for a definition,
simply reinstrument it with eval-defun.
For example, after evaluating (fac 5) with a source
breakpoint, and setting edebug-test-coverage to t, when
the breakpoint is reached, the frequency data looks like this:
(defun fac (n)
(if (= n 0) (edebug))
;#6 1 = =5
(if (< 0 n)
;#5 =
(* n (fac (1- n)))
;# 5 0
1))
a;# 0
The comment lines show that fac was called 6 times. The
first if statement returned 5 times with the same result each
time; the same is true of the condition on the second if.
The recursive call of fac did not return at all.
Edebug tries to be transparent to the program you are debugging, but it does not succeed completely. Edebug also tries to be transparent when you evaluate expressions with e or with the evaluation list buffer, by temporarily restoring the outside context. This section explains precisely what context Edebug restores, and how Edebug fails to be completely transparent.
Whenever Edebug is entered, it needs to save and restore certain data before even deciding whether to make trace information or stop the program.
max-lisp-eval-depth (see Eval) is increased to reduce Edebug’s
impact on the stack. You could, however, still run out of stack space when
using Edebug. You can also enlarge the value of
edebug-max-depth if Edebug reaches the limit of recursion depth
instrumenting code that contains very large quoted lists.
executing-kbd-macro is bound to nil
unless edebug-continue-kbd-macro is non-nil (see Edebug Options).
When Edebug needs to display something (e.g., in trace mode), it saves the current window configuration from outside Edebug (see Window Configurations). When you exit Edebug, it restores the previous window configuration.
Emacs redisplays only when it pauses. Usually, when you continue execution, the program re-enters Edebug at a breakpoint or after stepping, without pausing or reading input in between. In such cases, Emacs never gets a chance to redisplay the outside configuration. Consequently, what you see is the same window configuration as the last time Edebug was active, with no interruption.
Entry to Edebug for displaying something also saves and restores the following data (though some of them are deliberately not restored if an error or quit signal occurs).
edebug-save-windows is non-nil (see Edebug Options).
If the value of edebug-save-windows is a list, only the listed
windows are saved and restored.
The window configuration is not restored on error or quit, but the
outside selected window is reselected even on error or quit in
case a save-excursion is active.
The window start and horizontal scrolling of the source code buffer are not restored, however, so that the display remains coherent within Edebug.
Saving and restoring the outside window configuration can sometimes
change the positions of point in the buffers on which the Lisp program
you are debugging operates, especially if your program moves point.
If this happens and interferes with your debugging, we recommend to
set edebug-save-windows to nil
(see Edebug Options).
edebug-save-displayed-buffer-points is non-nil.
overlay-arrow-position and
overlay-arrow-string are saved and restored, so you can safely
invoke Edebug from the recursive edit elsewhere in the same buffer.
cursor-in-echo-area is locally bound to nil so that
the cursor shows up in the window.
When Edebug is entered and actually reads commands from the user, it saves (and later restores) these additional data:
last-command, this-command,
last-command-event, last-input-event,
last-event-frame, last-nonmenu-event, and
track-mouse. Commands in Edebug do not affect these variables
outside of Edebug.
Executing commands within Edebug can change the key sequence that
would be returned by this-command-keys, and there is no way to
reset the key sequence from Lisp.
Edebug cannot save and restore the value of
unread-command-events. Entering Edebug while this variable has a
nontrivial value can interfere with execution of the program you are
debugging.
command-history. In rare cases this can alter execution.
standard-output and standard-input are bound to nil
by the recursive-edit, but Edebug temporarily restores them during
evaluations.
defining-kbd-macro is bound to
edebug-continue-kbd-macro.
To make Edebug properly instrument expressions that call macros, some extra care is needed. This subsection explains the details.
When Edebug instruments an expression that calls a Lisp macro, it needs additional information about the macro to do the job properly. This is because there is no a-priori way to tell which subexpressions of the macro call are forms to be evaluated. (Evaluation may occur explicitly in the macro body, or when the resulting expansion is evaluated, or any time later.)
Therefore, you must define an Edebug specification for each macro
that Edebug will encounter, to explain the format of calls to that
macro. To do this, add a debug declaration (see The declare Form) to the macro definition. Here is a simple example that shows the
specification for the for example macro (see Evaluating Macro Arguments Repeatedly).
(defmacro for (var from init to final do &rest body) "Execute a simple \"for\" loop. For example, (for i from 1 to 10 do (print i))." (declare (debug (symbolp "from" form "to" form "do" &rest form))) ...)
The Edebug specification says which parts of a call to the macro are
forms to be evaluated. For simple macros, the specification
often looks very similar to the formal argument list of the macro
definition, but specifications are much more general than macro
arguments. See The declare Form, for more details about
the declare form.
Take care to ensure that the specifications are known to Edebug when
you instrument code. If you are instrumenting a function which uses a
macro defined in another file, you may first need to either evaluate
the require forms in the file containing your function, or
explicitly load the file containing the macro. If the definition of a
macro is wrapped by eval-when-compile, you may need to evaluate
it.
You can also define an edebug specification for a macro separately
from the macro definition with def-edebug-spec. Adding
debug declarations is preferred, and more convenient, for macro
definitions in Lisp, but def-edebug-spec makes it possible to
define Edebug specifications for special forms implemented in C.
Specify which expressions of a call to macro macro are forms to be evaluated. specification should be the Edebug specification. Neither argument is evaluated.
The macro argument can actually be any symbol, not just a macro name.
Here is a table of the possibilities for specification and how each directs processing of arguments.
tAll arguments are instrumented for evaluation.
This is short for (body).
The symbol must have an Edebug specification, which is used instead. This indirection is repeated until another kind of specification is found. This allows you to inherit the specification from another macro.
The elements of the list describe the types of the arguments of a calling form. The possible elements of a specification list are described in the following sections.
If a macro has no Edebug specification, neither through a debug
declaration nor through a def-edebug-spec call, the variable
edebug-eval-macro-args comes into play.
This controls the way Edebug treats macro arguments with no explicit
Edebug specification. If it is nil (the default), none of the
arguments is instrumented for evaluation. Otherwise, all arguments
are instrumented.
A specification list is required for an Edebug specification if
some arguments of a macro call are evaluated while others are not. Some
elements in a specification list match one or more arguments, but others
modify the processing of all following elements. The latter, called
specification keywords, are symbols beginning with ‘&’ (such
as &optional).
A specification list may contain sublists, which match arguments that are themselves lists, or it may contain vectors used for grouping. Sublists and groups thus subdivide the specification list into a hierarchy of levels. Specification keywords apply only to the remainder of the sublist or group they are contained in.
When a specification list involves alternatives or repetition, matching it against an actual macro call may require backtracking. For more details, see Backtracking in Specifications.
Edebug specifications provide the power of regular expression matching, plus some context-free grammar constructs: the matching of sublists with balanced parentheses, recursive processing of forms, and recursion via indirect specifications.
Here’s a table of the possible elements of a specification list, with their meanings (see Specification Examples, for the referenced examples):
sexpA single unevaluated Lisp object, which is not instrumented.
If the macro evaluates an argument at macro-expansion time, you should
use sexp for it rather than form.
formA single evaluated expression, which is instrumented. If your macro
wraps the expression with lambda before it is evaluated, use
def-form instead. See def-form below.
placeA generalized variable. See Generalized Variables.
bodyShort for &rest form. See &rest below. If your macro
wraps its body of code with lambda before it is evaluated, use
def-body instead. See def-body below.
lambda-exprA lambda expression with no quoting.
&optionalAll following elements in the specification list are optional; as soon as one does not match, Edebug stops matching at this level.
To make just a few elements optional, followed by non-optional elements,
use [&optional specs…]. To specify that several
elements must all match or none, use &optional
[specs…]. See the defun example.
&restAll following elements in the specification list are repeated zero or more times. In the last repetition, however, it is not a problem if the expression runs out before matching all of the elements of the specification list.
To repeat only a few elements, use [&rest specs…].
To specify several elements that must all match on every repetition, use
&rest [specs…].
&orEach of the following elements in the specification list is an
alternative. One of the alternatives must match, or the &or
specification fails.
Each list element following &or is a single alternative. To
group two or more list elements as a single alternative, enclose them in
[…].
¬Each of the following elements is matched as alternatives as if by using
&or, but if any of them match, the specification fails. If none
of them match, nothing is matched, but the ¬ specification
succeeds.
&defineIndicates that the specification is for a defining form. Edebug’s definition of a defining form is a form containing one or more code forms which are saved and executed later, after the execution of the defining form.
The defining form itself is not instrumented (that is, Edebug does not
stop before and after the defining form), but forms inside it
typically will be instrumented. The &define keyword should be
the first element in a list specification.
nilThis is successful when there are no more arguments to match at the current argument list level; otherwise it fails. See sublist specifications and the backquote example.
gate ¶No argument is matched but backtracking through the gate is disabled
while matching the remainder of the specifications at this level. This
is primarily used to generate more specific syntax error messages.
See Backtracking in Specifications, for more details. Also see the let example.
&error&error should be followed by a string, an error message, in the
edebug-spec; it aborts the instrumentation, displaying the message in
the minibuffer.
&interposeLets a function control the parsing of the remaining code.
It takes the form &interpose spec fun args...
and means that Edebug will first match spec against the code and
then call fun with the code that matched spec, a parsing
function pf, and finally args.... The parsing
function expects a single argument indicating the specification list
to use to parse the remaining code. It should be called exactly once
and returns the instrumented code that fun is expected to return.
For example (&interpose symbolp pcase--match-pat-args) matches
sexps whose first element is a symbol and then lets
pcase--match-pat-args lookup the specs associated
with that head symbol according to pcase--match-pat-args and
pass them to the pf it received as argument.
other-symbol ¶Any other symbol in a specification list may be a predicate or an indirect specification.
If the symbol has an Edebug specification, this indirect
specification should be either a list specification that is used in
place of the symbol, or a function that is called to process the
arguments. The specification may be defined with
def-edebug-elem-spec:
Define the specification to use in place of the symbol element. specification has to be a list.
Otherwise, the symbol should be a predicate. The predicate is called
with the argument, and if the predicate returns nil, the
specification fails and the argument is not instrumented.
Some suitable predicates include symbolp, integerp,
stringp, vectorp, and atom.
[elements…] ¶A vector of elements groups the elements into a single group specification. Its meaning has nothing to do with vectors.
"string"The argument should be a symbol named string. This specification
is equivalent to the quoted symbol, 'symbol, where the name
of symbol is the string, but the string form is preferred.
(vector elements…)The argument should be a vector whose elements must match the elements in the specification. See the backquote example.
(elements…)Any other list is a sublist specification and the argument must be a list whose elements match the specification elements.
A sublist specification may be a dotted list and the corresponding list
argument may then be a dotted list. Alternatively, the last CDR of a
dotted list specification may be another sublist specification (via a
grouping or an indirect specification, e.g., (spec . [(more
specs…)])) whose elements match the non-dotted list arguments.
This is useful in recursive specifications such as in the backquote
example. Also see the description of a nil specification
above for terminating such recursion.
Note that a sublist specification written as (specs . nil)
is equivalent to (specs), and (specs .
(sublist-elements…)) is equivalent to (specs
sublist-elements…).
Here is a list of additional specifications that may appear only after
&define. See the defun example.
&nameExtracts the name of the current defining form from the code.
It takes the form &name [prestring] spec
[poststring] fun args... and means that Edebug will
match spec against the code and then call fun with the
concatenation of the current name, args..., prestring,
the code that matched spec, and poststring. If fun
is absent, it defaults to a function that concatenates the arguments
(with an @ between the previous name and the new).
nameThe argument, a symbol, is the name of the defining form.
Shorthand for [&name symbolp].
A defining form is not required to have a name field; and it may have multiple name fields.
argThe argument, a symbol, is the name of an argument of the defining form. However, lambda-list keywords (symbols starting with ‘&’) are not allowed.
lambda-list ¶This matches a lambda list—the argument list of a lambda expression.
def-bodyThe argument is the body of code in a definition. This is like
body, described above, but a definition body must be instrumented
with a different Edebug call that looks up information associated with
the definition. Use def-body for the highest level list of forms
within the definition.
def-formThe argument is a single, highest-level form in a definition. This is
like def-body, except it is used to match a single form rather than
a list of forms. As a special case, def-form also means that
tracing information is not output when the form is executed. See the
interactive example.
If a specification fails to match at some point, this does not necessarily mean a syntax error will be signaled; instead, backtracking will take place until all alternatives have been exhausted. Eventually every element of the argument list must be matched by some element in the specification, and every required element in the specification must match some argument.
When a syntax error is detected, it might not be reported until much
later, after higher-level alternatives have been exhausted, and with the
point positioned further from the real error. But if backtracking is
disabled when an error occurs, it can be reported immediately. Note
that backtracking is also reenabled automatically in several situations;
when a new alternative is established by &optional,
&rest, or &or, or at the start of processing a sublist,
group, or indirect specification. The effect of enabling or disabling
backtracking is limited to the remainder of the level currently being
processed and lower levels.
Backtracking is disabled while matching any of the
form specifications (that is, form, body, def-form, and
def-body). These specifications will match any form so any error
must be in the form itself rather than at a higher level.
Backtracking is also disabled after successfully matching a quoted
symbol, string specification, or &define keyword, since this
usually indicates a recognized construct. But if you have a set of
alternative constructs that all begin with the same symbol, you can
usually work around this constraint by factoring the symbol out of the
alternatives, e.g., ["foo" &or [first case] [second case] ...].
Most needs are satisfied by these two ways that backtracking is
automatically disabled, but occasionally it is useful to explicitly
disable backtracking by using the gate specification. This is
useful when you know that no higher alternatives could apply. See the
example of the let specification.
It may be easier to understand Edebug specifications by studying the examples provided here.
Consider a hypothetical macro my-test-generator that runs
tests on supplied lists of data. Although it is Edebug’s default
behavior to not instrument arguments as code, as controlled by
edebug-eval-macro-args (see Instrumenting Macro Calls),
it can be useful to explicitly document that the arguments are data:
(def-edebug-spec my-test-generator (&rest sexp))
A let special form has a sequence of bindings and a body. Each
of the bindings is either a symbol or a sublist with a symbol and
optional expression. In the specification below, notice the gate
inside of the sublist to prevent backtracking once a sublist is found.
(def-edebug-spec let
((&rest
&or symbolp (gate symbolp &optional form))
body))
Edebug uses the following specifications for defun and the
associated argument list and interactive specifications. It is
necessary to handle interactive forms specially since an expression
argument is actually evaluated outside of the function body. (The
specification for defmacro is very similar to that for
defun, but allows for the declare statement.)
(def-edebug-spec defun
(&define name lambda-list
[&optional stringp] ; Match the doc string, if present.
[&optional ("interactive" interactive)]
def-body))
(def-edebug-elem-spec 'lambda-list
'(([&rest arg]
[&optional ["&optional" arg &rest arg]]
&optional ["&rest" arg]
)))
(def-edebug-elem-spec 'interactive
'(&optional &or stringp def-form)) ; Notice: def-form
The specification for backquote below illustrates how to match
dotted lists and use nil to terminate recursion. It also
illustrates how components of a vector may be matched. (The actual
specification defined by Edebug is a little different, and does not
support dotted lists because doing so causes very deep recursion that
could fail.)
(def-edebug-spec \` (backquote-form)) ; Alias just for clarity.
(def-edebug-elem-spec 'backquote-form
'(&or ([&or "," ",@"] &or ("quote" backquote-form) form)
(backquote-form . [&or nil backquote-form])
(vector &rest backquote-form)
sexp))
These options affect the behavior of Edebug:
Functions to call before Edebug is used. Each time it is set to a new
value, Edebug will call those functions once and then
reset edebug-setup-hook to nil. You could use this to
load up Edebug specifications associated with a package you are using,
but only when you also use Edebug.
See Instrumenting for Edebug.
If this is non-nil, normal evaluation of defining forms such as
defun and defmacro instruments them for Edebug. This
applies to eval-defun, eval-region and
eval-buffer.
Use the command M-x edebug-all-defs to toggle the value of this option. See Instrumenting for Edebug.
If this is non-nil, the commands eval-defun,
eval-region and eval-buffer instrument all forms, even
those that don’t define anything. This doesn’t apply to loading or
evaluations in the minibuffer.
Use the command M-x edebug-all-forms to toggle the value of this option. See Instrumenting for Edebug.
When this is non-nil, all macro arguments will be instrumented
in the generated code. For any macro, the debug declaration
overrides this option. So to specify exceptions for macros that have
some arguments evaluated and some not, use the debug declaration
specify an Edebug form specification.
If this is non-nil, Edebug saves and restores the window
configuration. That takes some time, so if your program does not care
what happens to the window configurations, it is better to set this
variable to nil. We also recommend to set this to nil
if the default value causes Edebug to overwrite the positions of point
in buffers that are involved in the program you are debugging, as
result of saving and restoring the window configuration; this could
happen if your program moves point in one or more of those buffers.
Another option to try to customize in this case is
edebug-save-displayed-buffer-points, described below.
If the value of edebug-save-windows is a list, only the listed
windows are saved and restored.
You can use the W command in Edebug to change this variable interactively. See Edebug Display Update.
If this is non-nil, Edebug saves and restores point in all
displayed buffers.
Saving and restoring point in other buffers is necessary if you are debugging code that changes the point of a buffer that is displayed in a non-selected window. If Edebug or the user then selects the window, point in that buffer will move to the window’s value of point.
Saving and restoring point in all buffers is expensive, since it requires selecting each window twice, so enable this only if you need it. See Edebug Display Update.
If this variable is non-nil, it specifies the initial execution
mode for Edebug when it is first activated. Possible values are
step, next, go, Go-nonstop, trace,
Trace-fast, continue, and Continue-fast.
The default value is step. This variable can be set
interactively with C-x C-a C-m (edebug-set-initial-mode).
See Edebug Execution Modes.
If this is non-nil, trace each function entry and exit.
Tracing output is displayed in a buffer named *edebug-trace*, one
function entry or exit per line, indented by the recursion level.
Also see edebug-tracing, in Trace Buffer.
If non-nil, Edebug tests coverage of all expressions debugged.
See Coverage Testing.
If non-nil, continue defining or executing any keyboard macro
that is executing outside of Edebug. Use this with caution since it is not
debugged.
See Edebug Execution Modes.
If non-nil, the default value of print-length for
printing results in Edebug. See Variables Affecting Output.
If non-nil, the default value of print-level for
printing results in Edebug. See Variables Affecting Output.
If non-nil, the default value of print-circle for
printing results in Edebug. See Variables Affecting Output.
If non-nil, Edebug tries to remove any of its own
instrumentation when showing the results of expressions. This is
relevant when debugging macros where the results of expressions are
themselves instrumented expressions. As a very artificial example,
suppose that the example function fac has been instrumented,
and consider a macro of the form:
(defmacro test () "Edebug example."
(if (symbol-function 'fac)
...))
If you instrument the test macro and step through it, then by
default the result of the symbol-function call has numerous
edebug-after and edebug-before forms, which can make it
difficult to see the actual result. If
edebug-unwrap-results is non-nil, Edebug tries to remove
these forms from the result.
Edebug binds debug-on-error to this value, if
debug-on-error was previously nil. See Trapping Errors.
Edebug binds debug-on-quit to this value, if
debug-on-quit was previously nil. See Trapping Errors.
If you change the values of edebug-on-error or
edebug-on-quit while Edebug is active, their values won’t be used
until the next time Edebug is invoked via a new command.
If non-nil, an expression to test for at every stop point. If
the result is non-nil, then break. Errors are ignored.
See Global Break Condition.
Number of seconds to pause when a breakpoint is reached and the execution mode is trace or continue. See Edebug Execution Modes.
Whether or not to pause for edebug-sit-for-seconds on reaching
a breakpoint. Set to nil to prevent the pause, non-nil
to allow it.
By default, this alist contains one entry with the key edebug
and a list of three functions, which are the default implementations
of the functions inserted in instrumented code: edebug-enter,
edebug-before and edebug-after. To change Edebug’s
behavior globally, modify the default entry.
Edebug’s behavior may also be changed on a per-definition basis by
adding an entry to this alist, with a key of your choice and three
functions. Then set the edebug-behavior symbol property of an
instrumented definition to the key of the new entry, and Edebug will
call the new functions in place of its own for that definition.
A function run by Edebug after it wraps the body of a definition
or closure. After Edebug has initialized its own data, this function
is called with one argument, the symbol associated with the
definition, which may be the actual symbol defined or one generated by
Edebug. This function may be used to set the edebug-behavior
symbol property of each definition instrumented by Edebug.
To inspect or modify Edebug’s instrumentation before it is used, set this variable to a function which takes one argument, an instrumented top-level form, and returns either the same or a replacement form, which Edebug will then use as the final result of instrumentation.
The Lisp reader reports invalid syntax, but cannot say where the real problem is. For example, the error ‘End of file during parsing’ in evaluating an expression indicates an excess of open parentheses (or square brackets). The reader detects this imbalance at the end of the file, but it cannot figure out where the close parenthesis should have been. Likewise, ‘Invalid read syntax: ")"’ indicates an excess close parenthesis or missing open parenthesis, but does not say where the missing parenthesis belongs. How, then, to find what to change?
If the problem is not simply an imbalance of parentheses, a useful
technique is to try C-M-e (end-of-defun, see Moving by
Defuns in The GNU Emacs Manual) at the beginning of each defun,
and see if it goes to the place where that defun appears to end. If
it does not, there is a problem in that defun.
However, unmatched parentheses are the most common syntax errors in Lisp, and we can give further advice for those cases. (In addition, just moving point through the code with Show Paren mode enabled might find the mismatch.)
The first step is to find the defun that is unbalanced. If there is
an excess open parenthesis, the way to do this is to go to the end of
the file and type C-u C-M-u (backward-up-list,
see Moving by Parens in The GNU Emacs Manual). This will
move you to the beginning of the first defun that is unbalanced.
The next step is to determine precisely what is wrong. There is no
way to be sure of this except by studying the program, but often the
existing indentation is a clue to where the parentheses should have
been. The easiest way to use this clue is to reindent with C-M-q
(indent-pp-sexp, see Multi-line Indent in The GNU
Emacs Manual) and see what moves. But don’t do this yet!
Keep reading, first.
Before you do this, make sure the defun has enough close parentheses.
Otherwise, C-M-q will get an error, or will reindent all the rest
of the file until the end. So move to the end of the defun and insert a
close parenthesis there. Don’t use C-M-e (end-of-defun) to
move there, since that too will fail to work until the defun is balanced.
Now you can go to the beginning of the defun and type C-M-q.
Usually all the lines from a certain point to the end of the function
will shift to the right. There is probably a missing close parenthesis,
or a superfluous open parenthesis, near that point. (However, don’t
assume this is true; study the code to make sure.) Once you have found
the discrepancy, undo the C-M-q with C-_ (undo),
since the old indentation is probably appropriate to the intended
parentheses.
After you think you have fixed the problem, use C-M-q again. If the old indentation actually fit the intended nesting of parentheses, and you have put back those parentheses, C-M-q should not change anything.
To deal with an excess close parenthesis, first go to the beginning
of the file, then type C-u -1 C-M-u (backward-up-list
with an argument of −1) to find the end of the first unbalanced
defun.
Then find the actual matching close parenthesis by typing C-M-f
(forward-sexp, see Expressions in The GNU Emacs Manual)
at the beginning of that defun. This will leave you somewhere short of
the place where the defun ought to end. It is possible that you will
find a spurious close parenthesis in that vicinity.
If you don’t see a problem at that point, the next thing to do is to
type C-M-q (indent-pp-sexp) at the beginning of the defun.
A range of lines will probably shift left; if so, the missing open
parenthesis or spurious close parenthesis is probably near the first of
those lines. (However, don’t assume this is true; study the code to
make sure.) Once you have found the discrepancy, undo the C-M-q
with C-_ (undo), since the old indentation is probably
appropriate to the intended parentheses.
After you think you have fixed the problem, use C-M-q again. If the old indentation actually fits the intended nesting of parentheses, and you have put back those parentheses, C-M-q should not change anything.
You can do coverage testing for a file of Lisp code by loading the
testcover library and using the command M-x
testcover-start RET file RET to instrument the
code. Then test your code by calling it one or more times. Then use
the command M-x testcover-mark-all to display colored highlights
on the code to show where coverage is insufficient. The command
M-x testcover-next-mark will move point forward to the next
highlighted spot.
Normally, a red highlight indicates the form was never completely
evaluated; a brown highlight means it always evaluated to the same
value (meaning there has been little testing of what is done with the
result). However, the red highlight is skipped for forms that can’t
possibly complete their evaluation, such as error. The brown
highlight is skipped for forms that are expected to always evaluate to
the same value, such as (setq x 14).
For difficult cases, you can add do-nothing macros to your code to give advice to the test coverage tool.
Evaluate form and return its value, but inform coverage testing that form’s value should always be the same.
Evaluate form, informing coverage testing that form should never return. If it ever does return, you get a run-time error.
Edebug also has a coverage testing feature (see Coverage Testing). These features partly duplicate each other, and it would be cleaner to combine them.
If your program is working correctly, but not fast enough, and you want to make it run more quickly or efficiently, the first thing to do is profile your code so that you know where it spends most of the execution time. If you find that one particular function is responsible for a significant portion of the execution time, you can start looking for ways to optimize that piece.
Emacs has built-in support for this. To begin profiling, type
M-x profiler-start. You can choose to sample CPU usage
periodically (cpu), when memory is allocated (memory),
or both. Then run the code you’d like to speed up. After that, type
M-x profiler-report to display a summary buffer for CPU usage
sampled by each type (cpu and memory) that you chose to profile. The
names of the report buffers include the times at which the reports
were generated, so you can generate another report later on without
erasing previous results. When you have finished profiling, type
M-x profiler-stop (there is a small overhead associated with
profiling, so we don’t recommend leaving it active except when you are
actually running the code you want to examine).
The profiler report buffer shows, on each line, a function that was called, preceded by how much CPU resources it used in absolute and percentage terms since profiling started. If a given line has a ‘+’ symbol to the left of the function name, you can expand that line by typing RET, in order to see the function(s) called by the higher-level function. Use a prefix argument (C-u RET) to see the whole call tree below a function. Pressing RET again will collapse back to the original state.
Press j (profiler-report-find-entry) or mouse-2 to
jump to the definition of a function at point. Press d
(profiler-report-describe-entry) to view a function’s
documentation. You can save a profile to a file using C-x C-w
(profiler-report-write-profile) and read a saved profile with
M-x profiler-find-profile or M-x profiler-find-profile-other-window. You can compare two profiles
using = (profiler-report-compare-profile).
The elp library offers an alternative approach, which is useful
when you know in advance which Lisp function(s) you want to profile.
Using that library, you begin by setting elp-function-list to
the list of function symbols—those are the functions you want to
profile. Then type M-x elp-instrument-list RET nil RET to arrange for profiling those functions. After running
the code you want to profile, invoke M-x elp-results to
display the current results. See the file elp.el for more
detailed instructions. This approach is limited to profiling
functions written in Lisp, it cannot profile Emacs primitives.
You can measure the time it takes to evaluate individual Emacs Lisp
forms using the benchmark library. See the function
benchmark-call as well as the macros benchmark-run,
benchmark-run-compiled, and benchmark-progn in
benchmark.el. You can also use the benchmark command
for timing forms interactively.
To profile Emacs at the level of its C code, you can build it using the
--enable-profiling option of configure. When Emacs
exits, it generates a file gmon.out that you can examine using
the gprof utility. This feature is mainly useful for
debugging Emacs. It actually stops the Lisp-level M-x
profiler-… commands described above from working.