1 This is ../info/lispref.info, produced by makeinfo version 4.8 from
4 INFO-DIR-SECTION XEmacs Editor
6 * Lispref: (lispref). XEmacs Lisp Reference Manual.
11 GNU Emacs Lisp Reference Manual Second Edition (v2.01), May 1993 GNU
12 Emacs Lisp Reference Manual Further Revised (v2.02), August 1993 Lucid
13 Emacs Lisp Reference Manual (for 19.10) First Edition, March 1994
14 XEmacs Lisp Programmer's Manual (for 19.12) Second Edition, April 1995
15 GNU Emacs Lisp Reference Manual v2.4, June 1995 XEmacs Lisp
16 Programmer's Manual (for 19.13) Third Edition, July 1995 XEmacs Lisp
17 Reference Manual (for 19.14 and 20.0) v3.1, March 1996 XEmacs Lisp
18 Reference Manual (for 19.15 and 20.1, 20.2, 20.3) v3.2, April, May,
19 November 1997 XEmacs Lisp Reference Manual (for 21.0) v3.3, April 1998
21 Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995 Free Software
22 Foundation, Inc. Copyright (C) 1994, 1995 Sun Microsystems, Inc.
23 Copyright (C) 1995, 1996 Ben Wing.
25 Permission is granted to make and distribute verbatim copies of this
26 manual provided the copyright notice and this permission notice are
27 preserved on all copies.
29 Permission is granted to copy and distribute modified versions of
30 this manual under the conditions for verbatim copying, provided that the
31 entire resulting derived work is distributed under the terms of a
32 permission notice identical to this one.
34 Permission is granted to copy and distribute translations of this
35 manual into another language, under the above conditions for modified
36 versions, except that this permission notice may be stated in a
37 translation approved by the Foundation.
39 Permission is granted to copy and distribute modified versions of
40 this manual under the conditions for verbatim copying, provided also
41 that the section entitled "GNU General Public License" is included
42 exactly as in the original, and provided that the entire resulting
43 derived work is distributed under the terms of a permission notice
44 identical to this one.
46 Permission is granted to copy and distribute translations of this
47 manual into another language, under the above conditions for modified
48 versions, except that the section entitled "GNU General Public License"
49 may be included in a translation approved by the Free Software
50 Foundation instead of in the original English.
53 File: lispref.info, Node: Autoload, Next: Repeated Loading, Prev: How Programs Do Loading, Up: Loading
58 The "autoload" facility allows you to make a function or macro known in
59 Lisp, but put off loading the file that defines it. The first call to
60 the function automatically reads the proper file to install the real
61 definition and other associated code, then runs the real definition as
62 if it had been loaded all along.
64 There are two ways to set up an autoloaded function: by calling
65 `autoload', and by writing a special "magic" comment in the source
66 before the real definition. `autoload' is the low-level primitive for
67 autoloading; any Lisp program can call `autoload' at any time. Magic
68 comments do nothing on their own; they serve as a guide for the command
69 `update-file-autoloads', which constructs calls to `autoload' and
70 arranges to execute them when Emacs is built. Magic comments are the
71 most convenient way to make a function autoload, but only for packages
72 installed along with Emacs.
74 -- Function: autoload function filename &optional docstring
76 This function defines the function (or macro) named FUNCTION so as
77 to load automatically from FILENAME. The string FILENAME
78 specifies the file to load to get the real definition of FUNCTION.
80 The argument DOCSTRING is the documentation string for the
81 function. Normally, this is identical to the documentation string
82 in the function definition itself. Specifying the documentation
83 string in the call to `autoload' makes it possible to look at the
84 documentation without loading the function's real definition.
86 If INTERACTIVE is non-`nil', then the function can be called
87 interactively. This lets completion in `M-x' work without loading
88 the function's real definition. The complete interactive
89 specification need not be given here; it's not needed unless the
90 user actually calls FUNCTION, and when that happens, it's time to
91 load the real definition.
93 You can autoload macros and keymaps as well as ordinary functions.
94 Specify TYPE as `macro' if FUNCTION is really a macro. Specify
95 TYPE as `keymap' if FUNCTION is really a keymap. Various parts of
96 Emacs need to know this information without loading the real
99 An autoloaded keymap loads automatically during key lookup when a
100 prefix key's binding is the symbol FUNCTION. Autoloading does not
101 occur for other kinds of access to the keymap. In particular, it
102 does not happen when a Lisp program gets the keymap from the value
103 of a variable and calls `define-key'; not even if the variable
104 name is the same symbol FUNCTION.
106 If FUNCTION already has a non-void function definition that is not
107 an autoload object, `autoload' does nothing and returns `nil'. If
108 the function cell of FUNCTION is void, or is already an autoload
109 object, then it is defined as an autoload object like this:
111 (autoload FILENAME DOCSTRING INTERACTIVE TYPE)
115 (symbol-function 'run-prolog)
116 => (autoload "prolog" 169681 t nil)
118 In this case, `"prolog"' is the name of the file to load, 169681
119 refers to the documentation string in the `DOC' file (*note
120 Documentation Basics::), `t' means the function is interactive,
121 and `nil' that it is not a macro or a keymap.
123 The autoloaded file usually contains other definitions and may
124 require or provide one or more features. If the file is not completely
125 loaded (due to an error in the evaluation of its contents), any function
126 definitions or `provide' calls that occurred during the load are
127 undone. This is to ensure that the next attempt to call any function
128 autoloading from this file will try again to load the file. If not for
129 this, then some of the functions in the file might appear defined, but
130 they might fail to work properly for the lack of certain subroutines
131 defined later in the file and not loaded successfully.
133 XEmacs as distributed comes with many autoloaded functions. The
134 calls to `autoload' are in the file `loaddefs.el'. There is a
135 convenient way of updating them automatically.
137 If the autoloaded file fails to define the desired Lisp function or
138 macro, then an error is signaled with data `"Autoloading failed to
139 define function FUNCTION-NAME"'.
141 A magic autoload comment looks like `;;;###autoload', on a line by
142 itself, just before the real definition of the function in its
143 autoloadable source file. The command `M-x update-file-autoloads'
144 writes a corresponding `autoload' call into `loaddefs.el'. Building
145 Emacs loads `loaddefs.el' and thus calls `autoload'. `M-x
146 update-directory-autoloads' is even more powerful; it updates autoloads
147 for all files in the current directory.
149 The same magic comment can copy any kind of form into `loaddefs.el'.
150 If the form following the magic comment is not a function definition,
151 it is copied verbatim. You can also use a magic comment to execute a
152 form at build time _without_ executing it when the file itself is
153 loaded. To do this, write the form "on the same line" as the magic
154 comment. Since it is in a comment, it does nothing when you load the
155 source file; but `update-file-autoloads' copies it to `loaddefs.el',
156 where it is executed while building Emacs.
158 The following example shows how `doctor' is prepared for autoloading
159 with a magic comment:
163 "Switch to *doctor* buffer and start giving psychotherapy."
165 (switch-to-buffer "*doctor*")
168 Here's what that produces in `loaddefs.el':
170 (autoload 'doctor "doctor"
172 Switch to *doctor* buffer and start giving psychotherapy."
175 The backslash and newline immediately following the double-quote are a
176 convention used only in the preloaded Lisp files such as `loaddefs.el';
177 they tell `make-docfile' to put the documentation string in the `DOC'
178 file. *Note Building XEmacs::.
181 File: lispref.info, Node: Repeated Loading, Next: Named Features, Prev: Autoload, Up: Loading
183 20.3 Repeated Loading
184 =====================
186 You may load one file more than once in an Emacs session. For example,
187 after you have rewritten and reinstalled a function definition by
188 editing it in a buffer, you may wish to return to the original version;
189 you can do this by reloading the file it came from.
191 When you load or reload files, bear in mind that the `load' and
192 `load-library' functions automatically load a byte-compiled file rather
193 than a non-compiled file of similar name. If you rewrite a file that
194 you intend to save and reinstall, remember to byte-compile it if
195 necessary; otherwise you may find yourself inadvertently reloading the
196 older, byte-compiled file instead of your newer, non-compiled file!
198 When writing the forms in a Lisp library file, keep in mind that the
199 file might be loaded more than once. For example, the choice of
200 `defvar' vs. `defconst' for defining a variable depends on whether it
201 is desirable to reinitialize the variable if the library is reloaded:
202 `defconst' does so, and `defvar' does not. (*Note Defining
205 The simplest way to add an element to an alist is like this:
207 (setq minor-mode-alist
208 (cons '(leif-mode " Leif") minor-mode-alist))
210 But this would add multiple elements if the library is reloaded. To
211 avoid the problem, write this:
213 (or (assq 'leif-mode minor-mode-alist)
214 (setq minor-mode-alist
215 (cons '(leif-mode " Leif") minor-mode-alist)))
217 To add an element to a list just once, use `add-to-list' (*note
218 Setting Variables::).
220 Occasionally you will want to test explicitly whether a library has
221 already been loaded. Here's one way to test, in a library, whether it
222 has been loaded before:
224 (defvar foo-was-loaded)
226 (if (not (boundp 'foo-was-loaded))
227 EXECUTE-FIRST-TIME-ONLY)
229 (setq foo-was-loaded t)
231 If the library uses `provide' to provide a named feature, you can use
232 `featurep' to test whether the library has been loaded. *Note Named
236 File: lispref.info, Node: Named Features, Next: Unloading, Prev: Repeated Loading, Up: Loading
241 `provide' and `require' are an alternative to `autoload' for loading
242 files automatically. They work in terms of named "features".
243 Autoloading is triggered by calling a specific function, but a feature
244 is loaded the first time another program asks for it by name.
246 A feature name is a symbol that stands for a collection of functions,
247 variables, etc. The file that defines them should "provide" the
248 feature. Another program that uses them may ensure they are defined by
249 "requiring" the feature. This loads the file of definitions if it
250 hasn't been loaded already.
252 To require the presence of a feature, call `require' with the
253 feature name as argument. `require' looks in the global variable
254 `features' to see whether the desired feature has been provided
255 already. If not, it loads the feature from the appropriate file. This
256 file should call `provide' at the top level to add the feature to
257 `features'; if it fails to do so, `require' signals an error.
259 Features are normally named after the files that provide them, so
260 that `require' need not be given the file name.
262 For example, in `emacs/lisp/prolog.el', the definition for
263 `run-prolog' includes the following code:
266 "Run an inferior Prolog process, input and output via buffer *prolog*."
269 (switch-to-buffer (make-comint "prolog" prolog-program-name))
270 (inferior-prolog-mode))
272 The expression `(require 'comint)' loads the file `comint.el' if it has
273 not yet been loaded. This ensures that `make-comint' is defined.
275 The `comint.el' file contains the following top-level expression:
279 This adds `comint' to the global `features' list, so that `(require
280 'comint)' will henceforth know that nothing needs to be done.
282 When `require' is used at top level in a file, it takes effect when
283 you byte-compile that file (*note Byte Compilation::) as well as when
284 you load it. This is in case the required package contains macros that
285 the byte compiler must know about.
287 Although top-level calls to `require' are evaluated during byte
288 compilation, `provide' calls are not. Therefore, you can ensure that a
289 file of definitions is loaded before it is byte-compiled by including a
290 `provide' followed by a `require' for the same feature, as in the
293 (provide 'my-feature) ; Ignored by byte compiler,
294 ; evaluated by `load'.
295 (require 'my-feature) ; Evaluated by byte compiler.
297 The compiler ignores the `provide', then processes the `require' by
298 loading the file in question. Loading the file does execute the
299 `provide' call, so the subsequent `require' call does nothing while
302 -- Function: provide feature
303 This function announces that FEATURE is now loaded, or being
304 loaded, into the current XEmacs session. This means that the
305 facilities associated with FEATURE are or will be available for
308 The direct effect of calling `provide' is to add FEATURE to the
309 front of the list `features' if it is not already in the list.
310 The argument FEATURE must be a symbol. `provide' returns FEATURE.
320 When a file is loaded to satisfy an autoload, and it stops due to
321 an error in the evaluating its contents, any function definitions
322 or `provide' calls that occurred during the load are undone.
325 -- Function: require feature &optional filename
326 This function checks whether FEATURE is present in the current
327 XEmacs session (using `(featurep FEATURE)'; see below). If it is
328 not, then `require' loads FILENAME with `load'. If FILENAME is
329 not supplied, then the name of the symbol FEATURE is used as the
332 If loading the file fails to provide FEATURE, `require' signals an
333 error, `Required feature FEATURE was not provided'.
335 -- Function: featurep fexp
336 This function returns `t' if feature FEXP is present in this
337 Emacs. Use this to conditionalize execution of lisp code based on
338 the presence or absence of emacs or environment extensions.
340 FEXP can be a symbol, a number, or a list.
342 If FEXP is a symbol, it is looked up in the `features' variable,
343 and `t' is returned if it is found, `nil' otherwise.
345 If FEXP is a number, the function returns `t' if this Emacs has an
346 equal or greater number than FEXP, `nil' otherwise. Note that
347 minor Emacs version is expected to be 2 decimal places wide, so
348 `(featurep 20.4)' will return `nil' on XEmacs 20.4--you must write
349 `(featurep 20.04)', unless you wish to match for XEmacs 20.40.
351 If FEXP is a list whose car is the symbol `and', the function
352 returns `t' if all the features in its cdr are present, `nil'
355 If FEXP is a list whose car is the symbol `or', the function
356 returns `t' if any the features in its cdr are present, `nil'
359 If FEXP is a list whose car is the symbol `not', the function
360 returns `t' if the feature is not present, `nil' otherwise.
367 (featurep '(and xemacs gnus))
368 => ; t on XEmacs with Gnus loaded.
370 (featurep '(or tty-frames (and emacs 19.30)))
371 => ; t if this Emacs supports TTY frames.
373 (featurep '(or (and xemacs 19.15) (and emacs 19.34)))
374 => ; t on XEmacs 19.15 and later, or on
375 ; FSF Emacs 19.34 and later.
377 *Please note:* The advanced arguments of this function (anything
378 other than a symbol) are not yet supported by FSF Emacs. If you
379 feel they are useful for supporting multiple Emacs variants, lobby
380 Richard Stallman at `<bug-gnu-emacs@prep.ai.mit.edu>'.
382 -- Variable: features
383 The value of this variable is a list of symbols that are the
384 features loaded in the current XEmacs session. Each symbol was
385 put in this list with a call to `provide'. The order of the
386 elements in the `features' list is not significant.
389 File: lispref.info, Node: Unloading, Next: Hooks for Loading, Prev: Named Features, Up: Loading
394 You can discard the functions and variables loaded by a library to
395 reclaim memory for other Lisp objects. To do this, use the function
398 -- Command: unload-feature feature &optional force
399 This command unloads the library that provided feature FEATURE.
400 It undefines all functions, macros, and variables defined in that
401 library with `defconst', `defvar', `defun', `defmacro',
402 `defsubst', `define-function' and `defalias'. It then restores
403 any autoloads formerly associated with those symbols. (Loading
404 saves these in the `autoload' property of the symbol.)
406 Ordinarily, `unload-feature' refuses to unload a library on which
407 other loaded libraries depend. (A library A depends on library B
408 if A contains a `require' for B.) If the optional argument FORCE
409 is non-`nil', dependencies are ignored and you can unload any
412 The `unload-feature' function is written in Lisp; its actions are
413 based on the variable `load-history'.
415 -- Variable: load-history
416 This variable's value is an alist connecting library names with the
417 names of functions and variables they define, the features they
418 provide, and the features they require.
420 Each element is a list and describes one library. The CAR of the
421 list is the name of the library, as a string. The rest of the
422 list is composed of these kinds of objects:
424 * Symbols that were defined by this library.
426 * Lists of the form `(require . FEATURE)' indicating features
429 * Lists of the form `(provide . FEATURE)' indicating features
432 The value of `load-history' may have one element whose CAR is
433 `nil'. This element describes definitions made with `eval-buffer'
434 on a buffer that is not visiting a file.
436 The command `eval-region' updates `load-history', but does so by
437 adding the symbols defined to the element for the file being visited,
438 rather than replacing that element.
441 File: lispref.info, Node: Hooks for Loading, Prev: Unloading, Up: Loading
443 20.6 Hooks for Loading
444 ======================
446 -- Variable: after-load-alist
447 An alist of expressions to evaluate if and when particular
448 libraries are loaded. Each element looks like this:
452 When `load' is run and the file-name argument is FILENAME, the
453 FORMS in the corresponding element are executed at the end of
456 FILENAME must match exactly! Normally FILENAME is the name of a
457 library, with no directory specified, since that is how `load' is
458 normally called. An error in FORMS does not undo the load, but
459 does prevent execution of the rest of the FORMS.
463 File: lispref.info, Node: Byte Compilation, Next: Debugging, Prev: Loading, Up: Top
468 XEmacs Lisp has a "compiler" that translates functions written in Lisp
469 into a special representation called "byte-code" that can be executed
470 more efficiently. The compiler replaces Lisp function definitions with
471 byte-code. When a byte-coded function is called, its definition is
472 evaluated by the "byte-code interpreter".
474 Because the byte-compiled code is evaluated by the byte-code
475 interpreter, instead of being executed directly by the machine's
476 hardware (as true compiled code is), byte-code is completely
477 transportable from machine to machine without recompilation. It is not,
478 however, as fast as true compiled code.
480 In general, any version of Emacs can run byte-compiled code produced
481 by recent earlier versions of Emacs, but the reverse is not true. In
482 particular, if you compile a program with XEmacs 20, the compiled code
483 may not run in earlier versions.
485 The first time a compiled-function object is executed, the byte-code
486 instructions are validated and the byte-code is further optimized. An
487 `invalid-byte-code' error is signaled if the byte-code is invalid, for
488 example if it contains invalid opcodes. This usually means a bug in
491 *Note Compilation Errors::, for how to investigate errors occurring
496 * Speed of Byte-Code:: An example of speedup from byte compilation.
497 * Compilation Functions:: Byte compilation functions.
498 * Compilation Options:: Controlling the byte compiler's behavior.
499 * Docs and Compilation:: Dynamic loading of documentation strings.
500 * Dynamic Loading:: Dynamic loading of individual functions.
501 * Eval During Compile:: Code to be evaluated when you compile.
502 * Compiled-Function Objects:: The data type used for byte-compiled functions.
503 * Disassembly:: Disassembling byte-code; how to read byte-code.
504 * Different Behavior:: When compiled code gives different results.
507 File: lispref.info, Node: Speed of Byte-Code, Next: Compilation Functions, Up: Byte Compilation
509 21.1 Performance of Byte-Compiled Code
510 ======================================
512 A byte-compiled function is not as efficient as a primitive function
513 written in C, but runs much faster than the version written in Lisp.
516 (defun silly-loop (n)
517 "Return time before and after N iterations of a loop."
518 (let ((t1 (current-time-string)))
519 (while (> (setq n (1- n))
521 (list t1 (current-time-string))))
525 => ("Mon Sep 14 15:51:49 1998"
526 "Mon Sep 14 15:52:07 1998") ; 18 seconds
528 (byte-compile 'silly-loop)
529 => #<compiled-function
532 [current-time-string t1 n 0]
534 "Return time before and after N iterations of a loop.">
537 => ("Mon Sep 14 15:53:43 1998"
538 "Mon Sep 14 15:53:49 1998") ; 6 seconds
540 In this example, the interpreted code required 18 seconds to run,
541 whereas the byte-compiled code required 6 seconds. These results are
542 representative, but actual results will vary greatly.
545 File: lispref.info, Node: Compilation Functions, Next: Compilation Options, Prev: Speed of Byte-Code, Up: Byte Compilation
547 21.2 The Compilation Functions
548 ==============================
550 You can byte-compile an individual function or macro definition with
551 the `byte-compile' function. You can compile a whole file with
552 `byte-compile-file', or several files with `byte-recompile-directory'
553 or `batch-byte-compile'.
555 When you run the byte compiler, you may get warnings in a buffer
556 called `*Compile-Log*'. These report things in your program that
557 suggest a problem but are not necessarily erroneous.
559 Be careful when byte-compiling code that uses macros. Macro calls
560 are expanded when they are compiled, so the macros must already be
561 defined for proper compilation. For more details, see *Note Compiling
564 Normally, compiling a file does not evaluate the file's contents or
565 load the file. But it does execute any `require' calls at top level in
566 the file. One way to ensure that necessary macro definitions are
567 available during compilation is to `require' the file that defines them
568 (*note Named Features::). To avoid loading the macro definition files
569 when someone _runs_ the compiled program, write `eval-when-compile'
570 around the `require' calls (*note Eval During Compile::).
572 -- Function: byte-compile symbol
573 This function byte-compiles the function definition of SYMBOL,
574 replacing the previous definition with the compiled one. The
575 function definition of SYMBOL must be the actual code for the
576 function; i.e., the compiler does not follow indirection to
577 another symbol. `byte-compile' returns the new, compiled
578 definition of SYMBOL.
580 If SYMBOL's definition is a compiled-function object,
581 `byte-compile' does nothing and returns `nil'. Lisp records only
582 one function definition for any symbol, and if that is already
583 compiled, non-compiled code is not available anywhere. So there
584 is no way to "compile the same definition again."
586 (defun factorial (integer)
587 "Compute factorial of INTEGER."
589 (* integer (factorial (1- integer)))))
592 (byte-compile 'factorial)
593 => #<compiled-function
596 [integer 1 factorial]
598 "Compute factorial of INTEGER.">
600 The result is a compiled-function object. The string it contains
601 is the actual byte-code; each character in it is an instruction or
602 an operand of an instruction. The vector contains all the
603 constants, variable names and function names used by the function,
604 except for certain primitives that are coded as special
607 -- Command: compile-defun &optional arg
608 This command reads the defun containing point, compiles it, and
609 evaluates the result. If you use this on a defun that is actually
610 a function definition, the effect is to install a compiled version
613 If ARG is non-`nil', the result is inserted in the current buffer
614 after the form; otherwise, it is printed in the minibuffer.
616 -- Command: byte-compile-file filename &optional load
617 This function compiles a file of Lisp code named FILENAME into a
618 file of byte-code. The output file's name is made by appending
619 `c' to the end of FILENAME.
621 If `load' is non-`nil', the file is loaded after having been
624 Compilation works by reading the input file one form at a time.
625 If it is a definition of a function or macro, the compiled
626 function or macro definition is written out. Other forms are
627 batched together, then each batch is compiled, and written so that
628 its compiled code will be executed when the file is read. All
629 comments are discarded when the input file is read.
631 This command returns `t'. When called interactively, it prompts
635 -rw-r--r-- 1 lewis 791 Oct 5 20:31 push.el
637 (byte-compile-file "~/emacs/push.el")
641 -rw-r--r-- 1 lewis 791 Oct 5 20:31 push.el
642 -rw-r--r-- 1 lewis 638 Oct 8 20:25 push.elc
644 -- Command: byte-recompile-directory directory &optional flag
646 This function recompiles every `.el' file in DIRECTORY that needs
647 recompilation. A file needs recompilation if a `.elc' file exists
648 but is older than the `.el' file.
650 Files in subdirectories of DIRECTORY are also processed unless
651 optional argument NORECURSION is non-`nil'.
653 When a `.el' file has no corresponding `.elc' file, then FLAG says
654 what to do. If it is `nil', these files are ignored. If it is
655 non-`nil', the user is asked whether to compile each such file.
657 If the fourth optional argument FORCE is non-`nil', recompile
658 every `.el' file that already has a `.elc' file.
660 The return value of this command is unpredictable.
662 -- Function: batch-byte-compile
663 This function runs `byte-compile-file' on files specified on the
664 command line. This function must be used only in a batch
665 execution of Emacs, as it kills Emacs on completion. An error in
666 one file does not prevent processing of subsequent files. (The
667 file that gets the error will not, of course, produce any compiled
670 % xemacs -batch -f batch-byte-compile *.el
672 -- Function: batch-byte-recompile-directory
673 This function is similar to `batch-byte-compile' but runs the
674 command `byte-recompile-directory' on the files remaining on the
677 -- Variable: byte-recompile-directory-ignore-errors-p
678 When non-`nil', `byte-recompile-directory' will continue compiling
679 even when an error occurs in a file. Default: `nil', but bound to
680 `t' by `batch-byte-recompile-directory'.
682 -- Variable: byte-recompile-directory-recursively
683 When non-`nil', `byte-recompile-directory' will recurse on
684 subdirectories. Default: `t'.
686 -- Function: byte-code instructions constants stack-depth
687 This function actually interprets byte-code. Don't call this
688 function yourself. Only the byte compiler knows how to generate
689 valid calls to this function.
691 In newer Emacs versions (19 and up), byte code is usually executed
692 as part of a compiled-function object, and only rarely due to an
693 explicit call to `byte-code'. A byte-compiled function was once
694 actually defined with a body that calls `byte-code', but in recent
695 versions of Emacs `byte-code' is only used to run isolated
696 fragments of lisp code without an associated argument list.
699 File: lispref.info, Node: Compilation Options, Next: Docs and Compilation, Prev: Compilation Functions, Up: Byte Compilation
701 21.3 Options for the Byte Compiler
702 ==================================
704 Warning: this node is a quick draft based on docstrings. There may be
705 inaccuracies, as the docstrings occasionally disagree with each other.
706 This has not been checked yet.
708 The byte compiler and optimizer are controlled by the following
709 variables. The `byte-compiler-options' macro described below provides
710 a convenient way to set most of them on a file-by-file basis.
712 -- Variable: emacs-lisp-file-regexp
713 Regexp which matches Emacs Lisp source files. You may want to
714 redefine `byte-compile-dest-file' if you change this. Default:
717 -- Function: byte-compile-dest-file filename
718 Convert an Emacs Lisp source file name to a compiled file name.
719 This function may be redefined by the user, if necessary, for
720 compatibility with `emacs-lisp-file-regexp'.
722 -- Variable: byte-compile-verbose
723 When non-`nil', print messages describing progress of
724 byte-compiler. Default: `t' if interactive on a not-too-slow
725 terminal (see `search-slow-speed'), otherwise `nil'.
727 -- Variable: byte-optimize
728 Level of optimization in the byte compiler.
734 Do all optimizations.
737 Do optimizations manipulating the source code only.
740 Do optimizations manipulating the byte code (actually, LAP
744 -- Variable: byte-compile-delete-errors
745 When non-`nil', the optimizer may delete forms that may signal an
746 error if that is the only change in the function's behavior. This
747 includes variable references and calls to functions such as `car'.
750 -- Variable: byte-optimize-log nil
751 When non-`nil', the byte-compiler logs optimizations into
758 Log all optimizations.
761 Log optimizations manipulating the source code only.
764 Log optimizations manipulating the byte code (actually, LAP
768 -- Variable: byte-compile-error-on-warn
769 When non-`nil', the byte-compiler reports warnings with `error'.
772 -- Variable: byte-compile-default-warnings
773 The warnings used when `byte-compile-warnings' is `t'. Called
774 `byte-compile-warning-types' in GNU Emacs. Default: `(redefine
775 callargs subr-callargs free-vars unresolved unused-vars obsolete)'.
777 -- Variable: byte-compile-warnings
778 List of warnings that the compiler should issue (`t' for the
779 default set). Elements of the list may be:
782 References to variables not in the current lexical scope.
785 References to non-global variables bound but not referenced.
788 Calls to unknown functions.
791 Lambda calls with args that don't match the definition.
794 Calls to subrs with args that don't match the definition.
797 Function cell redefined from a macro to a lambda or vice
798 versa, or redefined to take a different number of arguments.
801 Use of an obsolete function or variable.
804 Warn of use of compatible symbols.
806 The default set is specified by `byte-compile-default-warnings' and
807 normally encompasses all possible warnings.
809 See also the macro `byte-compiler-options'. Default: `t'.
811 The compiler can generate a call graph, which gives information about
812 which functions call which functions.
814 -- Variable: byte-compile-generate-call-tree
815 When non-`nil', the compiler generates a call graph. This records
816 functions that were called and from where. If the value is `t',
817 compilation displays the call graph when it finishes. If the
818 value is neither `t' nor `nil', compilation asks you whether to
821 The call tree only lists functions called, not macros used. Those
822 functions which the byte-code interpreter knows about directly
823 (`eq', `cons', etc.) are not reported.
825 The call tree also lists those functions which are not known to be
826 called (that is, to which no calls have been compiled). Functions
827 which can be invoked interactively are excluded from this list.
830 -- Variable: byte-compile-call-tree nil
831 Alist of functions and their call tree, used internally. Each
832 element takes the form
834 (FUNCTION CALLERS CALLS)
836 where CALLERS is a list of functions that call FUNCTION, and CALLS
837 is a list of functions for which calls were generated while
840 -- Variable: byte-compile-call-tree-sort
841 When non-`nil', sort the call tree. The values `name', `callers',
842 `calls', and `calls+callers' specify different fields to sort
843 on.") Default: `name'.
845 `byte-compile-overwrite-file' controls treatment of existing
848 -- Variable: byte-compile-overwrite-file
849 When non-`nil', do not preserve backups of `.elc's. Precisely, if
850 `nil', old `.elc' files are deleted before the new one is saved,
851 and `.elc' files will have the same modes as the corresponding
852 `.el' file. Otherwise, existing `.elc' files will simply be
853 overwritten, and the existing modes will not be changed. If this
854 variable is `nil', then an `.elc' file which is a symbolic link
855 will be turned into a normal file, instead of the file which the
856 link points to being overwritten. Default: `t'.
858 Variables controlling recompiling directories are described elsewhere
859 *Note Compilation Functions::. They are
860 `byte-recompile-directory-ignore-errors-p' and
861 `byte-recompile-directory-recursively'.
863 The dynamic loading features are described elsewhere. These are
864 controlled by the variables `byte-compile-dynamic' (*note Dynamic
865 Loading::) and `byte-compile-dynamic-docstrings' (*note Docs and
868 The byte compiler is a relatively recent development, and has evolved
869 significantly over the period covering Emacs versions 19 and 20. The
870 following variables control use of newer functionality by the byte
871 compiler. These are rarely needed since the release of XEmacs 21.
873 Another set of compatibility issues arises between Mule and non-Mule
874 XEmacsen; there are no known compatibility issues specific to the byte
875 compiler. There are also compatibility issues between XEmacs and GNU
876 Emacs's versions of the byte compiler. While almost all of the byte
877 codes are the same, and code compiled by one version often runs
878 perfectly well on the other, this is very dangerous, and can result in
879 crashes or data loss. Always recompile your Lisp when moving between
880 XEmacs and GNU Emacs.
882 -- Variable: byte-compile-single-version nil
883 When non-`nil', the choice of emacs version (v19 or v20) byte-codes
884 will be hard-coded into bytecomp when it compiles itself. If the
885 compiler itself is compiled with optimization, this causes a
886 speedup. Default: `nil'.
888 -- Variable: byte-compile-emacs19-compatibility
889 When non-`nil' generate output that can run in Emacs 19. Default:
890 `nil' when Emacs version is 20 or above, otherwise `t'.
892 -- Variable: byte-compile-print-gensym
893 When non-`nil', the compiler may generate code that creates unique
894 symbols at run-time. This is achieved by printing uninterned
895 symbols using the `#:' notation, so that they will be read
898 With this feature, code that uses uninterned symbols in macros will
899 not be runnable under pre-21.0 XEmacsen.
901 Default: When `byte-compile-emacs19-compatibility' is non-nil, this
902 variable is ignored and considered to be `nil'. Otherwise `t'.
904 -- Variable: byte-compile-new-bytecodes
905 This is completely ignored. For backwards compatibility.
907 -- Function: byte-compiler-options &rest args
908 Set some compilation-parameters for this file. This will affect
909 only the file in which it appears; this does nothing when
910 evaluated, or when loaded from a `.el' file.
912 Each argument to this macro must be a list of a key and a value.
913 (#### Need to check whether the newer variables are settable here.)
915 Keys: Values: Corresponding variable:
917 verbose t, nil byte-compile-verbose
918 optimize t, nil, source, byte byte-optimize
919 warnings list of warnings byte-compile-warnings
920 file-format emacs19, emacs20 byte-compile-emacs19-compatibility
922 The value specified with the `warnings'option must be a list,
923 containing some subset of the following flags:
925 free-vars references to variables not in the current lexical scope.
926 unused-vars references to non-global variables bound but not referenced.
927 unresolved calls to unknown functions.
928 callargs lambda calls with args that don't match the definition.
929 redefine function cell redefined from a macro to a lambda or vice
930 versa, or redefined to take a different number of arguments.
932 If the first element if the list is `+' or ``' then the specified
933 elements are added to or removed from the current set of warnings,
934 instead of the entire set of warnings being overwritten. (####
935 Need to check whether the newer warnings are settable here.)
937 For example, something like this might appear at the top of a
940 (byte-compiler-options
942 (warnings (- callargs)) ; Don't warn about arglist mismatch
943 (warnings (+ unused-vars)) ; Do warn about unused bindings
944 (file-format emacs19))
947 File: lispref.info, Node: Docs and Compilation, Next: Dynamic Loading, Prev: Compilation Options, Up: Byte Compilation
949 21.4 Documentation Strings and Compilation
950 ==========================================
952 Functions and variables loaded from a byte-compiled file access their
953 documentation strings dynamically from the file whenever needed. This
954 saves space within Emacs, and makes loading faster because the
955 documentation strings themselves need not be processed while loading the
956 file. Actual access to the documentation strings becomes slower as a
957 result, but normally not enough to bother users.
959 Dynamic access to documentation strings does have drawbacks:
961 * If you delete or move the compiled file after loading it, Emacs
962 can no longer access the documentation strings for the functions
963 and variables in the file.
965 * If you alter the compiled file (such as by compiling a new
966 version), then further access to documentation strings in this
967 file will give nonsense results.
969 If your site installs Emacs following the usual procedures, these
970 problems will never normally occur. Installing a new version uses a new
971 directory with a different name; as long as the old version remains
972 installed, its files will remain unmodified in the places where they are
975 However, if you have built Emacs yourself and use it from the
976 directory where you built it, you will experience this problem
977 occasionally if you edit and recompile Lisp files. When it happens, you
978 can cure the problem by reloading the file after recompiling it.
980 Versions of Emacs up to and including XEmacs 19.14 and FSF Emacs
981 19.28 do not support the dynamic docstrings feature, and so will not be
982 able to load bytecode created by more recent Emacs versions. You can
983 turn off the dynamic docstring feature by setting
984 `byte-compile-dynamic-docstrings' to `nil'. Once this is done, you can
985 compile files that will load into older Emacs versions. You can do
986 this globally, or for one source file by specifying a file-local
987 binding for the variable. Here's one way to do that:
989 -*-byte-compile-dynamic-docstrings: nil;-*-
991 -- Variable: byte-compile-dynamic-docstrings
992 If this is non-`nil', the byte compiler generates compiled files
993 that are set up for dynamic loading of documentation strings.
996 The dynamic documentation string feature writes compiled files that
997 use a special Lisp reader construct, `#@COUNT'. This construct skips
998 the next COUNT characters. It also uses the `#$' construct, which
999 stands for "the name of this file, as a string." It is best not to use
1000 these constructs in Lisp source files.
1003 File: lispref.info, Node: Dynamic Loading, Next: Eval During Compile, Prev: Docs and Compilation, Up: Byte Compilation
1005 21.5 Dynamic Loading of Individual Functions
1006 ============================================
1008 When you compile a file, you can optionally enable the "dynamic
1009 function loading" feature (also known as "lazy loading"). With dynamic
1010 function loading, loading the file doesn't fully read the function
1011 definitions in the file. Instead, each function definition contains a
1012 place-holder which refers to the file. The first time each function is
1013 called, it reads the full definition from the file, to replace the
1016 The advantage of dynamic function loading is that loading the file
1017 becomes much faster. This is a good thing for a file which contains
1018 many separate commands, provided that using one of them does not imply
1019 you will soon (or ever) use the rest. A specialized mode which provides
1020 many keyboard commands often has that usage pattern: a user may invoke
1021 the mode, but use only a few of the commands it provides.
1023 The dynamic loading feature has certain disadvantages:
1025 * If you delete or move the compiled file after loading it, Emacs
1026 can no longer load the remaining function definitions not already
1029 * If you alter the compiled file (such as by compiling a new
1030 version), then trying to load any function not already loaded will
1031 get nonsense results.
1033 If you compile a new version of the file, the best thing to do is
1034 immediately load the new compiled file. That will prevent any future
1037 The byte compiler uses the dynamic function loading feature if the
1038 variable `byte-compile-dynamic' is non-`nil' at compilation time. Do
1039 not set this variable globally, since dynamic loading is desirable only
1040 for certain files. Instead, enable the feature for specific source
1041 files with file-local variable bindings, like this:
1043 -*-byte-compile-dynamic: t;-*-
1045 -- Variable: byte-compile-dynamic
1046 If this is non-`nil', the byte compiler generates compiled files
1047 that are set up for dynamic function loading. Default: nil.
1049 -- Function: fetch-bytecode function
1050 This immediately finishes loading the definition of FUNCTION from
1051 its byte-compiled file, if it is not fully loaded already. The
1052 argument FUNCTION may be a compiled-function object or a function
1056 File: lispref.info, Node: Eval During Compile, Next: Compiled-Function Objects, Prev: Dynamic Loading, Up: Byte Compilation
1058 21.6 Evaluation During Compilation
1059 ==================================
1061 These features permit you to write code to be evaluated during
1062 compilation of a program.
1064 -- Special Form: eval-and-compile body
1065 This form marks BODY to be evaluated both when you compile the
1066 containing code and when you run it (whether compiled or not).
1068 You can get a similar result by putting BODY in a separate file
1069 and referring to that file with `require'. Using `require' is
1070 preferable if there is a substantial amount of code to be executed
1073 -- Special Form: eval-when-compile body
1074 This form marks BODY to be evaluated at compile time and not when
1075 the compiled program is loaded. The result of evaluation by the
1076 compiler becomes a constant which appears in the compiled program.
1077 When the program is interpreted, not compiled at all, BODY is
1080 At top level, this is analogous to the Common Lisp idiom
1081 `(eval-when (compile eval) ...)'. Elsewhere, the Common Lisp `#.'
1082 reader macro (but not when interpreting) is closer to what
1083 `eval-when-compile' does.
1086 File: lispref.info, Node: Compiled-Function Objects, Next: Disassembly, Prev: Eval During Compile, Up: Byte Compilation
1088 21.7 Compiled-Function Objects
1089 ==============================
1091 Byte-compiled functions have a special data type: they are
1092 "compiled-function objects". The evaluator handles this data type
1093 specially when it appears as a function to be called.
1095 The printed representation for a compiled-function object normally
1096 begins with `#<compiled-function' and ends with `>'. However, if the
1097 variable `print-readably' is non-`nil', the object is printed beginning
1098 with `#[' and ending with `]'. This representation can be read
1099 directly by the Lisp reader, and is used in byte-compiled files (those
1102 In Emacs version 18, there was no compiled-function object data type;
1103 compiled functions used the function `byte-code' to run the byte code.
1105 A compiled-function object has a number of different attributes.
1109 The list of argument symbols.
1112 The string containing the byte-code instructions.
1115 The vector of Lisp objects referenced by the byte code. These
1116 include symbols used as function names and variable names.
1119 The maximum stack size this function needs.
1122 The documentation string (if any); otherwise, `nil'. The value may
1123 be a number or a list, in case the documentation string is stored
1124 in a file. Use the function `documentation' to get the real
1125 documentation string (*note Accessing Documentation::).
1128 The interactive spec (if any). This can be a string or a Lisp
1129 expression. It is `nil' for a function that isn't interactive.
1132 The domain (if any). This is only meaningful if I18N3
1133 (message-translation) support was compiled into XEmacs. This is a
1134 string defining which domain to find the translation for the
1135 documentation string and interactive prompt. *Note Domain
1138 Here's an example of a compiled-function object, in printed
1139 representation. It is the definition of the command `backward-sexp'.
1141 (symbol-function 'backward-sexp)
1142 => #<compiled-function
1144 "...(15)" [arg 1 forward-sexp] 2 854740 "_p">
1146 The primitive way to create a compiled-function object is with
1149 -- Function: make-byte-code arglist instructions constants stack-depth
1150 &optional doc-string interactive
1151 This function constructs and returns a compiled-function object
1152 with the specified attributes.
1154 _Please note:_ Unlike all other Emacs-lisp functions, calling this
1155 with five arguments is _not_ the same as calling it with six
1156 arguments, the last of which is `nil'. If the INTERACTIVE arg is
1157 specified as `nil', then that means that this function was defined
1158 with `(interactive)'. If the arg is not specified, then that means
1159 the function is not interactive. This is terrible behavior which
1160 is retained for compatibility with old `.elc' files which expected
1163 You should not try to come up with the elements for a
1164 compiled-function object yourself, because if they are inconsistent,
1165 XEmacs may crash when you call the function. Always leave it to the
1166 byte compiler to create these objects; it makes the elements consistent
1169 The following primitives are provided for accessing the elements of
1170 a compiled-function object.
1172 -- Function: compiled-function-arglist function
1173 This function returns the argument list of compiled-function object
1176 -- Function: compiled-function-instructions function
1177 This function returns a string describing the byte-code
1178 instructions of compiled-function object FUNCTION.
1180 -- Function: compiled-function-constants function
1181 This function returns the vector of Lisp objects referenced by
1182 compiled-function object FUNCTION.
1184 -- Function: compiled-function-stack-depth function
1185 This function returns the maximum stack size needed by
1186 compiled-function object FUNCTION.
1188 -- Function: compiled-function-doc-string function
1189 This function returns the doc string of compiled-function object
1190 FUNCTION, if available.
1192 -- Function: compiled-function-interactive function
1193 This function returns the interactive spec of compiled-function
1194 object FUNCTION, if any. The return value is `nil' or a
1195 two-element list, the first element of which is the symbol
1196 `interactive' and the second element is the interactive spec (a
1197 string or Lisp form).
1199 -- Function: compiled-function-domain function
1200 This function returns the domain of compiled-function object
1201 FUNCTION, if any. The result will be a string or `nil'. *Note
1202 Domain Specification::.
1205 File: lispref.info, Node: Disassembly, Next: Different Behavior, Prev: Compiled-Function Objects, Up: Byte Compilation
1207 21.8 Disassembled Byte-Code
1208 ===========================
1210 People do not write byte-code; that job is left to the byte compiler.
1211 But we provide a disassembler to satisfy a cat-like curiosity. The
1212 disassembler converts the byte-compiled code into humanly readable form.
1214 The byte-code interpreter is implemented as a simple stack machine.
1215 It pushes values onto a stack of its own, then pops them off to use them
1216 in calculations whose results are themselves pushed back on the stack.
1217 When a byte-code function returns, it pops a value off the stack and
1218 returns it as the value of the function.
1220 In addition to the stack, byte-code functions can use, bind, and set
1221 ordinary Lisp variables, by transferring values between variables and
1224 -- Command: disassemble object &optional stream
1225 This function prints the disassembled code for OBJECT. If STREAM
1226 is supplied, then output goes there. Otherwise, the disassembled
1227 code is printed to the stream `standard-output'. The argument
1228 OBJECT can be a function name or a lambda expression.
1230 As a special exception, if this function is used interactively, it
1231 outputs to a buffer named `*Disassemble*'.
1233 Here are two examples of using the `disassemble' function. We have
1234 added explanatory comments to help you relate the byte-code to the Lisp
1235 source; these do not appear in the output of `disassemble'.
1237 (defun factorial (integer)
1238 "Compute factorial of an integer."
1240 (* integer (factorial (1- integer)))))
1246 (disassemble 'factorial)
1247 -| byte-code for factorial:
1248 doc: Compute factorial of an integer.
1251 0 varref integer ; Get value of `integer'
1252 ; from the environment
1253 ; and push the value
1256 1 constant 1 ; Push 1 onto stack.
1258 2 eqlsign ; Pop top two values off stack,
1260 ; and push result onto stack.
1262 3 goto-if-nil 1 ; Pop and test top of stack;
1264 ; go to label 1 (which is also byte 7),
1267 5 constant 1 ; Push 1 onto top of stack.
1269 6 return ; Return the top element
1272 7:1 varref integer ; Push value of `integer' onto stack.
1274 8 constant factorial ; Push `factorial' onto stack.
1276 9 varref integer ; Push value of `integer' onto stack.
1278 10 sub1 ; Pop `integer', decrement value,
1279 ; push new value onto stack.
1281 ; Stack now contains:
1282 ; - decremented value of `integer'
1284 ; - value of `integer'
1286 15 call 1 ; Call function `factorial' using
1287 ; the first (i.e., the top) element
1288 ; of the stack as the argument;
1289 ; push returned value onto stack.
1291 ; Stack now contains:
1292 ; - result of recursive
1293 ; call to `factorial'
1294 ; - value of `integer'
1296 12 mult ; Pop top two values off the stack,
1298 ; pushing the result onto the stack.
1300 13 return ; Return the top element
1304 The `silly-loop' function is somewhat more complex:
1306 (defun silly-loop (n)
1307 "Return time before and after N iterations of a loop."
1308 (let ((t1 (current-time-string)))
1309 (while (> (setq n (1- n))
1311 (list t1 (current-time-string))))
1314 (disassemble 'silly-loop)
1315 -| byte-code for silly-loop:
1316 doc: Return time before and after N iterations of a loop.
1319 0 constant current-time-string ; Push
1320 ; `current-time-string'
1321 ; onto top of stack.
1323 1 call 0 ; Call `current-time-string'
1325 ; pushing result onto stack.
1327 2 varbind t1 ; Pop stack and bind `t1'
1330 3:1 varref n ; Get value of `n' from
1331 ; the environment and push
1332 ; the value onto the stack.
1334 4 sub1 ; Subtract 1 from top of stack.
1336 5 dup ; Duplicate the top of the stack;
1337 ; i.e., copy the top of
1338 ; the stack and push the
1339 ; copy onto the stack.
1341 6 varset n ; Pop the top of the stack,
1342 ; and set `n' to the value.
1344 ; In effect, the sequence `dup varset'
1345 ; copies the top of the stack
1346 ; into the value of `n'
1347 ; without popping it.
1349 7 constant 0 ; Push 0 onto stack.
1351 8 gtr ; Pop top two values off stack,
1352 ; test if N is greater than 0
1353 ; and push result onto stack.
1355 9 goto-if-not-nil 1 ; Goto label 1 (byte 3) if `n' <= 0
1356 ; (this exits the while loop).
1357 ; else pop top of stack
1360 11 varref t1 ; Push value of `t1' onto stack.
1362 12 constant current-time-string ; Push
1363 ; `current-time-string'
1364 ; onto top of stack.
1366 13 call 0 ; Call `current-time-string' again.
1368 14 unbind 1 ; Unbind `t1' in local environment.
1370 15 list2 ; Pop top two elements off stack,
1371 ; create a list of them,
1372 ; and push list onto stack.
1374 16 return ; Return the top element of the stack.
1379 File: lispref.info, Node: Different Behavior, Prev: Disassembly, Up: Byte Compilation
1381 21.9 Different Behavior
1382 =======================
1384 The intent is that compiled byte-code and the corresponding code
1385 executed by the Lisp interpreter produce identical results. However,
1386 there are some circumstances where the results will differ.
1388 * Arithmetic operations may be rearranged for efficiency or
1389 compile-time evaluation. When floating point numbers are
1390 involved, this may produce different values or an overflow.
1392 * Some arithmetic operations may be optimized away. For example, the
1393 expression `(+ x)' may be optimized to simply `x'. If the value
1394 of `x' is a marker, then the value will be a marker instead of an
1395 integer. If the value of `x' is a cons cell, then the interpreter
1396 will issue an error, while the bytecode will not.
1398 If you're trying to use `(+ OBJECT 0)' to convert OBJECT to
1399 integer, consider using an explicit conversion function, which is
1400 clearer and guaranteed to work. Instead of `(+ MARKER 0)', use
1401 `(marker-position MARKER)'. Instead of `(+ CHAR 0)', use
1404 For maximal equivalence between interpreted and compiled code, the
1405 variables `byte-compile-delete-errors' and `byte-compile-optimize' can
1406 be set to `nil', but this is not recommended.
1409 File: lispref.info, Node: Debugging, Next: Read and Print, Prev: Byte Compilation, Up: Top
1411 22 Debugging Lisp Programs
1412 **************************
1414 There are three ways to investigate a problem in an XEmacs Lisp program,
1415 depending on what you are doing with the program when the problem
1418 * If the problem occurs when you run the program, you can use a Lisp
1419 debugger (either the default debugger or Edebug) to investigate
1420 what is happening during execution.
1422 * If the problem is syntactic, so that Lisp cannot even read the
1423 program, you can use the XEmacs facilities for editing Lisp to
1426 * If the problem occurs when trying to compile the program with the
1427 byte compiler, you need to know how to examine the compiler's
1432 * Debugger:: How the XEmacs Lisp debugger is implemented.
1433 * Syntax Errors:: How to find syntax errors.
1434 * Compilation Errors:: How to find errors that show up in byte compilation.
1435 * Edebug:: A source-level XEmacs Lisp debugger.
1437 Another useful debugging tool is the dribble file. When a dribble
1438 file is open, XEmacs copies all keyboard input characters to that file.
1439 Afterward, you can examine the file to find out what input was used.
1440 *Note Terminal Input::.
1442 For debugging problems in terminal descriptions, the
1443 `open-termscript' function can be useful. *Note Terminal Output::.
1446 File: lispref.info, Node: Debugger, Next: Syntax Errors, Up: Debugging
1448 22.1 The Lisp Debugger
1449 ======================
1451 The "Lisp debugger" provides the ability to suspend evaluation of a
1452 form. While evaluation is suspended (a state that is commonly known as
1453 a "break"), you may examine the run time stack, examine the values of
1454 local or global variables, or change those values. Since a break is a
1455 recursive edit, all the usual editing facilities of XEmacs are
1456 available; you can even run programs that will enter the debugger
1457 recursively. *Note Recursive Editing::.
1461 * Error Debugging:: Entering the debugger when an error happens.
1462 * Infinite Loops:: Stopping and debugging a program that doesn't exit.
1463 * Function Debugging:: Entering it when a certain function is called.
1464 * Explicit Debug:: Entering it at a certain point in the program.
1465 * Using Debugger:: What the debugger does; what you see while in it.
1466 * Debugger Commands:: Commands used while in the debugger.
1467 * Invoking the Debugger:: How to call the function `debug'.
1468 * Internals of Debugger:: Subroutines of the debugger, and global variables.
1471 File: lispref.info, Node: Error Debugging, Next: Infinite Loops, Up: Debugger
1473 22.1.1 Entering the Debugger on an Error
1474 ----------------------------------------
1476 The most important time to enter the debugger is when a Lisp error
1477 happens. This allows you to investigate the immediate causes of the
1480 However, entry to the debugger is not a normal consequence of an
1481 error. Many commands frequently get Lisp errors when invoked in
1482 inappropriate contexts (such as `C-f' at the end of the buffer) and
1483 during ordinary editing it would be very unpleasant to enter the
1484 debugger each time this happens. If you want errors to enter the
1485 debugger, set the variable `debug-on-error' to non-`nil'.
1487 -- User Option: debug-on-error
1488 This variable determines whether the debugger is called when an
1489 error is signaled and not handled. If `debug-on-error' is `t', all
1490 errors call the debugger. If it is `nil', none call the debugger.
1492 The value can also be a list of error conditions that should call
1493 the debugger. For example, if you set it to the list
1494 `(void-variable)', then only errors about a variable that has no
1495 value invoke the debugger.
1497 When this variable is non-`nil', Emacs does not catch errors that
1498 happen in process filter functions and sentinels. Therefore, these
1499 errors also can invoke the debugger. *Note Processes::.
1501 -- User Option: debug-on-signal
1502 This variable is similar to `debug-on-error' but breaks whenever
1503 an error is signalled, regardless of whether it would be handled.
1505 -- User Option: debug-ignored-errors
1506 This variable specifies certain kinds of errors that should not
1507 enter the debugger. Its value is a list of error condition
1508 symbols and/or regular expressions. If the error has any of those
1509 condition symbols, or if the error message matches any of the
1510 regular expressions, then that error does not enter the debugger,
1511 regardless of the value of `debug-on-error'.
1513 The normal value of this variable lists several errors that happen
1514 often during editing but rarely result from bugs in Lisp programs.
1516 To debug an error that happens during loading of the `.emacs' file,
1517 use the option `-debug-init', which binds `debug-on-error' to `t' while
1518 `.emacs' is loaded and inhibits use of `condition-case' to catch init
1521 If your `.emacs' file sets `debug-on-error', the effect may not last
1522 past the end of loading `.emacs'. (This is an undesirable byproduct of
1523 the code that implements the `-debug-init' command line option.) The
1524 best way to make `.emacs' set `debug-on-error' permanently is with
1525 `after-init-hook', like this:
1527 (add-hook 'after-init-hook
1528 '(lambda () (setq debug-on-error t)))
1531 File: lispref.info, Node: Infinite Loops, Next: Function Debugging, Prev: Error Debugging, Up: Debugger
1533 22.1.2 Debugging Infinite Loops
1534 -------------------------------
1536 When a program loops infinitely and fails to return, your first problem
1537 is to stop the loop. On most operating systems, you can do this with
1538 `C-g', which causes quit.
1540 Ordinary quitting gives no information about why the program was
1541 looping. To get more information, you can set the variable
1542 `debug-on-quit' to non-`nil'. Quitting with `C-g' is not considered an
1543 error, and `debug-on-error' has no effect on the handling of `C-g'.
1544 Likewise, `debug-on-quit' has no effect on errors.
1546 Once you have the debugger running in the middle of the infinite
1547 loop, you can proceed from the debugger using the stepping commands.
1548 If you step through the entire loop, you will probably get enough
1549 information to solve the problem.
1551 -- User Option: debug-on-quit
1552 This variable determines whether the debugger is called when `quit'
1553 is signaled and not handled. If `debug-on-quit' is non-`nil',
1554 then the debugger is called whenever you quit (that is, type
1555 `C-g'). If `debug-on-quit' is `nil', then the debugger is not
1556 called when you quit. *Note Quitting::.
1559 File: lispref.info, Node: Function Debugging, Next: Explicit Debug, Prev: Infinite Loops, Up: Debugger
1561 22.1.3 Entering the Debugger on a Function Call
1562 -----------------------------------------------
1564 To investigate a problem that happens in the middle of a program, one
1565 useful technique is to enter the debugger whenever a certain function is
1566 called. You can do this to the function in which the problem occurs,
1567 and then step through the function, or you can do this to a function
1568 called shortly before the problem, step quickly over the call to that
1569 function, and then step through its caller.
1571 -- Command: debug-on-entry function-name
1572 This function requests FUNCTION-NAME to invoke the debugger each
1573 time it is called. It works by inserting the form `(debug
1574 'debug)' into the function definition as the first form.
1576 Any function defined as Lisp code may be set to break on entry,
1577 regardless of whether it is interpreted code or compiled code. If
1578 the function is a command, it will enter the debugger when called
1579 from Lisp and when called interactively (after the reading of the
1580 arguments). You can't debug primitive functions (i.e., those
1581 written in C) this way.
1583 When `debug-on-entry' is called interactively, it prompts for
1584 FUNCTION-NAME in the minibuffer.
1586 If the function is already set up to invoke the debugger on entry,
1587 `debug-on-entry' does nothing.
1589 *Please note:* if you redefine a function after using
1590 `debug-on-entry' on it, the code to enter the debugger is lost.
1592 `debug-on-entry' returns FUNCTION-NAME.
1596 (* n (fact (1- n)))))
1598 (debug-on-entry 'fact)
1602 ------ Buffer: *Backtrace* ------
1605 eval-region(4870 4878 t)
1609 eval-insert-last-sexp(nil)
1610 * call-interactively(eval-insert-last-sexp)
1611 ------ Buffer: *Backtrace* ------
1613 (symbol-function 'fact)
1615 (debug (quote debug))
1616 (if (zerop n) 1 (* n (fact (1- n)))))
1618 -- Command: cancel-debug-on-entry &optional function-name
1619 This function undoes the effect of `debug-on-entry' on
1620 FUNCTION-NAME. When called interactively, it prompts for
1621 FUNCTION-NAME in the minibuffer. If FUNCTION-NAME is `nil' or the
1622 empty string, it cancels debugging for all functions.
1624 If `cancel-debug-on-entry' is called more than once on the same
1625 function, the second call does nothing. `cancel-debug-on-entry'
1626 returns FUNCTION-NAME.
1629 File: lispref.info, Node: Explicit Debug, Next: Using Debugger, Prev: Function Debugging, Up: Debugger
1631 22.1.4 Explicit Entry to the Debugger
1632 -------------------------------------
1634 You can cause the debugger to be called at a certain point in your
1635 program by writing the expression `(debug)' at that point. To do this,
1636 visit the source file, insert the text `(debug)' at the proper place,
1637 and type `C-M-x'. Be sure to undo this insertion before you save the
1640 The place where you insert `(debug)' must be a place where an
1641 additional form can be evaluated and its value ignored. (If the value
1642 of `(debug)' isn't ignored, it will alter the execution of the
1643 program!) The most common suitable places are inside a `progn' or an
1644 implicit `progn' (*note Sequencing::).
1647 File: lispref.info, Node: Using Debugger, Next: Debugger Commands, Prev: Explicit Debug, Up: Debugger
1649 22.1.5 Using the Debugger
1650 -------------------------
1652 When the debugger is entered, it displays the previously selected
1653 buffer in one window and a buffer named `*Backtrace*' in another
1654 window. The backtrace buffer contains one line for each level of Lisp
1655 function execution currently going on. At the beginning of this buffer
1656 is a message describing the reason that the debugger was invoked (such
1657 as the error message and associated data, if it was invoked due to an
1660 The backtrace buffer is read-only and uses a special major mode,
1661 Debugger mode, in which letters are defined as debugger commands. The
1662 usual XEmacs editing commands are available; thus, you can switch
1663 windows to examine the buffer that was being edited at the time of the
1664 error, switch buffers, visit files, or do any other sort of editing.
1665 However, the debugger is a recursive editing level (*note Recursive
1666 Editing::) and it is wise to go back to the backtrace buffer and exit
1667 the debugger (with the `q' command) when you are finished with it.
1668 Exiting the debugger gets out of the recursive edit and kills the
1671 The backtrace buffer shows you the functions that are executing and
1672 their argument values. It also allows you to specify a stack frame by
1673 moving point to the line describing that frame. (A stack frame is the
1674 place where the Lisp interpreter records information about a particular
1675 invocation of a function.) The frame whose line point is on is
1676 considered the "current frame". Some of the debugger commands operate
1677 on the current frame.
1679 The debugger itself must be run byte-compiled, since it makes
1680 assumptions about how many stack frames are used for the debugger
1681 itself. These assumptions are false if the debugger is running
1685 File: lispref.info, Node: Debugger Commands, Next: Invoking the Debugger, Prev: Using Debugger, Up: Debugger
1687 22.1.6 Debugger Commands
1688 ------------------------
1690 Inside the debugger (in Debugger mode), these special commands are
1691 available in addition to the usual cursor motion commands. (Keep in
1692 mind that all the usual facilities of XEmacs, such as switching windows
1693 or buffers, are still available.)
1695 The most important use of debugger commands is for stepping through
1696 code, so that you can see how control flows. The debugger can step
1697 through the control structures of an interpreted function, but cannot do
1698 so in a byte-compiled function. If you would like to step through a
1699 byte-compiled function, replace it with an interpreted definition of the
1700 same function. (To do this, visit the source file for the function and
1701 type `C-M-x' on its definition.)
1703 Here is a list of Debugger mode commands:
1706 Exit the debugger and continue execution. This resumes execution
1707 of the program as if the debugger had never been entered (aside
1708 from the effect of any variables or data structures you may have
1709 changed while inside the debugger).
1711 Continuing when an error or quit was signalled will cause the
1712 normal action of the signalling to take place. If you do not want
1713 this to happen, but instead want the program execution to continue
1714 as if the call to `signal' did not occur, use the `r' command.
1717 Continue execution, but enter the debugger the next time any Lisp
1718 function is called. This allows you to step through the
1719 subexpressions of an expression, seeing what values the
1720 subexpressions compute, and what else they do.
1722 The stack frame made for the function call which enters the
1723 debugger in this way will be flagged automatically so that the
1724 debugger will be called again when the frame is exited. You can
1725 use the `u' command to cancel this flag.
1728 Flag the current frame so that the debugger will be entered when
1729 the frame is exited. Frames flagged in this way are marked with
1730 stars in the backtrace buffer.
1733 Don't enter the debugger when the current frame is exited. This
1734 cancels a `b' command on that frame.
1737 Read a Lisp expression in the minibuffer, evaluate it, and print
1738 the value in the echo area. The debugger alters certain important
1739 variables, and the current buffer, as part of its operation; `e'
1740 temporarily restores their outside-the-debugger values so you can
1741 examine them. This makes the debugger more transparent. By
1742 contrast, `M-:' does nothing special in the debugger; it shows you
1743 the variable values within the debugger.
1746 Terminate the program being debugged; return to top-level XEmacs
1749 If the debugger was entered due to a `C-g' but you really want to
1750 quit, and not debug, use the `q' command.
1753 Return a value from the debugger. The value is computed by
1754 reading an expression with the minibuffer and evaluating it.
1756 The `r' command is useful when the debugger was invoked due to exit
1757 from a Lisp call frame (as requested with `b'); then the value
1758 specified in the `r' command is used as the value of that frame.
1759 It is also useful if you call `debug' and use its return value.
1761 If the debugger was entered at the beginning of a function call,
1762 `r' has the same effect as `c', and the specified return value
1765 If the debugger was entered through a call to `signal' (i.e. as a
1766 result of an error or quit), then returning a value will cause the
1767 call to `signal' itself to return, rather than throwing to
1768 top-level or invoking a handler, as is normal. This allows you to
1769 correct an error (e.g. the type of an argument was wrong) or
1770 continue from a `debug-on-quit' as if it never happened.
1772 Note that some errors (e.g. any error signalled using the `error'
1773 function, and many errors signalled from a primitive function) are
1774 not continuable. If you return a value from them and continue
1775 execution, then the error will immediately be signalled again.
1776 Other errors (e.g. wrong-type-argument errors) will be continually
1777 resignalled until the problem is corrected.
1780 File: lispref.info, Node: Invoking the Debugger, Next: Internals of Debugger, Prev: Debugger Commands, Up: Debugger
1782 22.1.7 Invoking the Debugger
1783 ----------------------------
1785 Here we describe fully the function used to invoke the debugger.
1787 -- Function: debug &rest debugger-args
1788 This function enters the debugger. It switches buffers to a buffer
1789 named `*Backtrace*' (or `*Backtrace*<2>' if it is the second
1790 recursive entry to the debugger, etc.), and fills it with
1791 information about the stack of Lisp function calls. It then
1792 enters a recursive edit, showing the backtrace buffer in Debugger
1795 The Debugger mode `c' and `r' commands exit the recursive edit;
1796 then `debug' switches back to the previous buffer and returns to
1797 whatever called `debug'. This is the only way the function
1798 `debug' can return to its caller.
1800 If the first of the DEBUGGER-ARGS passed to `debug' is `nil' (or
1801 if it is not one of the special values in the table below), then
1802 `debug' displays the rest of its arguments at the top of the
1803 `*Backtrace*' buffer. This mechanism is used to display a message
1806 However, if the first argument passed to `debug' is one of the
1807 following special values, then it has special significance.
1808 Normally, these values are passed to `debug' only by the internals
1809 of XEmacs and the debugger, and not by programmers calling `debug'.
1811 The special values are:
1814 A first argument of `lambda' means `debug' was called because
1815 of entry to a function when `debug-on-next-call' was
1816 non-`nil'. The debugger displays `Entering:' as a line of
1817 text at the top of the buffer.
1820 `debug' as first argument indicates a call to `debug' because
1821 of entry to a function that was set to debug on entry. The
1822 debugger displays `Entering:', just as in the `lambda' case.
1823 It also marks the stack frame for that function so that it
1824 will invoke the debugger when exited.
1827 When the first argument is `t', this indicates a call to
1828 `debug' due to evaluation of a list form when
1829 `debug-on-next-call' is non-`nil'. The debugger displays the
1830 following as the top line in the buffer:
1832 Beginning evaluation of function call form:
1835 When the first argument is `exit', it indicates the exit of a
1836 stack frame previously marked to invoke the debugger on exit.
1837 The second argument given to `debug' in this case is the
1838 value being returned from the frame. The debugger displays
1839 `Return value:' on the top line of the buffer, followed by
1840 the value being returned.
1843 When the first argument is `error', the debugger indicates
1844 that it is being entered because an error or `quit' was
1845 signaled and not handled, by displaying `Signaling:' followed
1846 by the error signaled and any arguments to `signal'. For
1849 (let ((debug-on-error t))
1852 ------ Buffer: *Backtrace* ------
1853 Signaling: (arith-error)
1856 ------ Buffer: *Backtrace* ------
1858 If an error was signaled, presumably the variable
1859 `debug-on-error' is non-`nil'. If `quit' was signaled, then
1860 presumably the variable `debug-on-quit' is non-`nil'.
1863 Use `nil' as the first of the DEBUGGER-ARGS when you want to
1864 enter the debugger explicitly. The rest of the DEBUGGER-ARGS
1865 are printed on the top line of the buffer. You can use this
1866 feature to display messages--for example, to remind yourself
1867 of the conditions under which `debug' is called.
1870 File: lispref.info, Node: Internals of Debugger, Prev: Invoking the Debugger, Up: Debugger
1872 22.1.8 Internals of the Debugger
1873 --------------------------------
1875 This section describes functions and variables used internally by the
1878 -- Variable: debugger
1879 The value of this variable is the function to call to invoke the
1880 debugger. Its value must be a function of any number of arguments
1881 (or, more typically, the name of a function). Presumably this
1882 function will enter some kind of debugger. The default value of
1883 the variable is `debug'.
1885 The first argument that Lisp hands to the function indicates why it
1886 was called. The convention for arguments is detailed in the
1887 description of `debug'.
1889 -- Command: backtrace &optional stream detailed
1890 This function prints a trace of Lisp function calls currently
1891 active. This is the function used by `debug' to fill up the
1892 `*Backtrace*' buffer. It is written in C, since it must have
1893 access to the stack to determine which function calls are active.
1894 The return value is always `nil'.
1896 The backtrace is normally printed to `standard-output', but this
1897 can be changed by specifying a value for STREAM. If DETAILED is
1898 non-`nil', the backtrace also shows places where currently active
1899 variable bindings, catches, condition-cases, and unwind-protects
1900 were made as well as function calls.
1902 In the following example, a Lisp expression calls `backtrace'
1903 explicitly. This prints the backtrace to the stream
1904 `standard-output': in this case, to the buffer `backtrace-output'.
1905 Each line of the backtrace represents one function call. The
1906 line shows the values of the function's arguments if they are all
1907 known. If they are still being computed, the line says so. The
1908 arguments of special forms are elided.
1910 (with-output-to-temp-buffer "backtrace-output"
1913 (setq var (eval '(progn
1915 (list 'testing (backtrace))))))))
1919 ----------- Buffer: backtrace-output ------------
1921 (list ...computing arguments...)
1923 eval((progn (1+ var) (list (quote testing) (backtrace))))
1925 (save-excursion ...)
1927 (with-output-to-temp-buffer ...)
1928 eval-region(1973 2142 #<buffer *scratch*>)
1929 byte-code("... for eval-print-last-sexp ...")
1930 eval-print-last-sexp(nil)
1931 * call-interactively(eval-print-last-sexp)
1932 ----------- Buffer: backtrace-output ------------
1934 The character `*' indicates a frame whose debug-on-exit flag is
1937 -- Variable: debug-on-next-call
1938 If this variable is non-`nil', it says to call the debugger before
1939 the next `eval', `apply' or `funcall'. Entering the debugger sets
1940 `debug-on-next-call' to `nil'.
1942 The `d' command in the debugger works by setting this variable.
1944 -- Function: backtrace-debug level flag
1945 This function sets the debug-on-exit flag of the stack frame LEVEL
1946 levels down the stack, giving it the value FLAG. If FLAG is
1947 non-`nil', this will cause the debugger to be entered when that
1948 frame later exits. Even a nonlocal exit through that frame will
1951 This function is used only by the debugger.
1953 -- Variable: command-debug-status
1954 This variable records the debugging status of the current
1955 interactive command. Each time a command is called interactively,
1956 this variable is bound to `nil'. The debugger can set this
1957 variable to leave information for future debugger invocations
1958 during the same command.
1960 The advantage, for the debugger, of using this variable rather than
1961 another global variable is that the data will never carry over to a
1962 subsequent command invocation.
1964 -- Function: backtrace-frame frame-number
1965 The function `backtrace-frame' is intended for use in Lisp
1966 debuggers. It returns information about what computation is
1967 happening in the stack frame FRAME-NUMBER levels down.
1969 If that frame has not evaluated the arguments yet (or is a special
1970 form), the value is `(nil FUNCTION ARG-FORMS...)'.
1972 If that frame has evaluated its arguments and called its function
1973 already, the value is `(t FUNCTION ARG-VALUES...)'.
1975 In the return value, FUNCTION is whatever was supplied as the CAR
1976 of the evaluated list, or a `lambda' expression in the case of a
1977 macro call. If the function has a `&rest' argument, that is
1978 represented as the tail of the list ARG-VALUES.
1980 If FRAME-NUMBER is out of range, `backtrace-frame' returns `nil'.
1983 File: lispref.info, Node: Syntax Errors, Next: Compilation Errors, Prev: Debugger, Up: Debugging
1985 22.2 Debugging Invalid Lisp Syntax
1986 ==================================
1988 The Lisp reader reports invalid syntax, but cannot say where the real
1989 problem is. For example, the error "End of file during parsing" in
1990 evaluating an expression indicates an excess of open parentheses (or
1991 square brackets). The reader detects this imbalance at the end of the
1992 file, but it cannot figure out where the close parenthesis should have
1993 been. Likewise, "Invalid read syntax: ")"" indicates an excess close
1994 parenthesis or missing open parenthesis, but does not say where the
1995 missing parenthesis belongs. How, then, to find what to change?
1997 If the problem is not simply an imbalance of parentheses, a useful
1998 technique is to try `C-M-e' at the beginning of each defun, and see if
1999 it goes to the place where that defun appears to end. If it does not,
2000 there is a problem in that defun.
2002 However, unmatched parentheses are the most common syntax errors in
2003 Lisp, and we can give further advice for those cases.
2007 * Excess Open:: How to find a spurious open paren or missing close.
2008 * Excess Close:: How to find a spurious close paren or missing open.
2011 File: lispref.info, Node: Excess Open, Next: Excess Close, Up: Syntax Errors
2013 22.2.1 Excess Open Parentheses
2014 ------------------------------
2016 The first step is to find the defun that is unbalanced. If there is an
2017 excess open parenthesis, the way to do this is to insert a close
2018 parenthesis at the end of the file and type `C-M-b' (`backward-sexp').
2019 This will move you to the beginning of the defun that is unbalanced.
2020 (Then type `C-<SPC> C-_ C-u C-<SPC>' to set the mark there, undo the
2021 insertion of the close parenthesis, and finally return to the mark.)
2023 The next step is to determine precisely what is wrong. There is no
2024 way to be sure of this except to study the program, but often the
2025 existing indentation is a clue to where the parentheses should have
2026 been. The easiest way to use this clue is to reindent with `C-M-q' and
2029 Before you do this, make sure the defun has enough close parentheses.
2030 Otherwise, `C-M-q' will get an error, or will reindent all the rest of
2031 the file until the end. So move to the end of the defun and insert a
2032 close parenthesis there. Don't use `C-M-e' to move there, since that
2033 too will fail to work until the defun is balanced.
2035 Now you can go to the beginning of the defun and type `C-M-q'.
2036 Usually all the lines from a certain point to the end of the function
2037 will shift to the right. There is probably a missing close parenthesis,
2038 or a superfluous open parenthesis, near that point. (However, don't
2039 assume this is true; study the code to make sure.) Once you have found
2040 the discrepancy, undo the `C-M-q' with `C-_', since the old indentation
2041 is probably appropriate to the intended parentheses.
2043 After you think you have fixed the problem, use `C-M-q' again. If
2044 the old indentation actually fit the intended nesting of parentheses,
2045 and you have put back those parentheses, `C-M-q' should not change
2049 File: lispref.info, Node: Excess Close, Prev: Excess Open, Up: Syntax Errors
2051 22.2.2 Excess Close Parentheses
2052 -------------------------------
2054 To deal with an excess close parenthesis, first insert an open
2055 parenthesis at the beginning of the file, back up over it, and type
2056 `C-M-f' to find the end of the unbalanced defun. (Then type `C-<SPC>
2057 C-_ C-u C-<SPC>' to set the mark there, undo the insertion of the open
2058 parenthesis, and finally return to the mark.)
2060 Then find the actual matching close parenthesis by typing `C-M-f' at
2061 the beginning of the defun. This will leave you somewhere short of the
2062 place where the defun ought to end. It is possible that you will find
2063 a spurious close parenthesis in that vicinity.
2065 If you don't see a problem at that point, the next thing to do is to
2066 type `C-M-q' at the beginning of the defun. A range of lines will
2067 probably shift left; if so, the missing open parenthesis or spurious
2068 close parenthesis is probably near the first of those lines. (However,
2069 don't assume this is true; study the code to make sure.) Once you have
2070 found the discrepancy, undo the `C-M-q' with `C-_', since the old
2071 indentation is probably appropriate to the intended parentheses.
2073 After you think you have fixed the problem, use `C-M-q' again. If
2074 the old indentation actually fit the intended nesting of parentheses,
2075 and you have put back those parentheses, `C-M-q' should not change
2079 File: lispref.info, Node: Compilation Errors, Next: Edebug, Prev: Syntax Errors, Up: Debugging
2081 22.3 Debugging Problems in Compilation
2082 ======================================
2084 When an error happens during byte compilation, it is normally due to
2085 invalid syntax in the program you are compiling. The compiler prints a
2086 suitable error message in the `*Compile-Log*' buffer, and then stops.
2087 The message may state a function name in which the error was found, or
2088 it may not. Either way, here is how to find out where in the file the
2091 What you should do is switch to the buffer ` *Compiler Input*'.
2092 (Note that the buffer name starts with a space, so it does not show up
2093 in `M-x list-buffers'.) This buffer contains the program being
2094 compiled, and point shows how far the byte compiler was able to read.
2096 If the error was due to invalid Lisp syntax, point shows exactly
2097 where the invalid syntax was _detected_. The cause of the error is not
2098 necessarily near by! Use the techniques in the previous section to find
2101 If the error was detected while compiling a form that had been read
2102 successfully, then point is located at the end of the form. In this
2103 case, this technique can't localize the error precisely, but can still
2104 show you which function to check.
2107 File: lispref.info, Node: Edebug, Prev: Compilation Errors, Up: Top
2112 Edebug is a source-level debugger for XEmacs Lisp programs that
2113 provides the following features:
2115 * Step through evaluation, stopping before and after each expression.
2117 * Set conditional or unconditional breakpoints, install embedded
2118 breakpoints, or a global break event.
2120 * Trace slow or fast stopping briefly at each stop point, or each
2123 * Display expression results and evaluate expressions as if outside
2124 of Edebug. Interface with the custom printing package for
2125 printing circular structures.
2127 * Automatically reevaluate a list of expressions and display their
2128 results each time Edebug updates the display.
2130 * Output trace info on function enter and exit.
2132 * Errors stop before the source causing the error.
2134 * Display backtrace without Edebug calls.
2136 * Allow specification of argument evaluation for macros and defining
2139 * Provide rudimentary coverage testing and display of frequency
2143 The first three sections should tell you enough about Edebug to
2144 enable you to use it.
2148 * Using Edebug:: Introduction to use of Edebug.
2149 * Instrumenting:: You must first instrument code.
2150 * Edebug Execution Modes:: Execution modes, stopping more or less often.
2151 * Jumping:: Commands to jump to a specified place.
2152 * Edebug Misc:: Miscellaneous commands.
2153 * Breakpoints:: Setting breakpoints to make the program stop.
2154 * Trapping Errors:: trapping errors with Edebug.
2155 * Edebug Views:: Views inside and outside of Edebug.
2156 * Edebug Eval:: Evaluating expressions within Edebug.
2157 * Eval List:: Automatic expression evaluation.
2158 * Reading in Edebug:: Customization of reading.
2159 * Printing in Edebug:: Customization of printing.
2160 * Tracing:: How to produce tracing output.
2161 * Coverage Testing:: How to test evaluation coverage.
2162 * The Outside Context:: Data that Edebug saves and restores.
2163 * Instrumenting Macro Calls:: Specifying how to handle macro calls.
2164 * Edebug Options:: Option variables for customizing Edebug.
2167 File: lispref.info, Node: Using Edebug, Next: Instrumenting, Up: Edebug
2172 To debug an XEmacs Lisp program with Edebug, you must first
2173 "instrument" the Lisp code that you want to debug. If you want to just
2174 try it now, load `edebug.el', move point into a definition and do `C-u
2175 C-M-x' (`eval-defun' with a prefix argument). See *Note
2176 Instrumenting:: for alternative ways to instrument code.
2178 Once a function is instrumented, any call to the function activates
2179 Edebug. Activating Edebug may stop execution and let you step through
2180 the function, or it may update the display and continue execution while
2181 checking for debugging commands, depending on the selected Edebug
2182 execution mode. The initial execution mode is `step', by default,
2183 which does stop execution. *Note Edebug Execution Modes::.
2185 Within Edebug, you normally view an XEmacs buffer showing the source
2186 of the Lisp function you are debugging. This is referred to as the
2187 "source code buffer"--but note that it is not always the same buffer
2188 depending on which function is currently being executed.
2190 An arrow at the left margin indicates the line where the function is
2191 executing. Point initially shows where within the line the function is
2192 executing, but you can move point yourself.
2194 If you instrument the definition of `fac' (shown below) and then
2195 execute `(fac 3)', here is what you normally see. Point is at the
2196 open-parenthesis before `if'.
2203 The places within a function where Edebug can stop execution are
2204 called "stop points". These occur both before and after each
2205 subexpression that is a list, and also after each variable reference.
2206 Here we show with periods the stop points found in the function `fac':
2210 .(* n. .(fac (1- n.).).).
2213 While the source code buffer is selected, the special commands of
2214 Edebug are available in it, in addition to the commands of XEmacs Lisp
2215 mode. (The buffer is temporarily made read-only, however.) For
2216 example, you can type the Edebug command <SPC> to execute until the
2217 next stop point. If you type <SPC> once after entry to `fac', here is
2218 the display you will see:
2225 When Edebug stops execution after an expression, it displays the
2226 expression's value in the echo area.
2228 Other frequently used commands are `b' to set a breakpoint at a stop
2229 point, `g' to execute until a breakpoint is reached, and `q' to exit to
2230 the top-level command loop. Type `?' to display a list of all Edebug
2234 File: lispref.info, Node: Instrumenting, Next: Edebug Execution Modes, Prev: Using Edebug, Up: Edebug
2236 22.4.2 Instrumenting for Edebug
2237 -------------------------------
2239 In order to use Edebug to debug Lisp code, you must first "instrument"
2240 the code. Instrumenting a form inserts additional code into it which
2241 invokes Edebug at the proper places. Furthermore, if Edebug detects a
2242 syntax error while instrumenting, point is left at the erroneous code
2243 and an `invalid-read-syntax' error is signaled.
2245 Once you have loaded Edebug, the command `C-M-x' (`eval-defun') is
2246 redefined so that when invoked with a prefix argument on a definition,
2247 it instruments the definition before evaluating it. (The source code
2248 itself is not modified.) If the variable `edebug-all-defs' is
2249 non-`nil', that inverts the meaning of the prefix argument: then
2250 `C-M-x' instruments the definition _unless_ it has a prefix argument.
2251 The default value of `edebug-all-defs' is `nil'. The command `M-x
2252 edebug-all-defs' toggles the value of the variable `edebug-all-defs'.
2254 If `edebug-all-defs' is non-`nil', then the commands `eval-region',
2255 `eval-current-buffer', and `eval-buffer' also instrument any
2256 definitions they evaluate. Similarly, `edebug-all-forms' controls
2257 whether `eval-region' should instrument _any_ form, even non-defining
2258 forms. This doesn't apply to loading or evaluations in the minibuffer.
2259 The command `M-x edebug-all-forms' toggles this option.
2261 Another command, `M-x edebug-eval-top-level-form', is available to
2262 instrument any top-level form regardless of the value of
2263 `edebug-all-defs' or `edebug-all-forms'.
2265 Just before Edebug instruments any code, it calls any functions in
2266 the variable `edebug-setup-hook' and resets its value to `nil'. You
2267 could use this to load up Edebug specifications associated with a
2268 package you are using but only when you also use Edebug. For example,
2269 `my-specs.el' may be loaded automatically when you use `my-package'
2270 with Edebug by including the following code in `my-package.el'.
2272 (add-hook 'edebug-setup-hook
2273 (function (lambda () (require 'my-specs))))
2275 While Edebug is active, the command `I' (`edebug-instrument-callee')
2276 instruments the definition of the function or macro called by the list
2277 form after point, if is not already instrumented. If the location of
2278 the definition is not known to Edebug, this command cannot be used.
2279 After loading Edebug, `eval-region' records the position of every
2280 definition it evaluates, even if not instrumenting it. Also see the
2281 command `i' (*Note Jumping::) which steps into the callee.
2283 Edebug knows how to instrument all the standard special forms, an
2284 interactive form with an expression argument, anonymous lambda
2285 expressions, and other defining forms. (Specifications for macros
2286 defined by `cl.el' (version 2.03) are provided in `cl-specs.el'.)
2287 Edebug cannot know what a user-defined macro will do with the arguments
2288 of a macro call so you must tell it. See *Note Instrumenting Macro
2289 Calls:: for the details.
2291 Note that a couple ways remain to evaluate expressions without
2292 instrumenting them. Loading a file via the `load' subroutine does not
2293 instrument expressions for Edebug. Evaluations in the minibuffer via
2294 `eval-expression' (`M-ESC') are not instrumented.
2296 To remove instrumentation from a definition, simply reevaluate it
2297 with one of the non-instrumenting commands, or reload the file.
2299 See *Note Edebug Eval:: for other evaluation functions available
2303 File: lispref.info, Node: Edebug Execution Modes, Next: Jumping, Prev: Instrumenting, Up: Edebug
2305 22.4.3 Edebug Execution Modes
2306 -----------------------------
2308 Edebug supports several execution modes for running the program you are
2309 debugging. We call these alternatives "Edebug execution modes"; do not
2310 confuse them with major or minor modes. The current Edebug execution
2311 mode determines how Edebug displays the progress of the evaluation,
2312 whether it stops at each stop point, or continues to the next
2313 breakpoint, for example.
2315 Normally, you specify the Edebug execution mode by typing a command
2316 to continue the program in a certain mode. Here is a table of these
2317 commands. All except for `S' resume execution of the program, at least
2318 for a certain distance.
2321 Stop: don't execute any more of the program for now, just wait for
2322 more Edebug commands (`edebug-stop').
2325 Step: stop at the next stop point encountered (`edebug-step-mode').
2328 Next: stop at the next stop point encountered after an expression
2329 (`edebug-next-mode'). Also see `edebug-forward-sexp' in *Note
2333 Trace: pause one second at each Edebug stop point
2334 (`edebug-trace-mode').
2337 Rapid trace: update at each stop point, but don't actually pause
2338 (`edebug-Trace-fast-mode').
2341 Go: run until the next breakpoint (`edebug-go-mode'). *Note
2345 Continue: pause for one second at each breakpoint, but don't stop
2346 (`edebug-continue-mode').
2349 Rapid continue: update at each breakpoint, but don't actually pause
2350 (`edebug-Continue-fast-mode').
2353 Go non-stop: ignore breakpoints (`edebug-Go-nonstop-mode'). You
2354 can still stop the program by hitting any key.
2356 In general, the execution modes earlier in the above list run the
2357 program more slowly or stop sooner.
2359 When you enter a new Edebug level, the initial execution mode comes
2360 from the value of the variable `edebug-initial-mode'. By default, this
2361 specifies `step' mode. Note that you may reenter the same Edebug level
2362 several times if, for example, an instrumented function is called
2363 several times from one command.
2365 While executing or tracing, you can interrupt the execution by typing
2366 any Edebug command. Edebug stops the program at the next stop point and
2367 then executes the command that you typed. For example, typing `t'
2368 during execution switches to trace mode at the next stop point. You can
2369 use `S' to stop execution without doing anything else.
2371 If your function happens to read input, a character you hit
2372 intending to interrupt execution may be read by the function instead.
2373 You can avoid such unintended results by paying attention to when your
2374 program wants input.
2376 Keyboard macros containing Edebug commands do not work; when you exit
2377 from Edebug, to resume the program, whether you are defining or
2378 executing a keyboard macro is forgotten. Also, defining or executing a
2379 keyboard macro outside of Edebug does not affect the command loop inside
2380 Edebug. This is usually an advantage. But see
2381 `edebug-continue-kbd-macro'.
2384 File: lispref.info, Node: Jumping, Next: Edebug Misc, Prev: Edebug Execution Modes, Up: Edebug
2389 Commands described here let you jump to a specified location. All,
2390 except `i', use temporary breakpoints to establish the stop point and
2391 then switch to `go' mode. Any other breakpoint reached before the
2392 intended stop point will also stop execution. See *Note Breakpoints::
2393 for the details on breakpoints.
2396 Run the program forward over one expression
2397 (`edebug-forward-sexp'). More precisely, set a temporary
2398 breakpoint at the position that `C-M-f' would reach, then execute
2399 in `go' mode so that the program will stop at breakpoints.
2401 With a prefix argument N, the temporary breakpoint is placed N
2402 sexps beyond point. If the containing list ends before N more
2403 elements, then the place to stop is after the containing
2406 Be careful that the position `C-M-f' finds is a place that the
2407 program will really get to; this may not be true in a `cond', for
2410 This command does `forward-sexp' starting at point rather than the
2411 stop point. If you want to execute one expression from the
2412 current stop point, type `w' first, to move point there.
2415 Continue "out of" an expression (`edebug-step-out'). It places a
2416 temporary breakpoint at the end of the sexp containing point.
2418 If the containing sexp is a function definition itself, it
2419 continues until just before the last sexp in the definition. If
2420 that is where you are now, it returns from the function and then
2421 stops. In other words, this command does not exit the currently
2422 executing function unless you are positioned after the last sexp.
2425 Step into the function or macro after point after first ensuring
2426 that it is instrumented. It does this by calling
2427 `edebug-on-entry' and then switching to `go' mode.
2429 Although the automatic instrumentation is convenient, it is not
2430 later automatically uninstrumented.
2433 Proceed to the stop point near where point is using a temporary
2434 breakpoint (`edebug-goto-here').
2437 All the commands in this section may fail to work as expected in case
2438 of nonlocal exit, because a nonlocal exit can bypass the temporary
2439 breakpoint where you expected the program to stop.
2442 File: lispref.info, Node: Edebug Misc, Next: Breakpoints, Prev: Jumping, Up: Edebug
2444 22.4.5 Miscellaneous
2445 --------------------
2447 Some miscellaneous commands are described here.
2450 Display the help message for Edebug (`edebug-help').
2453 Abort one level back to the previous command level
2454 (`abort-recursive-edit').
2457 Return to the top level editor command loop (`top-level'). This
2458 exits all recursive editing levels, including all levels of Edebug
2459 activity. However, instrumented code protected with
2460 `unwind-protect' or `condition-case' forms may resume debugging.
2463 Like `q' but don't stop even for protected code
2464 (`top-level-nonstop').
2467 Redisplay the most recently known expression result in the echo
2468 area (`edebug-previous-result').
2471 Display a backtrace, excluding Edebug's own functions for clarity
2472 (`edebug-backtrace').
2474 You cannot use debugger commands in the backtrace buffer in Edebug
2475 as you would in the standard debugger.
2477 The backtrace buffer is killed automatically when you continue
2480 From the Edebug recursive edit, you may invoke commands that activate
2481 Edebug again recursively. Any time Edebug is active, you can quit to
2482 the top level with `q' or abort one recursive edit level with `C-]'.
2483 You can display a backtrace of all the pending evaluations with `d'.
2486 File: lispref.info, Node: Breakpoints, Next: Trapping Errors, Prev: Edebug Misc, Up: Edebug
2491 There are three more ways to stop execution once it has started:
2492 breakpoints, the global break condition, and embedded breakpoints.
2494 While using Edebug, you can specify "breakpoints" in the program you
2495 are testing: points where execution should stop. You can set a
2496 breakpoint at any stop point, as defined in *Note Using Edebug::. For
2497 setting and unsetting breakpoints, the stop point that is affected is
2498 the first one at or after point in the source code buffer. Here are the
2499 Edebug commands for breakpoints:
2502 Set a breakpoint at the stop point at or after point
2503 (`edebug-set-breakpoint'). If you use a prefix argument, the
2504 breakpoint is temporary (it turns off the first time it stops the
2508 Unset the breakpoint (if any) at the stop point at or after the
2509 current point (`edebug-unset-breakpoint').
2512 Set a conditional breakpoint which stops the program only if
2513 CONDITION evaluates to a non-`nil' value
2514 (`edebug-set-conditional-breakpoint'). If you use a prefix
2515 argument, the breakpoint is temporary (it turns off the first time
2516 it stops the program).
2519 Move point to the next breakpoint in the definition
2520 (`edebug-next-breakpoint').
2522 While in Edebug, you can set a breakpoint with `b' and unset one
2523 with `u'. First you must move point to a position at or before the
2524 desired Edebug stop point, then hit the key to change the breakpoint.
2525 Unsetting a breakpoint that has not been set does nothing.
2527 Reevaluating or reinstrumenting a definition clears all its
2530 A "conditional breakpoint" tests a condition each time the program
2531 gets there. To set a conditional breakpoint, use `x', and specify the
2532 condition expression in the minibuffer. Setting a conditional
2533 breakpoint at a stop point that already has a conditional breakpoint
2534 puts the current condition expression in the minibuffer so you can edit
2537 You can make both conditional and unconditional breakpoints
2538 "temporary" by using a prefix arg to the command to set the breakpoint.
2539 After breaking at a temporary breakpoint, it is automatically cleared.
2541 Edebug always stops or pauses at a breakpoint except when the Edebug
2542 mode is `Go-nonstop'. In that mode, it ignores breakpoints entirely.
2544 To find out where your breakpoints are, use `B', which moves point
2545 to the next breakpoint in the definition following point, or to the
2546 first breakpoint if there are no following breakpoints. This command
2547 does not continue execution--it just moves point in the buffer.
2551 * Global Break Condition:: Breaking on an event.
2552 * Embedded Breakpoints:: Embedding breakpoints in code.
2555 File: lispref.info, Node: Global Break Condition, Next: Embedded Breakpoints, Up: Breakpoints
2557 22.4.6.1 Global Break Condition
2558 ...............................
2560 In contrast to breaking when execution reaches specified locations, you
2561 can also cause a break when a certain event occurs. The "global break
2562 condition" is a condition that is repeatedly evaluated at every stop
2563 point. If it evaluates to a non-`nil' value, then execution is stopped
2564 or paused depending on the execution mode, just like a breakpoint. Any
2565 errors that might occur as a result of evaluating the condition are
2566 ignored, as if the result were `nil'.
2568 You can set or edit the condition expression, stored in
2569 `edebug-global-break-condition', using `X'
2570 (`edebug-set-global-break-condition').
2572 Using the global break condition is perhaps the fastest way to find
2573 where in your code some event occurs, but since it is rather expensive
2574 you should reset the condition to `nil' when not in use.
2577 File: lispref.info, Node: Embedded Breakpoints, Prev: Global Break Condition, Up: Breakpoints
2579 22.4.6.2 Embedded Breakpoints
2580 .............................
2582 Since all breakpoints in a definition are cleared each time you
2583 reinstrument it, you might rather create an "embedded breakpoint" which
2584 is simply a call to the function `edebug'. You can, of course, make
2585 such a call conditional. For example, in the `fac' function, insert
2586 the first line as shown below to stop when the argument reaches zero:
2589 (if (= n 0) (edebug))
2594 When the `fac' definition is instrumented and the function is
2595 called, Edebug will stop before the call to `edebug'. Depending on the
2596 execution mode, Edebug will stop or pause.
2598 However, if no instrumented code is being executed, calling `edebug'
2599 will instead invoke `debug'. Calling `debug' will always invoke the
2600 standard backtrace debugger.
2603 File: lispref.info, Node: Trapping Errors, Next: Edebug Views, Prev: Breakpoints, Up: Edebug
2605 22.4.7 Trapping Errors
2606 ----------------------
2608 An error may be signaled by subroutines or XEmacs Lisp code. If a
2609 signal is not handled by a `condition-case', this indicates an
2610 unrecognized situation has occurred. If Edebug is not active when an
2611 unhandled error is signaled, `debug' is run normally (if
2612 `debug-on-error' is non-`nil'). But while Edebug is active,
2613 `debug-on-error' and `debug-on-quit' are bound to `edebug-on-error' and
2614 `edebug-on-quit', which are both `t' by default. Actually, if
2615 `debug-on-error' already has a non-`nil' value, that value is still
2618 It is best to change the values of `edebug-on-error' or
2619 `edebug-on-quit' when Edebug is not active since their values won't be
2620 used until the next time Edebug is invoked at a deeper command level.
2621 If you only change `debug-on-error' or `debug-on-quit' while Edebug is
2622 active, these changes will be forgotten when Edebug becomes inactive.
2623 Furthermore, during Edebug's recursive edit, these variables are bound
2624 to the values they had outside of Edebug.
2626 Edebug shows you the last stop point that it knew about before the
2627 error was signaled. This may be the location of a call to a function
2628 which was not instrumented, within which the error actually occurred.
2629 For an unbound variable error, the last known stop point might be quite
2630 distant from the offending variable. If the cause of the error is not
2631 obvious at first, note that you can also get a full backtrace inside of
2632 Edebug (see *Note Edebug Misc::).
2634 Edebug can also trap signals even if they are handled. If
2635 `debug-on-error' is a list of signal names, Edebug will stop when any
2636 of these errors are signaled. Edebug shows you the last known stop
2637 point just as for unhandled errors. After you continue execution, the
2638 error is signaled again (but without being caught by Edebug). Edebug
2639 can only trap errors that are handled if they are signaled in Lisp code
2640 (not subroutines) since it does so by temporarily replacing the
2644 File: lispref.info, Node: Edebug Views, Next: Edebug Eval, Prev: Trapping Errors, Up: Edebug
2649 The following Edebug commands let you view aspects of the buffer and
2650 window status that obtained before entry to Edebug.
2653 View the outside window configuration (`edebug-view-outside').
2656 Temporarily display the outside current buffer with point at its
2657 outside position (`edebug-bounce-point'). If prefix arg is
2658 supplied, sit for that many seconds instead.
2661 Move point back to the current stop point (`edebug-where') in the
2662 source code buffer. Also, if you use this command in another
2663 window displaying the same buffer, this window will be used
2664 instead to display the buffer in the future.
2667 Toggle the `edebug-save-windows' variable which indicates whether
2668 the outside window configuration is saved and restored
2669 (`edebug-toggle-save-windows'). Also, each time it is toggled on,
2670 make the outside window configuration the same as the current
2671 window configuration.
2673 With a prefix argument, `edebug-toggle-save-windows' only toggles
2674 saving and restoring of the selected window. To specify a window
2675 that is not displaying the source code buffer, you must use
2676 `C-xXW' from the global keymap.
2679 You can view the outside window configuration with `v' or just
2680 bounce to the current point in the current buffer with `p', even if it
2681 is not normally displayed. After moving point, you may wish to pop
2682 back to the stop point with `w' from a source code buffer.
2684 By using `W' twice, Edebug again saves and restores the outside
2685 window configuration, but to the current configuration. This is a
2686 convenient way to, for example, add another buffer to be displayed
2687 whenever Edebug is active. However, the automatic redisplay of
2688 `*edebug*' and `*edebug-trace*' may conflict with the buffers you wish
2689 to see unless you have enough windows open.
2692 File: lispref.info, Node: Edebug Eval, Next: Eval List, Prev: Edebug Views, Up: Edebug
2697 While within Edebug, you can evaluate expressions "as if" Edebug were
2698 not running. Edebug tries to be invisible to the expression's
2699 evaluation and printing. Evaluation of expressions that cause side
2700 effects will work as expected except for things that Edebug explicitly
2701 saves and restores. See *Note The Outside Context:: for details on this
2702 process. Also see *Note Reading in Edebug:: and *Note Printing in
2703 Edebug:: for topics related to evaluation.
2706 Evaluate expression EXP in the context outside of Edebug
2707 (`edebug-eval-expression'). In other words, Edebug tries to avoid
2708 altering the effect of EXP.
2711 Evaluate expression EXP in the context of Edebug itself.
2714 Evaluate the expression before point, in the context outside of
2715 Edebug (`edebug-eval-last-sexp').
2717 Edebug supports evaluation of expressions containing references to
2718 lexically bound symbols created by the following constructs in `cl.el'
2719 (version 2.03 or later): `lexical-let', `macrolet', and
2723 File: lispref.info, Node: Eval List, Next: Reading in Edebug, Prev: Edebug Eval, Up: Edebug
2725 22.4.10 Evaluation List Buffer
2726 ------------------------------
2728 You can use the "evaluation list buffer", called `*edebug*', to
2729 evaluate expressions interactively. You can also set up the
2730 "evaluation list" of expressions to be evaluated automatically each
2731 time Edebug updates the display.
2734 Switch to the evaluation list buffer `*edebug*'
2735 (`edebug-visit-eval-list').
2737 In the `*edebug*' buffer you can use the commands of Lisp
2738 Interaction as well as these special commands:
2741 Evaluate the expression before point, in the outside context, and
2742 insert the value in the buffer (`edebug-eval-print-last-sexp').
2745 Evaluate the expression before point, in the context outside of
2746 Edebug (`edebug-eval-last-sexp').
2749 Build a new evaluation list from the first expression of each
2750 group, reevaluate and redisplay (`edebug-update-eval-list').
2751 Groups are separated by comment lines.
2754 Delete the evaluation list group that point is in
2755 (`edebug-delete-eval-item').
2758 Switch back to the source code buffer at the current stop point
2761 You can evaluate expressions in the evaluation list window with
2762 `LFD' or `C-x C-e', just as you would in `*scratch*'; but they are
2763 evaluated in the context outside of Edebug.
2765 The expressions you enter interactively (and their results) are lost
2766 when you continue execution unless you add them to the evaluation list
2767 with `C-c C-u'. This command builds a new list from the first
2768 expression of each "evaluation list group". Groups are separated by
2769 comment lines. Be careful not to add expressions that execute
2770 instrumented code otherwise an infinite loop will result.
2772 When the evaluation list is redisplayed, each expression is displayed
2773 followed by the result of evaluating it, and a comment line. If an
2774 error occurs during an evaluation, the error message is displayed in a
2775 string as if it were the result. Therefore expressions that, for
2776 example, use variables not currently valid do not interrupt your
2779 Here is an example of what the evaluation list window looks like
2780 after several expressions have been added to it:
2784 ;---------------------------------------------------------------
2786 #<window 16 on *scratch*>
2787 ;---------------------------------------------------------------
2790 ;---------------------------------------------------------------
2792 "Symbol's value as variable is void: bad-var"
2793 ;---------------------------------------------------------------
2796 ;---------------------------------------------------------------
2799 ;---------------------------------------------------------------
2801 To delete a group, move point into it and type `C-c C-d', or simply
2802 delete the text for the group and update the evaluation list with `C-c
2803 C-u'. When you add a new group, be sure it is separated from its
2804 neighbors by a comment line.
2806 After selecting `*edebug*', you can return to the source code buffer
2807 with `C-c C-w'. The `*edebug*' buffer is killed when you continue
2808 execution, and recreated next time it is needed.
2811 File: lispref.info, Node: Reading in Edebug, Next: Printing in Edebug, Prev: Eval List, Up: Edebug
2813 22.4.11 Reading in Edebug
2814 -------------------------
2816 To instrument a form, Edebug first reads the whole form. Edebug
2817 replaces the standard Lisp Reader with its own reader that remembers the
2818 positions of expressions. This reader is used by the Edebug
2819 replacements for `eval-region', `eval-defun', `eval-buffer', and
2820 `eval-current-buffer'.
2822 Another package, `cl-read.el', replaces the standard reader with one
2823 that understands Common Lisp reader macros. If you use that package,
2824 Edebug will automatically load `edebug-cl-read.el' to provide
2825 corresponding reader macros that remember positions of expressions. If
2826 you define new reader macros, you will have to define similar reader
2830 File: lispref.info, Node: Printing in Edebug, Next: Tracing, Prev: Reading in Edebug, Up: Edebug
2832 22.4.12 Printing in Edebug
2833 --------------------------
2835 If the result of an expression in your program contains a circular
2836 reference, you may get an error when Edebug attempts to print it. You
2837 can set `print-length' to a non-zero value to limit the print length of
2838 lists (the number of cdrs), and in Emacs 19, set `print-level' to a
2839 non-zero value to limit the print depth of lists. But you can print
2840 such circular structures and structures that share elements more
2841 informatively by using the `cust-print' package.
2843 To load `cust-print' and activate custom printing only for Edebug,
2844 simply use the command `M-x edebug-install-custom-print'. To restore
2845 the standard print functions, use `M-x edebug-uninstall-custom-print'.
2846 You can also activate custom printing for printing in any Lisp code;
2847 see the package for details.
2849 Here is an example of code that creates a circular structure:
2852 (edebug-install-custom-print)
2856 Edebug will print the result of the `setcar' as `Result: #1=(#1#
2857 y)'. The `#1=' notation names the structure that follows it, and the
2858 `#1#' notation references the previously named structure. This
2859 notation is used for any shared elements of lists or vectors.
2861 Independent of whether `cust-print' is active, while printing
2862 results Edebug binds `print-length', `print-level', and `print-circle'
2863 to `edebug-print-length' (`50'), `edebug-print-level' (`50'), and
2864 `edebug-print-circle' (`t') respectively, if these values are
2865 non-`nil'. Also, `print-readably' is bound to `nil' since some objects
2866 simply cannot be printed readably.
2869 File: lispref.info, Node: Tracing, Next: Coverage Testing, Prev: Printing in Edebug, Up: Edebug
2874 In addition to automatic stepping through source code, which is also
2875 called _tracing_ (see *Note Edebug Execution Modes::), Edebug can
2876 produce a traditional trace listing of execution in a separate buffer,
2879 If the variable `edebug-trace' is non-`nil', each function entry and
2880 exit adds lines to the trace buffer. On function entry, Edebug prints
2881 `::::{' followed by the function name and argument values. On function
2882 exit, Edebug prints `::::}' followed by the function name and result of
2883 the function. The number of `:'s is computed from the recursion depth.
2884 The balanced braces in the trace buffer can be used to find the
2885 matching beginning or end of function calls. These displays may be
2886 customized by replacing the functions `edebug-print-trace-before' and
2887 `edebug-print-trace-after', which take an arbitrary message string to
2890 The macro `edebug-tracing' provides tracing similar to function
2891 enter and exit tracing, but for arbitrary expressions. This macro
2892 should be explicitly inserted by you around expressions you wish to
2893 trace the execution of. The first argument is a message string
2894 (evaluated), and the rest are expressions to evaluate. The result of
2895 the last expression is returned.
2897 Finally, you can insert arbitrary strings into the trace buffer with
2898 explicit calls to `edebug-trace'. The arguments of this function are
2899 the same as for `message', but a newline is always inserted after each
2900 string printed in this way.
2902 `edebug-tracing' and `edebug-trace' insert lines in the trace buffer
2903 even if Edebug is not active. Every time the trace buffer is added to,
2904 the window is scrolled to show the last lines inserted. (There may be
2905 some display problems if you use tracing along with the evaluation
2909 File: lispref.info, Node: Coverage Testing, Next: The Outside Context, Prev: Tracing, Up: Edebug
2911 22.4.14 Coverage Testing
2912 ------------------------
2914 Edebug provides a rudimentary coverage tester and display of execution
2915 frequency. Frequency counts are always accumulated, both before and
2916 after evaluation of each instrumented expression, even if the execution
2917 mode is `Go-nonstop'. Coverage testing is only done if the option
2918 `edebug-test-coverage' is non-`nil' because this is relatively
2919 expensive. Both data sets are displayed by `M-x
2920 edebug-display-freq-count'.
2922 -- Command: edebug-display-freq-count
2923 Display the frequency count data for each line of the current
2924 definition. The frequency counts are inserted as comment lines
2925 after each line, and you can undo all insertions with one `undo'
2926 command. The counts are inserted starting under the `(' before an
2927 expression or the `)' after an expression, or on the last char of
2928 a symbol. The counts are only displayed when they differ from
2929 previous counts on the same line.
2931 If coverage is being tested, whenever all known results of an
2932 expression are `eq', the char `=' will be appended after the count
2933 for that expression. Note that this is always the case for an
2934 expression only evaluated once.
2936 To clear the frequency count and coverage data for a definition,
2940 For example, after evaluating `(fac 5)' with an embedded breakpoint,
2941 and setting `edebug-test-coverage' to `t', when the breakpoint is
2942 reached, the frequency data is looks like this:
2945 (if (= n 0) (edebug))
2954 The comment lines show that `fac' has been called 6 times. The
2955 first `if' statement has returned 5 times with the same result each
2956 time, and the same is true for the condition on the second `if'. The
2957 recursive call of `fac' has not returned at all.
2960 File: lispref.info, Node: The Outside Context, Next: Instrumenting Macro Calls, Prev: Coverage Testing, Up: Edebug
2962 22.4.15 The Outside Context
2963 ---------------------------
2965 Edebug tries to be transparent to the program you are debugging. In
2966 addition, most evaluations you do within Edebug (see *Note Edebug
2967 Eval::) occur in the same outside context which is temporarily restored
2968 for the evaluation. But Edebug is not completely successful and this
2969 section explains precisely how it fails. Edebug operation unavoidably
2970 alters some data in XEmacs, and this can interfere with debugging
2971 certain programs. Also notice that Edebug's protection against change
2972 of outside data means that any side effects _intended_ by the user in
2973 the course of debugging will be defeated.
2977 * Checking Whether to Stop:: When Edebug decides what to do.
2978 * Edebug Display Update:: When Edebug updates the display.
2979 * Edebug Recursive Edit:: When Edebug stops execution.
2982 File: lispref.info, Node: Checking Whether to Stop, Next: Edebug Display Update, Up: The Outside Context
2984 22.4.15.1 Checking Whether to Stop
2985 ..................................
2987 Whenever Edebug is entered just to think about whether to take some
2988 action, it needs to save and restore certain data.
2990 * `max-lisp-eval-depth' and `max-specpdl-size' are both incremented
2991 one time to reduce Edebug's impact on the stack. You could,
2992 however, still run out of stack space when using Edebug.
2994 * The state of keyboard macro execution is saved and restored. While
2995 Edebug is active, `executing-macro' is bound to
2996 `edebug-continue-kbd-macro'.
3000 File: lispref.info, Node: Edebug Display Update, Next: Edebug Recursive Edit, Prev: Checking Whether to Stop, Up: The Outside Context
3002 22.4.15.2 Edebug Display Update
3003 ...............................
3005 When Edebug needs to display something (e.g., in trace mode), it saves
3006 the current window configuration from "outside" Edebug. When you exit
3007 Edebug (by continuing the program), it restores the previous window
3010 XEmacs redisplays only when it pauses. Usually, when you continue
3011 execution, the program comes back into Edebug at a breakpoint or after
3012 stepping without pausing or reading input in between. In such cases,
3013 XEmacs never gets a chance to redisplay the "outside" configuration.
3014 What you see is the same window configuration as the last time Edebug
3015 was active, with no interruption.
3017 Entry to Edebug for displaying something also saves and restores the
3018 following data, but some of these are deliberately not restored if an
3019 error or quit signal occurs.
3021 * Which buffer is current, and where point and mark are in the
3022 current buffer are saved and restored.
3024 * The Edebug Display Update, is saved and restored if
3025 `edebug-save-windows' is non-`nil'. It is not restored on error
3026 or quit, but the outside selected window _is_ reselected even on
3027 error or quit in case a `save-excursion' is active. If the value
3028 of `edebug-save-windows' is a list, only the listed windows are
3031 The window start and horizontal scrolling of the source code
3032 buffer are not restored, however, so that the display remains
3035 * The value of point in each displayed buffer is saved and restored
3036 if `edebug-save-displayed-buffer-points' is non-`nil'.
3038 * The variables `overlay-arrow-position' and `overlay-arrow-string'
3039 are saved and restored. So you can safely invoke Edebug from the
3040 recursive edit elsewhere in the same buffer.
3042 * `cursor-in-echo-area' is locally bound to `nil' so that the cursor
3043 shows up in the window.
3047 File: lispref.info, Node: Edebug Recursive Edit, Prev: Edebug Display Update, Up: The Outside Context
3049 22.4.15.3 Edebug Recursive Edit
3050 ...............................
3052 When Edebug is entered and actually reads commands from the user, it
3053 saves (and later restores) these additional data:
3055 * The current match data, for whichever buffer was current.
3057 * `last-command', `this-command', `last-command-char',
3058 `last-input-char', `last-input-event', `last-command-event',
3059 `last-event-frame', `last-nonmenu-event', and `track-mouse' .
3060 Commands used within Edebug do not affect these variables outside
3063 The key sequence returned by `this-command-keys' is changed by
3064 executing commands within Edebug and there is no way to reset the
3065 key sequence from Lisp.
3067 For Emacs 18, Edebug cannot save and restore the value of
3068 `unread-command-char'. Entering Edebug while this variable has a
3069 nontrivial value can interfere with execution of the program you
3072 * Complex commands executed while in Edebug are added to the variable
3073 `command-history'. In rare cases this can alter execution.
3075 * Within Edebug, the recursion depth appears one deeper than the
3076 recursion depth outside Edebug. This is not true of the
3077 automatically updated evaluation list window.
3079 * `standard-output' and `standard-input' are bound to `nil' by the
3080 `recursive-edit', but Edebug temporarily restores them during
3083 * The state of keyboard macro definition is saved and restored.
3084 While Edebug is active, `defining-kbd-macro' is bound to
3085 `edebug-continue-kbd-macro'.
3089 File: lispref.info, Node: Instrumenting Macro Calls, Next: Edebug Options, Prev: The Outside Context, Up: Edebug
3091 22.4.16 Instrumenting Macro Calls
3092 ---------------------------------
3094 When Edebug instruments an expression that calls a Lisp macro, it needs
3095 additional advice to do the job properly. This is because there is no
3096 way to tell which subexpressions of the macro call may be evaluated.
3097 (Evaluation may occur explicitly in the macro body, or when the
3098 resulting expansion is evaluated, or any time later.) You must explain
3099 the format of macro call arguments by using `def-edebug-spec' to define
3100 an "Edebug specification" for each macro.
3102 -- Macro: def-edebug-spec macro specification
3103 Specify which expressions of a call to macro MACRO are forms to be
3104 evaluated. For simple macros, the SPECIFICATION often looks very
3105 similar to the formal argument list of the macro definition, but
3106 specifications are much more general than macro arguments.
3108 The MACRO argument may actually be any symbol, not just a macro
3111 Unless you are using Emacs 19 or XEmacs, this macro is only defined
3112 in Edebug, so you may want to use the following which is
3113 equivalent: `(put 'MACRO 'edebug-form-spec 'SPECIFICATION)'
3115 Here is a simple example that defines the specification for the
3116 `for' macro described in the XEmacs Lisp Reference Manual, followed by
3117 an alternative, equivalent specification.
3119 (def-edebug-spec for
3120 (symbolp "from" form "to" form "do" &rest form))
3122 (def-edebug-spec for
3123 (symbolp ['from form] ['to form] ['do body]))
3125 Here is a table of the possibilities for SPECIFICATION and how each
3126 directs processing of arguments.
3129 All arguments are instrumented for evaluation.
3132 None of the arguments is instrumented.
3135 The symbol must have an Edebug specification which is used instead.
3136 This indirection is repeated until another kind of specification is
3137 found. This allows you to inherit the specification for another
3141 The elements of the list describe the types of the arguments of a
3142 calling form. The possible elements of a specification list are
3143 described in the following sections.
3147 * Specification List:: How to specify complex patterns of evaluation.
3148 * Backtracking:: What Edebug does when matching fails.
3149 * Debugging Backquote:: Debugging Backquote
3150 * Specification Examples:: To help understand specifications.
3153 File: lispref.info, Node: Specification List, Next: Backtracking, Up: Instrumenting Macro Calls
3155 22.4.16.1 Specification List
3156 ............................
3158 A "specification list" is required for an Edebug specification if some
3159 arguments of a macro call are evaluated while others are not. Some
3160 elements in a specification list match one or more arguments, but others
3161 modify the processing of all following elements. The latter, called
3162 "keyword specifications", are symbols beginning with ``&'' (e.g.
3165 A specification list may contain sublists which match arguments that
3166 are themselves lists, or it may contain vectors used for grouping.
3167 Sublists and groups thus subdivide the specification list into a
3168 hierarchy of levels. Keyword specifications only apply to the
3169 remainder of the sublist or group they are contained in and there is an
3170 implicit grouping around a keyword specification and all following
3171 elements in the sublist or group.
3173 If a specification list fails at some level, then backtracking may
3174 be invoked to find some alternative at a higher level, or if no
3175 alternatives remain, an error will be signaled. See *Note
3176 Backtracking:: for more details.
3178 Edebug specifications provide at least the power of regular
3179 expression matching. Some context-free constructs are also supported:
3180 the matching of sublists with balanced parentheses, recursive
3181 processing of forms, and recursion via indirect specifications.
3183 Each element of a specification list may be one of the following,
3184 with the corresponding type of argument:
3187 A single unevaluated expression.
3190 A single evaluated expression, which is instrumented.
3193 A place as in the Common Lisp `setf' place argument. It will be
3194 instrumented just like a form, but the macro is expected to strip
3195 the instrumentation. Two functions, `edebug-unwrap' and
3196 `edebug-unwrap*', are provided to strip the instrumentation one
3197 level or recursively at all levels.
3200 Short for `&rest form'. See `&rest' below.
3203 A function form: either a quoted function symbol, a quoted lambda
3204 expression, or a form (that should evaluate to a function symbol
3205 or lambda expression). This is useful when function arguments
3206 might be quoted with `quote' rather than `function' since the body
3207 of a lambda expression will be instrumented either way.
3210 An unquoted anonymous lambda expression.
3213 All following elements in the specification list are optional; as
3214 soon as one does not match, Edebug stops matching at this level.
3216 To make just a few elements optional followed by non-optional
3217 elements, use `[&optional SPECS...]'. To specify that several
3218 elements should all succeed together, use `&optional [SPECS...]'.
3219 See the `defun' example below.
3222 All following elements in the specification list are repeated zero
3223 or more times. All the elements need not match in the last
3224 repetition, however.
3226 To repeat only a few elements, use `[&rest SPECS...]'. To specify
3227 all elements must match on every repetition, use `&rest
3231 Each of the following elements in the specification list is an
3232 alternative, processed left to right until one matches. One of the
3233 alternatives must match otherwise the `&or' specification fails.
3235 Each list element following `&or' is a single alternative even if
3236 it is a keyword specification. (This breaks the implicit grouping
3237 rule.) To group two or more list elements as a single
3238 alternative, enclose them in `[...]'.
3241 Each of the following elements is matched as alternatives as if by
3242 using `&or', but if any of them match, the specification fails.
3243 If none of them match, nothing is matched, but the `¬'
3244 specification succeeds.
3247 Indicates that the specification is for a defining form. The
3248 defining form itself is not instrumented (i.e. Edebug does not
3249 stop before and after the defining form), but forms inside it
3250 typically will be instrumented. The `&define' keyword should be
3251 the first element in a list specification.
3253 Additional specifications that may only appear after `&define' are
3254 described here. See the `defun' example below.
3257 The argument, a symbol, is the name of the defining form.
3258 But a defining form need not be named at all, in which case a
3259 unique name will be created for it.
3261 The `name' specification may be used more than once in the
3262 specification and each subsequent use will append the
3263 corresponding symbol argument to the previous name with ``@''
3264 between them. This is useful for generating unique but
3265 meaningful names for definitions such as `defadvice' and
3269 The element following `:name' should be a symbol; it is used
3270 as an additional name component for the definition. This is
3271 useful to add a unique, static component to the name of the
3272 definition. It may be used more than once. No argument is
3276 The argument, a symbol, is the name of an argument of the
3277 defining form. However, lambda list keywords (symbols
3278 starting with ``&'') are not allowed. See `lambda-list' and
3282 This matches the whole argument list of an XEmacs Lisp lambda
3283 expression, which is a list of symbols and the keywords
3284 `&optional' and `&rest'
3287 The argument is the body of code in a definition. This is
3288 like `body', described above, but a definition body must be
3289 instrumented with a different Edebug call that looks up
3290 information associated with the definition. Use `def-body'
3291 for the highest level list of forms within the definition.
3294 The argument is a single, highest-level form in a definition.
3295 This is like `def-body', except use this to match a single
3296 form rather than a list of forms. As a special case,
3297 `def-form' also means that tracing information is not output
3298 when the form is executed. See the `interactive' example
3303 This is successful when there are no more arguments to match at the
3304 current argument list level; otherwise it fails. See sublist
3305 specifications and the backquote example below.
3308 No argument is matched but backtracking through the gate is
3309 disabled while matching the remainder of the specifications at
3310 this level. This is primarily used to generate more specific
3311 syntax error messages. See *Note Backtracking:: for more details.
3312 Also see the `let' example below.
3315 Any other symbol in a specification list may be a predicate or an
3316 indirect specification.
3318 If the symbol has an Edebug specification, this "indirect
3319 specification" should be either a list specification that is used
3320 in place of the symbol, or a function that is called to process the
3321 arguments. The specification may be defined with `def-edebug-spec'
3322 just as for macros. See the `defun' example below.
3324 Otherwise, the symbol should be a predicate. The predicate is
3325 called with the argument and the specification fails if the
3326 predicate fails. The argument is not instrumented.
3328 Predicates that may be used include: `symbolp', `integerp',
3329 `stringp', `vectorp', `atom' (which matches a number, string,
3330 symbol, or vector), `keywordp', and `lambda-list-keywordp'. The
3331 last two, defined in `edebug.el', test whether the argument is a
3332 symbol starting with ``:'' and ``&'' respectively.
3335 Rather than matching a vector argument, a vector treats the
3336 ELEMENTS as a single "group specification".
3339 The argument should be a symbol named STRING. This specification
3340 is equivalent to the quoted symbol, `'SYMBOL', where the name of
3341 SYMBOL is the STRING, but the string form is preferred.
3343 `'SYMBOL or (quote SYMBOL)'
3344 The argument should be the symbol SYMBOL. But use a string
3345 specification instead.
3347 `(vector ELEMENTS...)'
3348 The argument should be a vector whose elements must match the
3349 ELEMENTS in the specification. See the backquote example below.
3352 Any other list is a "sublist specification" and the argument must
3353 be a list whose elements match the specification ELEMENTS.
3355 A sublist specification may be a dotted list and the corresponding
3356 list argument may then be a dotted list. Alternatively, the last
3357 cdr of a dotted list specification may be another sublist
3358 specification (via a grouping or an indirect specification, e.g.
3359 `(spec . [(more specs...)])') whose elements match the non-dotted
3360 list arguments. This is useful in recursive specifications such
3361 as in the backquote example below. Also see the description of a
3362 `nil' specification above for terminating such recursion.
3364 Note that a sublist specification of the form `(specs . nil)'
3365 means the same as `(specs)', and `(specs .
3366 (sublist-elements...))' means the same as `(specs
3367 sublist-elements...)'.
3371 File: lispref.info, Node: Backtracking, Next: Debugging Backquote, Prev: Specification List, Up: Instrumenting Macro Calls
3373 22.4.16.2 Backtracking
3374 ......................
3376 If a specification fails to match at some point, this does not
3377 necessarily mean a syntax error will be signaled; instead,
3378 "backtracking" will take place until all alternatives have been
3379 exhausted. Eventually every element of the argument list must be
3380 matched by some element in the specification, and every required element
3381 in the specification must match some argument.
3383 Backtracking is disabled for the remainder of a sublist or group when
3384 certain conditions occur, described below. Backtracking is reenabled
3385 when a new alternative is established by `&optional', `&rest', or
3386 `&or'. It is also reenabled initially when processing a sublist or
3387 group specification or an indirect specification.
3389 You might want to disable backtracking to commit to some alternative
3390 so that Edebug can provide a more specific syntax error message.
3391 Normally, if no alternative matches, Edebug reports that none matched,
3392 but if one alternative is committed to, Edebug can report how it failed
3395 First, backtracking is disabled while matching any of the form
3396 specifications (i.e. `form', `body', `def-form', and `def-body').
3397 These specifications will match any form so any error must be in the
3398 form itself rather than at a higher level.
3400 Second, backtracking is disabled after successfully matching a quoted
3401 symbol or string specification, since this usually indicates a
3402 recognized construct. If you have a set of alternative constructs that
3403 all begin with the same symbol, you can usually work around this
3404 constraint by factoring the symbol out of the alternatives, e.g.,
3405 `["foo" &or [first case] [second case] ...]'.
3407 Third, backtracking may be explicitly disabled by using the `gate'
3408 specification. This is useful when you know that no higher
3409 alternatives may apply.
3412 File: lispref.info, Node: Debugging Backquote, Next: Specification Examples, Prev: Backtracking, Up: Instrumenting Macro Calls
3414 22.4.16.3 Debugging Backquote
3415 .............................
3417 Backquote (``') is a macro that results in an expression that may or
3418 may not be evaluated. It is often used to simplify the definition of a
3419 macro to return an expression that is evaluated, but Edebug does not
3420 know when this is the case. However, the forms inside unquotes (`,' and
3421 `,@') are evaluated and Edebug instruments them.
3423 Nested backquotes are supported by Edebug, but there is a limit on
3424 the support of quotes inside of backquotes. Quoted forms (with `'')
3425 are not normally evaluated, but if the quoted form appears immediately
3426 within `,' and `,@' forms, Edebug treats this as a backquoted form at
3427 the next higher level (even if there is not a next higher level - this
3428 is difficult to fix).
3430 If the backquoted forms happen to be code intended to be evaluated,
3431 you can have Edebug instrument them by using `edebug-`' instead of the
3432 regular ``'. Unquoted forms can always appear inside `edebug-`'
3433 anywhere a form is normally allowed. But `(, FORM)' may be used in two
3434 other places specially recognized by Edebug: wherever a predicate
3435 specification would match, and at the head of a list form in place of a
3436 function name or lambda expression. The FORM inside a spliced unquote,
3437 `(,@ FORM)', will be wrapped, but the unquote form itself will not be
3438 wrapped since this would interfere with the splicing.
3440 There is one other complication with using `edebug-`'. If the
3441 `edebug-`' call is in a macro and the macro may be called from code
3442 that is also instrumented, and if unquoted forms contain any macro
3443 arguments bound to instrumented forms, then you should modify the
3444 specification for the macro as follows: the specifications for those
3445 arguments must use `def-form' instead of `form'. (This is to
3446 reestablish the Edebugging context for those external forms.)
3448 For example, the `for' macro (*note Problems with Macros: ()Problems
3449 with Macros.) is shown here but with `edebug-`' substituted for regular
3453 (list 'setq var (list '1+ var)))
3455 (defmacro for (var from init to final do &rest body)
3456 (let ((tempvar (make-symbol "max")))
3457 (edebug-` (let (((, var) (, init))
3458 ((, tempvar) (, final)))
3459 (while (<= (, var) (, tempvar))
3463 Here is the corresponding modified Edebug specification and some code
3464 that calls the macro:
3466 (def-edebug-spec for
3467 (symbolp "from" def-form "to" def-form "do" &rest def-form))
3470 (for i from n to (* n (+ n 1)) do
3473 After instrumenting the `for' macro and the macro call, Edebug first
3474 steps to the beginning of the macro call, then into the macro body,
3475 then through each of the unquoted expressions in the backquote showing
3476 the expressions that will be embedded in the backquote form. Then when
3477 the macro expansion is evaluated, Edebug will step through the `let'
3478 form and each time it gets to an unquoted form, it will jump back to an
3479 argument of the macro call to step through that expression. Finally
3480 stepping will continue after the macro call. Even more convoluted
3481 execution paths may result when using anonymous functions.
3483 When the result of an expression is an instrumented expression, it is
3484 difficult to see the expression inside the instrumentation. So you may
3485 want to set the option `edebug-unwrap-results' to a non-`nil' value
3486 while debugging such expressions, but it would slow Edebug down to
3490 File: lispref.info, Node: Specification Examples, Prev: Debugging Backquote, Up: Instrumenting Macro Calls
3492 22.4.16.4 Specification Examples
3493 ................................
3495 Here we provide several examples of Edebug specifications to show many
3496 of its capabilities.
3498 A `let' special form has a sequence of bindings and a body. Each of
3499 the bindings is either a symbol or a sublist with a symbol and optional
3500 value. In the specification below, notice the `gate' inside of the
3501 sublist to prevent backtracking.
3503 (def-edebug-spec let
3505 &or symbolp (gate symbolp &optional form))
3508 Edebug uses the following specifications for `defun' and `defmacro'
3509 and the associated argument list and `interactive' specifications. It
3510 is necessary to handle the expression argument of an interactive form
3511 specially since it is actually evaluated outside of the function body.
3513 (def-edebug-spec defmacro defun) ; Indirect ref to `defun' spec
3514 (def-edebug-spec defun
3515 (&define name lambda-list
3516 [&optional stringp] ; Match the doc string, if present.
3517 [&optional ("interactive" interactive)]
3520 (def-edebug-spec lambda-list
3522 [&optional ["&optional" arg &rest arg]]
3523 &optional ["&rest" arg]
3526 (def-edebug-spec interactive
3527 (&optional &or stringp def-form)) ; Notice: `def-form'
3529 The specification for backquote below illustrates how to match
3530 dotted lists and use `nil' to terminate recursion. It also illustrates
3531 how components of a vector may be matched. (The actual specification
3532 provided by Edebug does not support dotted lists because doing so
3533 causes very deep recursion that could fail.)
3535 (def-edebug-spec ` (backquote-form)) ;; alias just for clarity
3537 (def-edebug-spec backquote-form
3538 (&or ([&or "," ",@"] &or ("quote" backquote-form) form)
3539 (backquote-form . [&or nil backquote-form])
3540 (vector &rest backquote-form)
3544 File: lispref.info, Node: Edebug Options, Prev: Instrumenting Macro Calls, Up: Edebug
3546 22.4.17 Edebug Options
3547 ----------------------
3549 These options affect the behavior of Edebug:
3551 -- User Option: edebug-setup-hook
3552 Functions to call before Edebug is used. Each time it is set to a
3553 new value, Edebug will call those functions once and then
3554 `edebug-setup-hook' is reset to `nil'. You could use this to load
3555 up Edebug specifications associated with a package you are using
3556 but only when you also use Edebug. See *Note Instrumenting::.
3558 -- User Option: edebug-all-defs
3559 If non-`nil', normal evaluation of any defining forms (e.g.
3560 `defun' and `defmacro') will instrument them for Edebug. This
3561 applies to `eval-defun', `eval-region', and `eval-current-buffer'.
3563 Use the command `M-x edebug-all-defs' to toggle the value of this
3564 variable. You may want to make this variable local to each buffer
3565 by calling `(make-local-variable 'edebug-all-defs)' in your
3566 `emacs-lisp-mode-hook'. See *Note Instrumenting::.
3568 -- User Option: edebug-all-forms
3569 If non-`nil', normal evaluation of any forms by `eval-defun',
3570 `eval-region', and `eval-current-buffer' will instrument them for
3573 Use the command `M-x edebug-all-forms' to toggle the value of this
3574 option. See *Note Instrumenting::.
3576 -- User Option: edebug-save-windows
3577 If non-`nil', save and restore window configuration on Edebug
3578 calls. It takes some time to do this, so if your program does not
3579 care what happens to data about windows, you may want to set this
3582 If the value is a list, only the listed windows are saved and
3585 `M-x edebug-toggle-save-windows' may be used to change this
3586 variable. This command is bound to `W' in source code buffers.
3587 See *Note Edebug Display Update::.
3589 -- User Option: edebug-save-displayed-buffer-points
3590 If non-`nil', save and restore point in all displayed buffers.
3591 This is necessary if you are debugging code that changes the point
3592 of a buffer which is displayed in a non-selected window. If
3593 Edebug or the user then selects the window, the buffer's point
3594 will be changed to the window's point.
3596 This is an expensive operation since it visits each window and
3597 therefore each displayed buffer twice for each Edebug activation,
3598 so it is best to avoid it if you can. See *Note Edebug Display
3601 -- User Option: edebug-initial-mode
3602 If this variable is non-`nil', it specifies the initial execution
3603 mode for Edebug when it is first activated. Possible values are
3604 `step', `next', `go', `Go-nonstop', `trace', `Trace-fast',
3605 `continue', and `Continue-fast'.
3607 The default value is `step'. See *Note Edebug Execution Modes::.
3609 -- User Option: edebug-trace
3610 Non-`nil' means display a trace of function entry and exit.
3611 Tracing output is displayed in a buffer named `*edebug-trace*', one
3612 function entry or exit per line, indented by the recursion level.
3614 The default value is `nil'.
3616 Also see `edebug-tracing'. See *Note Tracing::.
3618 -- User Option: edebug-test-coverage
3619 If non-`nil', Edebug tests coverage of all expressions debugged.
3620 This is done by comparing the result of each expression with the
3621 previous result. Coverage is considered OK if two different
3622 results are found. So to sufficiently test the coverage of your
3623 code, try to execute it under conditions that evaluate all
3624 expressions more than once, and produce different results for each
3627 Use `M-x edebug-display-freq-count' to display the frequency count
3628 and coverage information for a definition. See *Note Coverage
3631 -- User Option: edebug-continue-kbd-macro
3632 If non-`nil', continue defining or executing any keyboard macro
3633 that is executing outside of Edebug. Use this with caution since
3634 it is not debugged. See *Note Edebug Execution Modes::.
3636 -- User Option: edebug-print-length
3637 If non-`nil', bind `print-length' to this while printing results
3638 in Edebug. The default value is `50'. See *Note Printing in
3641 -- User Option: edebug-print-level
3642 If non-`nil', bind `print-level' to this while printing results in
3643 Edebug. The default value is `50'.
3645 -- User Option: edebug-print-circle
3646 If non-`nil', bind `print-circle' to this while printing results
3647 in Edebug. The default value is `nil'.
3649 -- User Option: edebug-on-error
3650 `debug-on-error' is bound to this while Edebug is active. See
3651 *Note Trapping Errors::.
3653 -- User Option: edebug-on-quit
3654 `debug-on-quit' is bound to this while Edebug is active. See
3655 *Note Trapping Errors::.
3657 -- User Option: edebug-unwrap-results
3658 Non-`nil' if Edebug should unwrap results of expressions. This is
3659 useful when debugging macros where the results of expressions are
3660 instrumented expressions. But don't do this when results might be
3661 circular or an infinite loop will result. See *Note Debugging
3664 -- User Option: edebug-global-break-condition
3665 If non-`nil', an expression to test for at every stop point. If
3666 the result is non-`nil', then break. Errors are ignored. See
3667 *Note Global Break Condition::.
3670 File: lispref.info, Node: Read and Print, Next: Minibuffers, Prev: Debugging, Up: Top
3672 23 Reading and Printing Lisp Objects
3673 ************************************
3675 "Printing" and "reading" are the operations of converting Lisp objects
3676 to textual form and vice versa. They use the printed representations
3677 and read syntax described in *Note Lisp Data Types::.
3679 This chapter describes the Lisp functions for reading and printing.
3680 It also describes "streams", which specify where to get the text (if
3681 reading) or where to put it (if printing).
3685 * Streams Intro:: Overview of streams, reading and printing.
3686 * Input Streams:: Various data types that can be used as input streams.
3687 * Input Functions:: Functions to read Lisp objects from text.
3688 * Output Streams:: Various data types that can be used as output streams.
3689 * Output Functions:: Functions to print Lisp objects as text.
3690 * Output Variables:: Variables that control what the printing functions do.
3693 File: lispref.info, Node: Streams Intro, Next: Input Streams, Up: Read and Print
3695 23.1 Introduction to Reading and Printing
3696 =========================================
3698 "Reading" a Lisp object means parsing a Lisp expression in textual form
3699 and producing a corresponding Lisp object. This is how Lisp programs
3700 get into Lisp from files of Lisp code. We call the text the "read
3701 syntax" of the object. For example, the text `(a . 5)' is the read
3702 syntax for a cons cell whose CAR is `a' and whose CDR is the number 5.
3704 "Printing" a Lisp object means producing text that represents that
3705 object--converting the object to its printed representation. Printing
3706 the cons cell described above produces the text `(a . 5)'.
3708 Reading and printing are more or less inverse operations: printing
3709 the object that results from reading a given piece of text often
3710 produces the same text, and reading the text that results from printing
3711 an object usually produces a similar-looking object. For example,
3712 printing the symbol `foo' produces the text `foo', and reading that text
3713 returns the symbol `foo'. Printing a list whose elements are `a' and
3714 `b' produces the text `(a b)', and reading that text produces a list
3715 (but not the same list) with elements `a' and `b'.
3717 However, these two operations are not precisely inverses. There are
3718 three kinds of exceptions:
3720 * Printing can produce text that cannot be read. For example,
3721 buffers, windows, frames, subprocesses and markers print into text
3722 that starts with `#'; if you try to read this text, you get an
3723 error. There is no way to read those data types.
3725 * One object can have multiple textual representations. For example,
3726 `1' and `01' represent the same integer, and `(a b)' and `(a .
3727 (b))' represent the same list. Reading will accept any of the
3728 alternatives, but printing must choose one of them.
3730 * Comments can appear at certain points in the middle of an object's
3731 read sequence without affecting the result of reading it.
3734 File: lispref.info, Node: Input Streams, Next: Input Functions, Prev: Streams Intro, Up: Read and Print
3739 Most of the Lisp functions for reading text take an "input stream" as
3740 an argument. The input stream specifies where or how to get the
3741 characters of the text to be read. Here are the possible types of input
3745 The input characters are read from BUFFER, starting with the
3746 character directly after point. Point advances as characters are
3750 The input characters are read from the buffer that MARKER is in,
3751 starting with the character directly after the marker. The marker
3752 position advances as characters are read. The value of point in
3753 the buffer has no effect when the stream is a marker.
3756 The input characters are taken from STRING, starting at the first
3757 character in the string and using as many characters as required.
3760 The input characters are generated by FUNCTION, one character per
3761 call. Normally FUNCTION is called with no arguments, and should
3764 Occasionally FUNCTION is called with one argument (always a
3765 character). When that happens, FUNCTION should save the argument
3766 and arrange to return it on the next call. This is called
3767 "unreading" the character; it happens when the Lisp reader reads
3768 one character too many and wants to "put it back where it came
3772 `t' used as a stream means that the input is read from the
3773 minibuffer. In fact, the minibuffer is invoked once and the text
3774 given by the user is made into a string that is then used as the
3778 `nil' supplied as an input stream means to use the value of
3779 `standard-input' instead; that value is the "default input
3780 stream", and must be a non-`nil' input stream.
3783 A symbol as input stream is equivalent to the symbol's function
3784 definition (if any).
3786 Here is an example of reading from a stream that is a buffer, showing
3787 where point is located before and after:
3789 ---------- Buffer: foo ----------
3790 This-!- is the contents of foo.
3791 ---------- Buffer: foo ----------
3793 (read (get-buffer "foo"))
3795 (read (get-buffer "foo"))
3798 ---------- Buffer: foo ----------
3799 This is the-!- contents of foo.
3800 ---------- Buffer: foo ----------
3802 Note that the first read skips a space. Reading skips any amount of
3803 whitespace preceding the significant text.
3805 In Emacs 18, reading a symbol discarded the delimiter terminating the
3806 symbol. Thus, point would end up at the beginning of `contents' rather
3807 than after `the'. The Emacs 19 behavior is superior because it
3808 correctly handles input such as `bar(foo)', where the open-parenthesis
3809 that ends one object is needed as the beginning of another object.
3811 Here is an example of reading from a stream that is a marker,
3812 initially positioned at the beginning of the buffer shown. The value
3813 read is the symbol `This'.
3816 ---------- Buffer: foo ----------
3817 This is the contents of foo.
3818 ---------- Buffer: foo ----------
3820 (setq m (set-marker (make-marker) 1 (get-buffer "foo")))
3821 => #<marker at 1 in foo>
3825 => #<marker at 5 in foo> ;; Before the first space.
3827 Here we read from the contents of a string:
3829 (read "(When in) the course")
3832 The following example reads from the minibuffer. The prompt is:
3833 `Lisp expression: '. (That is always the prompt used when you read
3834 from the stream `t'.) The user's input is shown following the prompt.
3838 ---------- Buffer: Minibuffer ----------
3839 Lisp expression: 23 <RET>
3840 ---------- Buffer: Minibuffer ----------
3842 Finally, here is an example of a stream that is a function, named
3843 `useless-stream'. Before we use the stream, we initialize the variable
3844 `useless-list' to a list of characters. Then each call to the function
3845 `useless-stream' obtains the next character in the list or unreads a
3846 character by adding it to the front of the list.
3848 (setq useless-list (append "XY()" nil))
3851 (defun useless-stream (&optional unread)
3853 (setq useless-list (cons unread useless-list))
3854 (prog1 (car useless-list)
3855 (setq useless-list (cdr useless-list)))))
3858 Now we read using the stream thus constructed:
3860 (read 'useless-stream)
3866 Note that the open and close parentheses remains in the list. The Lisp
3867 reader encountered the open parenthesis, decided that it ended the
3868 input, and unread it. Another attempt to read from the stream at this
3869 point would read `()' and return `nil'.
3872 File: lispref.info, Node: Input Functions, Next: Output Streams, Prev: Input Streams, Up: Read and Print
3874 23.3 Input Functions
3875 ====================
3877 This section describes the Lisp functions and variables that pertain to
3880 In the functions below, STREAM stands for an input stream (see the
3881 previous section). If STREAM is `nil' or omitted, it defaults to the
3882 value of `standard-input'.
3884 An `end-of-file' error is signaled if reading encounters an
3885 unterminated list, vector, or string.
3887 -- Function: read &optional stream
3888 This function reads one textual Lisp expression from STREAM,
3889 returning it as a Lisp object. This is the basic Lisp input
3892 -- Function: read-from-string string &optional start end
3893 This function reads the first textual Lisp expression from the
3894 text in STRING. It returns a cons cell whose CAR is that
3895 expression, and whose CDR is an integer giving the position of the
3896 next remaining character in the string (i.e., the first one not
3899 If START is supplied, then reading begins at index START in the
3900 string (where the first character is at index 0). If END is also
3901 supplied, then reading stops just before that index, as if the rest
3902 of the string were not there.
3906 (read-from-string "(setq x 55) (setq y 5)")
3907 => ((setq x 55) . 11)
3908 (read-from-string "\"A short string\"")
3909 => ("A short string" . 16)
3911 ;; Read starting at the first character.
3912 (read-from-string "(list 112)" 0)
3913 => ((list 112) . 10)
3914 ;; Read starting at the second character.
3915 (read-from-string "(list 112)" 1)
3917 ;; Read starting at the seventh character,
3918 ;; and stopping at the ninth.
3919 (read-from-string "(list 112)" 6 8)
3922 -- Variable: standard-input
3923 This variable holds the default input stream--the stream that
3924 `read' uses when the STREAM argument is `nil'.
3927 File: lispref.info, Node: Output Streams, Next: Output Functions, Prev: Input Functions, Up: Read and Print
3932 An output stream specifies what to do with the characters produced by
3933 printing. Most print functions accept an output stream as an optional
3934 argument. Here are the possible types of output stream:
3937 The output characters are inserted into BUFFER at point. Point
3938 advances as characters are inserted.
3941 The output characters are inserted into the buffer that MARKER
3942 points into, at the marker position. The marker position advances
3943 as characters are inserted. The value of point in the buffer has
3944 no effect on printing when the stream is a marker.
3947 The output characters are passed to FUNCTION, which is responsible
3948 for storing them away. It is called with a single character as
3949 argument, as many times as there are characters to be output, and
3950 is free to do anything at all with the characters it receives.
3953 The output characters are displayed in the echo area.
3956 `nil' specified as an output stream means to the value of
3957 `standard-output' instead; that value is the "default output
3958 stream", and must be a non-`nil' output stream.
3961 A symbol as output stream is equivalent to the symbol's function
3962 definition (if any).
3964 Many of the valid output streams are also valid as input streams.
3965 The difference between input and output streams is therefore mostly one
3966 of how you use a Lisp object, not a distinction of types of object.
3968 Here is an example of a buffer used as an output stream. Point is
3969 initially located as shown immediately before the `h' in `the'. At the
3970 end, point is located directly before that same `h'.
3972 ---------- Buffer: foo ----------
3973 This is t-!-he contents of foo.
3974 ---------- Buffer: foo ----------
3976 (print "This is the output" (get-buffer "foo"))
3977 => "This is the output"
3979 ---------- Buffer: foo ----------
3981 "This is the output"
3982 -!-he contents of foo.
3983 ---------- Buffer: foo ----------
3985 Now we show a use of a marker as an output stream. Initially, the
3986 marker is in buffer `foo', between the `t' and the `h' in the word
3987 `the'. At the end, the marker has advanced over the inserted text so
3988 that it remains positioned before the same `h'. Note that the location
3989 of point, shown in the usual fashion, has no effect.
3991 ---------- Buffer: foo ----------
3992 "This is the -!-output"
3993 ---------- Buffer: foo ----------
3996 => #<marker at 11 in foo>
3998 (print "More output for foo." m)
3999 => "More output for foo."
4001 ---------- Buffer: foo ----------
4003 "More output for foo."
4005 ---------- Buffer: foo ----------
4008 => #<marker at 35 in foo>
4010 The following example shows output to the echo area:
4012 (print "Echo Area output" t)
4013 => "Echo Area output"
4014 ---------- Echo Area ----------
4016 ---------- Echo Area ----------
4018 Finally, we show the use of a function as an output stream. The
4019 function `eat-output' takes each character that it is given and conses
4020 it onto the front of the list `last-output' (*note Building Lists::).
4021 At the end, the list contains all the characters output, but in reverse
4024 (setq last-output nil)
4027 (defun eat-output (c)
4028 (setq last-output (cons c last-output)))
4031 (print "This is the output" 'eat-output)
4032 => "This is the output"
4035 => (?\n ?\" ?t ?u ?p ?t ?u ?o ?\ ?e ?h ?t
4036 ?\ ?s ?i ?\ ?s ?i ?h ?T ?\" ?\n)
4038 Now we can put the output in the proper order by reversing the list:
4040 (concat (nreverse last-output))
4042 \"This is the output\"
4045 Calling `concat' converts the list to a string so you can see its
4046 contents more clearly.
4049 File: lispref.info, Node: Output Functions, Next: Output Variables, Prev: Output Streams, Up: Read and Print
4051 23.5 Output Functions
4052 =====================
4054 This section describes the Lisp functions for printing Lisp objects.
4056 Some of the XEmacs printing functions add quoting characters to the
4057 output when necessary so that it can be read properly. The quoting
4058 characters used are `"' and `\'; they distinguish strings from symbols,
4059 and prevent punctuation characters in strings and symbols from being
4060 taken as delimiters when reading. *Note Printed Representation::, for
4061 full details. You specify quoting or no quoting by the choice of
4064 If the text is to be read back into Lisp, then it is best to print
4065 with quoting characters to avoid ambiguity. Likewise, if the purpose is
4066 to describe a Lisp object clearly for a Lisp programmer. However, if
4067 the purpose of the output is to look nice for humans, then it is better
4068 to print without quoting.
4070 Printing a self-referent Lisp object requires an infinite amount of
4071 text. In certain cases, trying to produce this text leads to a stack
4072 overflow. XEmacs detects such recursion and prints `#LEVEL' instead of
4073 recursively printing an object already being printed. For example,
4074 here `#0' indicates a recursive reference to the object at level 0 of
4075 the current print operation:
4077 (setq foo (list nil))
4082 In the functions below, STREAM stands for an output stream. (See
4083 the previous section for a description of output streams.) If STREAM
4084 is `nil' or omitted, it defaults to the value of `standard-output'.
4086 -- Function: print object &optional stream
4087 The `print' function is a convenient way of printing. It outputs
4088 the printed representation of OBJECT to STREAM, printing in
4089 addition one newline before OBJECT and another after it. Quoting
4090 characters are used. `print' returns OBJECT. For example:
4092 (progn (print 'The\ cat\ in)
4094 (print " came back"))
4104 -- Function: prin1 object &optional stream
4105 This function outputs the printed representation of OBJECT to
4106 STREAM. It does not print newlines to separate output as `print'
4107 does, but it does use quoting characters just like `print'. It
4110 (progn (prin1 'The\ cat\ in)
4112 (prin1 " came back"))
4113 -| The\ cat\ in"the hat"" came back"
4116 -- Function: princ object &optional stream
4117 This function outputs the printed representation of OBJECT to
4118 STREAM. It returns OBJECT.
4120 This function is intended to produce output that is readable by
4121 people, not by `read', so it doesn't insert quoting characters and
4122 doesn't put double-quotes around the contents of strings. It does
4123 not add any spacing between calls.
4127 (princ " in the \"hat\""))
4128 -| The cat in the "hat"
4129 => " in the \"hat\""
4131 -- Function: terpri &optional stream
4132 This function outputs a newline to STREAM. The name stands for
4135 -- Function: write-char character &optional stream
4136 This function outputs CHARACTER to STREAM. It returns CHARACTER.
4138 -- Function: prin1-to-string object &optional noescape
4139 This function returns a string containing the text that `prin1'
4140 would have printed for the same argument.
4142 (prin1-to-string 'foo)
4144 (prin1-to-string (mark-marker))
4145 => "#<marker at 2773 in strings.texi>"
4147 If NOESCAPE is non-`nil', that inhibits use of quoting characters
4148 in the output. (This argument is supported in Emacs versions 19
4151 (prin1-to-string "foo")
4153 (prin1-to-string "foo" t)
4156 See `format', in *Note String Conversion::, for other ways to
4157 obtain the printed representation of a Lisp object as a string.
4160 File: lispref.info, Node: Output Variables, Prev: Output Functions, Up: Read and Print
4162 23.6 Variables Affecting Output
4163 ===============================
4165 -- Variable: standard-output
4166 The value of this variable is the default output stream--the stream
4167 that print functions use when the STREAM argument is `nil'.
4169 -- Variable: print-escape-newlines
4170 If this variable is non-`nil', then newline characters in strings
4171 are printed as `\n' and formfeeds are printed as `\f'. Normally
4172 these characters are printed as actual newlines and formfeeds.
4174 This variable affects the print functions `prin1' and `print', as
4175 well as everything that uses them. It does not affect `princ'.
4176 Here is an example using `prin1':
4184 (let ((print-escape-newlines t))
4190 In the second expression, the local binding of
4191 `print-escape-newlines' is in effect during the call to `prin1',
4192 but not during the printing of the result.
4194 -- Variable: print-readably
4195 If non-`nil', then all objects will be printed in a readable form.
4196 If an object has no readable representation, then an error is
4197 signalled. When `print-readably' is true, compiled-function
4198 objects will be written in `#[...]' form instead of in
4199 `#<compiled-function [...]>' form, and two-element lists of the
4200 form `(quote object)' will be written as the equivalent `'object'.
4201 Do not _set_ this variable; bind it instead.
4203 -- Variable: print-length
4204 The value of this variable is the maximum number of elements of a
4205 list that will be printed. If a list being printed has more than
4206 this many elements, it is abbreviated with an ellipsis.
4208 If the value is `nil' (the default), then there is no limit.
4210 (setq print-length 2)
4212 (print '(1 2 3 4 5))
4216 -- Variable: print-level
4217 The value of this variable is the maximum depth of nesting of
4218 parentheses and brackets when printed. Any list or vector at a
4219 depth exceeding this limit is abbreviated with an ellipsis. A
4220 value of `nil' (which is the default) means no limit.
4222 This variable exists in version 19 and later versions.
4224 -- Variable: print-string-length
4225 The value of this variable is the maximum number of characters of
4226 a string that will be printed. If a string being printed has more
4227 than this many characters, it is abbreviated with an ellipsis.
4229 -- Variable: print-gensym
4230 If non-`nil', then uninterned symbols will be printed specially.
4231 Uninterned symbols are those which are not present in `obarray',
4232 that is, those which were made with `make-symbol' or by calling
4233 `intern' with a second argument.
4235 When `print-gensym' is true, such symbols will be preceded by
4236 `#:', which causes the reader to create a new symbol instead of
4237 interning and returning an existing one. Beware: The `#:' syntax
4238 creates a new symbol each time it is seen, so if you print an
4239 object which contains two pointers to the same uninterned symbol,
4240 `read' will not duplicate that structure.
4242 Also, since XEmacs has no real notion of packages, there is no way
4243 for the printer to distinguish between symbols interned in no
4244 obarray, and symbols interned in an alternate obarray.
4246 -- Variable: float-output-format
4247 This variable holds the format descriptor string that Lisp uses to
4248 print floats. This is a `%'-spec like those accepted by `printf'
4249 in C, but with some restrictions. It must start with the two
4250 characters `%.'. After that comes an integer precision
4251 specification, and then a letter which controls the format. The
4252 letters allowed are `e', `f' and `g'.
4254 * Use `e' for exponential notation `DIG.DIGITSeEXPT'.
4256 * Use `f' for decimal point notation `DIGITS.DIGITS'.
4258 * Use `g' to choose the shorter of those two formats for the
4261 The precision in any of these cases is the number of digits
4262 following the decimal point. With `f', a precision of 0 means to
4263 omit the decimal point. 0 is not allowed with `f' or `g'.
4265 A value of `nil' means to use `%.16g'.
4267 Regardless of the value of `float-output-format', a floating point
4268 number will never be printed in such a way that it is ambiguous
4269 with an integer; that is, a floating-point number will always be
4270 printed with a decimal point and/or an exponent, even if the
4271 digits following the decimal point are all zero. This is to
4272 preserve read-equivalence.
4275 File: lispref.info, Node: Minibuffers, Next: Command Loop, Prev: Read and Print, Up: Top
4280 A "minibuffer" is a special buffer that XEmacs commands use to read
4281 arguments more complicated than the single numeric prefix argument.
4282 These arguments include file names, buffer names, and command names (as
4283 in `M-x'). The minibuffer is displayed on the bottom line of the
4284 frame, in the same place as the echo area, but only while it is in use
4285 for reading an argument.
4289 * Intro to Minibuffers:: Basic information about minibuffers.
4290 * Text from Minibuffer:: How to read a straight text string.
4291 * Object from Minibuffer:: How to read a Lisp object or expression.
4292 * Minibuffer History:: Recording previous minibuffer inputs
4293 so the user can reuse them.
4294 * Completion:: How to invoke and customize completion.
4295 * Yes-or-No Queries:: Asking a question with a simple answer.
4296 * Multiple Queries:: Asking a series of similar questions.
4297 * Reading a Password:: Reading a password from the terminal.
4298 * Minibuffer Misc:: Various customization hooks and variables.
4301 File: lispref.info, Node: Intro to Minibuffers, Next: Text from Minibuffer, Up: Minibuffers
4303 24.1 Introduction to Minibuffers
4304 ================================
4306 In most ways, a minibuffer is a normal XEmacs buffer. Most operations
4307 _within_ a buffer, such as editing commands, work normally in a
4308 minibuffer. However, many operations for managing buffers do not apply
4309 to minibuffers. The name of a minibuffer always has the form
4310 ` *Minibuf-NUMBER', and it cannot be changed. Minibuffers are
4311 displayed only in special windows used only for minibuffers; these
4312 windows always appear at the bottom of a frame. (Sometimes frames have
4313 no minibuffer window, and sometimes a special kind of frame contains
4314 nothing but a minibuffer window; see *Note Minibuffers and Frames::.)
4316 The minibuffer's window is normally a single line. You can resize it
4317 temporarily with the window sizing commands; it reverts to its normal
4318 size when the minibuffer is exited. You can resize it permanently by
4319 using the window sizing commands in the frame's other window, when the
4320 minibuffer is not active. If the frame contains just a minibuffer, you
4321 can change the minibuffer's size by changing the frame's size.
4323 If a command uses a minibuffer while there is an active minibuffer,
4324 this is called a "recursive minibuffer". The first minibuffer is named
4325 ` *Minibuf-0*'. Recursive minibuffers are named by incrementing the
4326 number at the end of the name. (The names begin with a space so that
4327 they won't show up in normal buffer lists.) Of several recursive
4328 minibuffers, the innermost (or most recently entered) is the active
4329 minibuffer. We usually call this "the" minibuffer. You can permit or
4330 forbid recursive minibuffers by setting the variable
4331 `enable-recursive-minibuffers'.
4333 Like other buffers, a minibuffer may use any of several local keymaps
4334 (*note Keymaps::); these contain various exit commands and in some cases
4335 completion commands (*note Completion::).
4337 * `minibuffer-local-map' is for ordinary input (no completion).
4339 * `minibuffer-local-completion-map' is for permissive completion.
4341 * `minibuffer-local-must-match-map' is for strict completion and for
4342 cautious completion.
4345 File: lispref.info, Node: Text from Minibuffer, Next: Object from Minibuffer, Prev: Intro to Minibuffers, Up: Minibuffers
4347 24.2 Reading Text Strings with the Minibuffer
4348 =============================================
4350 Most often, the minibuffer is used to read text as a string. It can
4351 also be used to read a Lisp object in textual form. The most basic
4352 primitive for minibuffer input is `read-from-minibuffer'; it can do
4355 In most cases, you should not call minibuffer input functions in the
4356 middle of a Lisp function. Instead, do all minibuffer input as part of
4357 reading the arguments for a command, in the `interactive' spec. *Note
4358 Defining Commands::.
4360 -- Function: read-from-minibuffer prompt-string &optional
4361 initial-contents keymap read hist abbrev-table default
4362 This function is the most general way to get input through the
4363 minibuffer. By default, it accepts arbitrary text and returns it
4364 as a string; however, if READ is non-`nil', then it uses `read' to
4365 convert the text into a Lisp object (*note Input Functions::).
4367 The first thing this function does is to activate a minibuffer and
4368 display it with PROMPT-STRING as the prompt. This value must be a
4371 Then, if INITIAL-CONTENTS is a string, `read-from-minibuffer'
4372 inserts it into the minibuffer, leaving point at the end. The
4373 minibuffer appears with this text as its contents.
4375 The value of INITIAL-CONTENTS may also be a cons cell of the form
4376 `(STRING . POSITION)'. This means to insert STRING in the
4377 minibuffer but put point POSITION characters from the beginning,
4378 rather than at the end.
4380 When the user types a command to exit the minibuffer,
4381 `read-from-minibuffer' constructs the return value from the text in
4382 the minibuffer. Normally it returns a string containing that text.
4383 However, if READ is non-`nil', `read-from-minibuffer' reads the
4384 text and returns the resulting Lisp object, unevaluated. (*Note
4385 Input Functions::, for information about reading.)
4387 The argument DEFAULT specifies a default value to make available
4388 through the history commands. It should be a string, or `nil'.
4390 If KEYMAP is non-`nil', that keymap is the local keymap to use in
4391 the minibuffer. If KEYMAP is omitted or `nil', the value of
4392 `minibuffer-local-map' is used as the keymap. Specifying a keymap
4393 is the most important way to customize the minibuffer for various
4394 applications such as completion.
4396 The argument ABBREV-TABLE specifies `local-abbrev-table' in the
4397 minibuffer (*note Standard Abbrev Tables::).
4399 The argument HIST specifies which history list variable to use for
4400 saving the input and for history commands used in the minibuffer.
4401 It defaults to `minibuffer-history'. *Note Minibuffer History::.
4403 When the user types a command to exit the minibuffer,
4404 `read-from-minibuffer' uses the text in the minibuffer to produce
4405 its return value. Normally it simply makes a string containing
4406 that text. However, if READ is non-`nil', `read-from-minibuffer'
4407 reads the text and returns the resulting Lisp object, unevaluated.
4408 (*Note Input Functions::, for information about reading.)
4410 *Usage note:* The INITIAL-CONTENTS argument and the DEFAULT
4411 argument are two alternative features for more or less the same
4412 job. It does not make sense to use both features in a single call
4413 to `read-from-minibuffer'. In general, we recommend using
4414 DEFAULT, since this permits the user to insert the default value
4415 when it is wanted, but does not burden the user with deleting it
4416 from the minibuffer on other occasions. However, if user is
4417 supposed to edit default value, INITIAL-CONTENTS may be preferred.
4419 -- Function: read-string prompt &optional initial history default-value
4420 This function reads a string from the minibuffer and returns it.
4421 The arguments PROMPT and INITIAL are used as in
4422 `read-from-minibuffer'. The keymap used is `minibuffer-local-map'.
4424 The optional argument HISTORY, if non-`nil', specifies a history
4425 list and optionally the initial position in the list. The optional
4426 argument DEFAULT-VALUE specifies a default value to return if the
4427 user enters null input; it should be a string.
4429 This function is a simplified interface to the
4430 `read-from-minibuffer' function:
4432 (read-string PROMPT INITIAL HISTORY DEFAULT)
4434 (read-from-minibuffer PROMPT INITIAL nil nil
4435 HISTORY nil DEFAULT)))
4437 -- Variable: minibuffer-local-map
4438 This is the default local keymap for reading from the minibuffer.
4439 By default, it makes the following bindings:
4448 `abort-recursive-edit'
4451 `next-history-element'
4454 `previous-history-element'
4457 `next-matching-history-element'
4460 `previous-matching-history-element'
4463 File: lispref.info, Node: Object from Minibuffer, Next: Minibuffer History, Prev: Text from Minibuffer, Up: Minibuffers
4465 24.3 Reading Lisp Objects with the Minibuffer
4466 =============================================
4468 This section describes functions for reading Lisp objects with the
4471 -- Function: read-expression prompt &optional initial history
4473 This function reads a Lisp object using the minibuffer, and
4474 returns it without evaluating it. The arguments PROMPT and
4475 INITIAL are used as in `read-from-minibuffer'.
4477 The optional argument HISTORY, if non-`nil', specifies a history
4478 list and optionally the initial position in the list. The optional
4479 argument DEFAULT-VALUE specifies a default value to return if the
4480 user enters null input; it should be a string.
4482 This is a simplified interface to the `read-from-minibuffer'
4485 (read-expression PROMPT INITIAL HISTORY DEFAULT-VALUE)
4487 (read-from-minibuffer PROMPT INITIAL nil t
4488 HISTORY nil DEFAULT-VALUE)
4490 Here is an example in which we supply the string `"(testing)"' as
4494 "Enter an expression: " (format "%s" '(testing)))
4496 ;; Here is how the minibuffer is displayed:
4498 ---------- Buffer: Minibuffer ----------
4499 Enter an expression: (testing)-!-
4500 ---------- Buffer: Minibuffer ----------
4502 The user can type <RET> immediately to use the initial input as a
4503 default, or can edit the input.
4505 -- Function: read-minibuffer prompt &optional initial history
4507 This is a FSF Emacs compatible function. Use `read-expression'
4510 -- Function: eval-minibuffer prompt &optional initial history
4512 This function reads a Lisp expression using the minibuffer,
4513 evaluates it, then returns the result. The arguments PROMPT and
4514 INITIAL are used as in `read-from-minibuffer'.
4516 The optional argument HISTORY, if non-`nil', specifies a history
4517 list and optionally the initial position in the list. The optional
4518 argument DEFAULT-VALUE specifies a default value to return if the
4519 user enters null input; it should be a string.
4521 This function simply evaluates the result of a call to
4524 (eval-minibuffer PROMPT INITIAL)
4526 (eval (read-expression PROMPT INITIAL))
4528 -- Function: edit-and-eval-command prompt form &optional history
4529 This function reads a Lisp expression in the minibuffer, and then
4530 evaluates it. The difference between this command and
4531 `eval-minibuffer' is that here the initial FORM is not optional
4532 and it is treated as a Lisp object to be converted to printed
4533 representation rather than as a string of text. It is printed with
4534 `prin1', so if it is a string, double-quote characters (`"')
4535 appear in the initial text. *Note Output Functions::.
4537 The first thing `edit-and-eval-command' does is to activate the
4538 minibuffer with PROMPT as the prompt. Then it inserts the printed
4539 representation of FORM in the minibuffer, and lets the user edit
4540 it. When the user exits the minibuffer, the edited text is read
4541 with `read' and then evaluated. The resulting value becomes the
4542 value of `edit-and-eval-command'.
4544 In the following example, we offer the user an expression with
4545 initial text which is a valid form already:
4547 (edit-and-eval-command "Please edit: " '(forward-word 1))
4549 ;; After evaluation of the preceding expression,
4550 ;; the following appears in the minibuffer:
4552 ---------- Buffer: Minibuffer ----------
4553 Please edit: (forward-word 1)-!-
4554 ---------- Buffer: Minibuffer ----------
4556 Typing <RET> right away would exit the minibuffer and evaluate the
4557 expression, thus moving point forward one word.
4558 `edit-and-eval-command' returns `t' in this example.
4561 File: lispref.info, Node: Minibuffer History, Next: Completion, Prev: Object from Minibuffer, Up: Minibuffers
4563 24.4 Minibuffer History
4564 =======================
4566 A "minibuffer history list" records previous minibuffer inputs so the
4567 user can reuse them conveniently. A history list is actually a symbol,
4568 not a list; it is a variable whose value is a list of strings (previous
4569 inputs), most recent first.
4571 There are many separate history lists, used for different kinds of
4572 inputs. It's the Lisp programmer's job to specify the right history
4573 list for each use of the minibuffer.
4575 The basic minibuffer input functions `read-from-minibuffer' and
4576 `completing-read' both accept an optional argument named HIST which is
4577 how you specify the history list. Here are the possible values:
4580 Use VARIABLE (a symbol) as the history list.
4582 (VARIABLE . STARTPOS)
4583 Use VARIABLE (a symbol) as the history list, and assume that the
4584 initial history position is STARTPOS (an integer, counting from
4585 zero which specifies the most recent element of the history).
4587 If you specify STARTPOS, then you should also specify that element
4588 of the history as the initial minibuffer contents, for consistency.
4590 If you don't specify HIST, then the default history list
4591 `minibuffer-history' is used. For other standard history lists, see
4592 below. You can also create your own history list variable; just
4593 initialize it to `nil' before the first use.
4595 Both `read-from-minibuffer' and `completing-read' add new elements
4596 to the history list automatically, and provide commands to allow the
4597 user to reuse items on the list. The only thing your program needs to
4598 do to use a history list is to initialize it and to pass its name to
4599 the input functions when you wish. But it is safe to modify the list
4600 by hand when the minibuffer input functions are not using it.
4602 Here are some of the standard minibuffer history list variables:
4604 -- Variable: minibuffer-history
4605 The default history list for minibuffer history input.
4607 -- Variable: query-replace-history
4608 A history list for arguments to `query-replace' (and similar
4609 arguments to other commands).
4611 -- Variable: file-name-history
4612 A history list for file name arguments.
4614 -- Variable: regexp-history
4615 A history list for regular expression arguments.
4617 -- Variable: extended-command-history
4618 A history list for arguments that are names of extended commands.
4620 -- Variable: shell-command-history
4621 A history list for arguments that are shell commands.
4623 -- Variable: read-expression-history
4624 A history list for arguments that are Lisp expressions to evaluate.
4626 -- Variable: Info-minibuffer-history
4627 A history list for Info mode's minibuffer.
4629 -- Variable: Manual-page-minibuffer-history
4630 A history list for `manual-entry'.
4632 There are many other minibuffer history lists, defined by various
4633 libraries. An `M-x apropos' search for `history' should prove fruitful
4634 in discovering them.
4637 File: lispref.info, Node: Completion, Next: Yes-or-No Queries, Prev: Minibuffer History, Up: Minibuffers
4642 "Completion" is a feature that fills in the rest of a name starting
4643 from an abbreviation for it. Completion works by comparing the user's
4644 input against a list of valid names and determining how much of the
4645 name is determined uniquely by what the user has typed. For example,
4646 when you type `C-x b' (`switch-to-buffer') and then type the first few
4647 letters of the name of the buffer to which you wish to switch, and then
4648 type <TAB> (`minibuffer-complete'), Emacs extends the name as far as it
4651 Standard XEmacs commands offer completion for names of symbols,
4652 files, buffers, and processes; with the functions in this section, you
4653 can implement completion for other kinds of names.
4655 The `try-completion' function is the basic primitive for completion:
4656 it returns the longest determined completion of a given initial string,
4657 with a given set of strings to match against.
4659 The function `completing-read' provides a higher-level interface for
4660 completion. A call to `completing-read' specifies how to determine the
4661 list of valid names. The function then activates the minibuffer with a
4662 local keymap that binds a few keys to commands useful for completion.
4663 Other functions provide convenient simple interfaces for reading
4664 certain kinds of names with completion.
4668 * Basic Completion:: Low-level functions for completing strings.
4669 (These are too low level to use the minibuffer.)
4670 * Minibuffer Completion:: Invoking the minibuffer with completion.
4671 * Completion Commands:: Minibuffer commands that do completion.
4672 * High-Level Completion:: Convenient special cases of completion
4673 (reading buffer name, file name, etc.)
4674 * Reading File Names:: Using completion to read file names.
4675 * Programmed Completion:: Finding the completions for a given file name.
4678 File: lispref.info, Node: Basic Completion, Next: Minibuffer Completion, Up: Completion
4680 24.5.1 Basic Completion Functions
4681 ---------------------------------
4683 The two functions `try-completion' and `all-completions' have nothing
4684 in themselves to do with minibuffers. We describe them in this chapter
4685 so as to keep them near the higher-level completion features that do
4688 -- Function: try-completion string collection &optional predicate
4689 This function returns the longest common prefix of all possible
4690 completions of STRING in COLLECTION. The value of COLLECTION must
4691 be an alist, an obarray, or a function that implements a virtual
4692 set of strings (see below).
4694 Completion compares STRING against each of the permissible
4695 completions specified by COLLECTION; if the beginning of the
4696 permissible completion equals STRING, it matches. If no
4697 permissible completions match, `try-completion' returns `nil'. If
4698 only one permissible completion matches, and the match is exact,
4699 then `try-completion' returns `t'. Otherwise, the value is the
4700 longest initial sequence common to all the permissible completions
4703 If COLLECTION is an alist (*note Association Lists::), the CARs of
4704 the alist elements form the set of permissible completions.
4706 If COLLECTION is an obarray (*note Creating Symbols::), the names
4707 of all symbols in the obarray form the set of permissible
4708 completions. The global variable `obarray' holds an obarray
4709 containing the names of all interned Lisp symbols.
4711 Note that the only valid way to make a new obarray is to create it
4712 empty and then add symbols to it one by one using `intern'. Also,
4713 you cannot intern a given symbol in more than one obarray.
4715 If the argument PREDICATE is non-`nil', then it must be a function
4716 of one argument. It is used to test each possible match, and the
4717 match is accepted only if PREDICATE returns non-`nil'. The
4718 argument given to PREDICATE is either a cons cell from the alist
4719 (the CAR of which is a string) or else it is a symbol (_not_ a
4720 symbol name) from the obarray.
4722 You can also use a symbol that is a function as COLLECTION. Then
4723 the function is solely responsible for performing completion;
4724 `try-completion' returns whatever this function returns. The
4725 function is called with three arguments: STRING, PREDICATE and
4726 `nil'. (The reason for the third argument is so that the same
4727 function can be used in `all-completions' and do the appropriate
4728 thing in either case.) *Note Programmed Completion::.
4730 In the first of the following examples, the string `foo' is
4731 matched by three of the alist CARs. All of the matches begin with
4732 the characters `fooba', so that is the result. In the second
4733 example, there is only one possible match, and it is exact, so the
4738 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4)))
4741 (try-completion "foo" '(("barfoo" 2) ("foo" 3)))
4744 In the following example, numerous symbols begin with the
4745 characters `forw', and all of them begin with the word `forward'.
4746 In most of the symbols, this is followed with a `-', but not in
4747 all, so no more than `forward' can be completed.
4749 (try-completion "forw" obarray)
4752 Finally, in the following example, only two of the three possible
4753 matches pass the predicate `test' (the string `foobaz' is too
4754 short). Both of those begin with the string `foobar'.
4757 (> (length (car s)) 6))
4761 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))
4765 -- Function: all-completions string collection &optional predicate
4766 This function returns a list of all possible completions of STRING.
4767 The arguments to this function are the same as those of
4770 If COLLECTION is a function, it is called with three arguments:
4771 STRING, PREDICATE and `t'; then `all-completions' returns whatever
4772 the function returns. *Note Programmed Completion::.
4774 Here is an example, using the function `test' shown in the example
4775 for `try-completion':
4778 (> (length (car s)) 6))
4783 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))
4785 => ("foobar1" "foobar2")
4787 -- Variable: completion-ignore-case
4788 If the value of this variable is non-`nil', XEmacs does not
4789 consider case significant in completion.
4792 File: lispref.info, Node: Minibuffer Completion, Next: Completion Commands, Prev: Basic Completion, Up: Completion
4794 24.5.2 Completion and the Minibuffer
4795 ------------------------------------
4797 This section describes the basic interface for reading from the
4798 minibuffer with completion.
4800 -- Function: completing-read prompt collection &optional predicate
4801 require-match initial hist default
4802 This function reads a string in the minibuffer, assisting the user
4803 by providing completion. It activates the minibuffer with prompt
4804 PROMPT, which must be a string. If INITIAL is non-`nil',
4805 `completing-read' inserts it into the minibuffer as part of the
4806 input. Then it allows the user to edit the input, providing
4807 several commands to attempt completion.
4809 The actual completion is done by passing COLLECTION and PREDICATE
4810 to the function `try-completion'. This happens in certain
4811 commands bound in the local keymaps used for completion.
4813 If REQUIRE-MATCH is `t', the usual minibuffer exit commands won't
4814 exit unless the input completes to an element of COLLECTION. If
4815 REQUIRE-MATCH is neither `nil' nor `t', then the exit commands
4816 won't exit unless the input typed is itself an element of
4817 COLLECTION. If REQUIRE-MATCH is `nil', the exit commands work
4818 regardless of the input in the minibuffer.
4820 However, empty input is always permitted, regardless of the value
4821 of REQUIRE-MATCH; in that case, `completing-read' returns DEFAULT.
4822 The value of DEFAULT (if non-`nil') is also available to the user
4823 through the history commands.
4825 The user can exit with null input by typing <RET> with an empty
4826 minibuffer. Then `completing-read' returns `""'. This is how the
4827 user requests whatever default the command uses for the value being
4828 read. The user can return using <RET> in this way regardless of
4829 the value of REQUIRE-MATCH, and regardless of whether the empty
4830 string is included in COLLECTION.
4832 The function `completing-read' works by calling `read-expression'.
4833 It uses `minibuffer-local-completion-map' as the keymap if
4834 REQUIRE-MATCH is `nil', and uses `minibuffer-local-must-match-map'
4835 if REQUIRE-MATCH is non-`nil'. *Note Completion Commands::.
4837 The argument HIST specifies which history list variable to use for
4838 saving the input and for minibuffer history commands. It defaults
4839 to `minibuffer-history'. *Note Minibuffer History::.
4841 Completion ignores case when comparing the input against the
4842 possible matches, if the built-in variable
4843 `completion-ignore-case' is non-`nil'. *Note Basic Completion::.
4845 Here's an example of using `completing-read':
4849 '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))
4852 ;; After evaluation of the preceding expression,
4853 ;; the following appears in the minibuffer:
4855 ---------- Buffer: Minibuffer ----------
4856 Complete a foo: fo-!-
4857 ---------- Buffer: Minibuffer ----------
4859 If the user then types `<DEL> <DEL> b <RET>', `completing-read'
4862 The `completing-read' function binds three variables to pass
4863 information to the commands that actually do completion. These
4864 variables are `minibuffer-completion-table',
4865 `minibuffer-completion-predicate' and
4866 `minibuffer-completion-confirm'. For more information about them,
4867 see *Note Completion Commands::.
4870 File: lispref.info, Node: Completion Commands, Next: High-Level Completion, Prev: Minibuffer Completion, Up: Completion
4872 24.5.3 Minibuffer Commands That Do Completion
4873 ---------------------------------------------
4875 This section describes the keymaps, commands and user options used in
4876 the minibuffer to do completion.
4878 -- Variable: minibuffer-local-completion-map
4879 `completing-read' uses this value as the local keymap when an
4880 exact match of one of the completions is not required. By
4881 default, this keymap makes the following bindings:
4884 `minibuffer-completion-help'
4887 `minibuffer-complete-word'
4890 `minibuffer-complete'
4892 with other characters bound as in `minibuffer-local-map' (*note
4893 Text from Minibuffer::).
4895 -- Variable: minibuffer-local-must-match-map
4896 `completing-read' uses this value as the local keymap when an
4897 exact match of one of the completions is required. Therefore, no
4898 keys are bound to `exit-minibuffer', the command that exits the
4899 minibuffer unconditionally. By default, this keymap makes the
4903 `minibuffer-completion-help'
4906 `minibuffer-complete-word'
4909 `minibuffer-complete'
4912 `minibuffer-complete-and-exit'
4915 `minibuffer-complete-and-exit'
4917 with other characters bound as in `minibuffer-local-map'.
4919 -- Variable: minibuffer-completion-table
4920 The value of this variable is the alist or obarray used for
4921 completion in the minibuffer. This is the global variable that
4922 contains what `completing-read' passes to `try-completion'. It is
4923 used by minibuffer completion commands such as
4924 `minibuffer-complete-word'.
4926 -- Variable: minibuffer-completion-predicate
4927 This variable's value is the predicate that `completing-read'
4928 passes to `try-completion'. The variable is also used by the other
4929 minibuffer completion functions.
4931 -- Command: minibuffer-complete-word
4932 This function completes the minibuffer contents by at most a single
4933 word. Even if the minibuffer contents have only one completion,
4934 `minibuffer-complete-word' does not add any characters beyond the
4935 first character that is not a word constituent. *Note Syntax
4938 -- Command: minibuffer-complete
4939 This function completes the minibuffer contents as far as possible.
4941 -- Command: minibuffer-complete-and-exit
4942 This function completes the minibuffer contents, and exits if
4943 confirmation is not required, i.e., if
4944 `minibuffer-completion-confirm' is `nil'. If confirmation _is_
4945 required, it is given by repeating this command immediately--the
4946 command is programmed to work without confirmation when run twice
4949 -- Variable: minibuffer-completion-confirm
4950 When the value of this variable is non-`nil', XEmacs asks for
4951 confirmation of a completion before exiting the minibuffer. The
4952 function `minibuffer-complete-and-exit' checks the value of this
4953 variable before it exits.
4955 -- Command: minibuffer-completion-help
4956 This function creates a list of the possible completions of the
4957 current minibuffer contents. It works by calling `all-completions'
4958 using the value of the variable `minibuffer-completion-table' as
4959 the COLLECTION argument, and the value of
4960 `minibuffer-completion-predicate' as the PREDICATE argument. The
4961 list of completions is displayed as text in a buffer named
4964 -- Function: display-completion-list completions &rest cl-keys
4965 This function displays COMPLETIONS to the stream in
4966 `standard-output', usually a buffer. (*Note Read and Print::, for
4967 more information about streams.) The argument COMPLETIONS is
4968 normally a list of completions just returned by `all-completions',
4969 but it does not have to be. Each element may be a symbol or a
4970 string, either of which is simply printed, or a list of two
4971 strings, which is printed as if the strings were concatenated.
4973 This function is called by `minibuffer-completion-help'. The most
4974 common way to use it is together with
4975 `with-output-to-temp-buffer', like this:
4977 (with-output-to-temp-buffer "*Completions*"
4978 (display-completion-list
4979 (all-completions (buffer-string) my-alist)))
4981 -- User Option: completion-auto-help
4982 If this variable is non-`nil', the completion commands
4983 automatically display a list of possible completions whenever
4984 nothing can be completed because the next character is not
4985 uniquely determined.
4988 File: lispref.info, Node: High-Level Completion, Next: Reading File Names, Prev: Completion Commands, Up: Completion
4990 24.5.4 High-Level Completion Functions
4991 ---------------------------------------
4993 This section describes the higher-level convenient functions for
4994 reading certain sorts of names with completion.
4996 In most cases, you should not call these functions in the middle of a
4997 Lisp function. When possible, do all minibuffer input as part of
4998 reading the arguments for a command, in the `interactive' spec. *Note
4999 Defining Commands::.
5001 -- Function: read-buffer prompt &optional default existing
5002 This function reads the name of a buffer and returns it as a
5003 string. The argument DEFAULT is the default name to use, the
5004 value to return if the user exits with an empty minibuffer. If
5005 non-`nil', it should be a string or a buffer. It is mentioned in
5006 the prompt, but is not inserted in the minibuffer as initial input.
5008 If EXISTING is non-`nil', then the name specified must be that of
5009 an existing buffer. The usual commands to exit the minibuffer do
5010 not exit if the text is not valid, and <RET> does completion to
5011 attempt to find a valid name. (However, DEFAULT is not checked
5012 for validity; it is returned, whatever it is, if the user exits
5013 with the minibuffer empty.)
5015 In the following example, the user enters `minibuffer.t', and then
5016 types <RET>. The argument EXISTING is `t', and the only buffer
5017 name starting with the given input is `minibuffer.texi', so that
5020 (read-buffer "Buffer name? " "foo" t)
5021 ;; After evaluation of the preceding expression,
5022 ;; the following prompt appears,
5023 ;; with an empty minibuffer:
5025 ---------- Buffer: Minibuffer ----------
5026 Buffer name? (default foo) -!-
5027 ---------- Buffer: Minibuffer ----------
5029 ;; The user types `minibuffer.t <RET>'.
5030 => "minibuffer.texi"
5032 -- Function: read-command prompt &optional default-value
5033 This function reads the name of a command and returns it as a Lisp
5034 symbol. The argument PROMPT is used as in `read-from-minibuffer'.
5035 Recall that a command is anything for which `commandp' returns
5036 `t', and a command name is a symbol for which `commandp' returns
5037 `t'. *Note Interactive Call::.
5039 The argument DEFAULT-VALUE specifies what to return if the user
5040 enters null input. It can be a symbol or a string; if it is a
5041 string, `read-command' interns it before returning it. If DEFAULT
5042 is `nil', that means no default has been specified; then if the
5043 user enters null input, the return value is `nil'.
5045 (read-command "Command name? ")
5047 ;; After evaluation of the preceding expression,
5048 ;; the following prompt appears with an empty minibuffer:
5050 ---------- Buffer: Minibuffer ----------
5052 ---------- Buffer: Minibuffer ----------
5054 If the user types `forward-c <RET>', then this function returns
5057 The `read-command' function is a simplified interface to the
5058 function `completing-read'. It uses the variable `obarray' so as
5059 to complete in the set of extant Lisp symbols, and it uses the
5060 `commandp' predicate so as to accept only command names:
5062 (read-command PROMPT)
5064 (intern (completing-read PROMPT obarray
5067 -- Function: read-variable prompt &optional default-value
5068 This function reads the name of a user variable and returns it as a
5071 The argument DEFAULT-VALUE specifies what to return if the user
5072 enters null input. It can be a symbol or a string; if it is a
5073 string, `read-variable' interns it before returning it. If
5074 DEFAULT-VALUE is `nil', that means no default has been specified;
5075 then if the user enters null input, the return value is `nil'.
5077 (read-variable "Variable name? ")
5079 ;; After evaluation of the preceding expression,
5080 ;; the following prompt appears,
5081 ;; with an empty minibuffer:
5083 ---------- Buffer: Minibuffer ----------
5085 ---------- Buffer: Minibuffer ----------
5087 If the user then types `fill-p <RET>', `read-variable' returns
5090 This function is similar to `read-command', but uses the predicate
5091 `user-variable-p' instead of `commandp':
5093 (read-variable PROMPT)
5096 (completing-read PROMPT obarray
5097 'user-variable-p t nil))
5100 File: lispref.info, Node: Reading File Names, Next: Programmed Completion, Prev: High-Level Completion, Up: Completion
5102 24.5.5 Reading File Names
5103 -------------------------
5105 Here is another high-level completion function, designed for reading a
5106 file name. It provides special features including automatic insertion
5107 of the default directory.
5109 -- Function: read-file-name prompt &optional directory default
5110 existing initial history
5111 This function reads a file name in the minibuffer, prompting with
5112 PROMPT and providing completion. If DEFAULT is non-`nil', then
5113 the function returns DEFAULT if the user just types <RET>.
5114 DEFAULT is not checked for validity; it is returned, whatever it
5115 is, if the user exits with the minibuffer empty.
5117 If EXISTING is non-`nil', then the user must specify the name of
5118 an existing file; <RET> performs completion to make the name valid
5119 if possible, and then refuses to exit if it is not valid. If the
5120 value of EXISTING is neither `nil' nor `t', then <RET> also
5121 requires confirmation after completion. If EXISTING is `nil',
5122 then the name of a nonexistent file is acceptable.
5124 The argument DIRECTORY specifies the directory to use for
5125 completion of relative file names. If `insert-default-directory'
5126 is non-`nil', DIRECTORY is also inserted in the minibuffer as
5127 initial input. It defaults to the current buffer's value of
5128 `default-directory'.
5130 If you specify INITIAL, that is an initial file name to insert in
5131 the buffer (after DIRECTORY, if that is inserted). In this case,
5132 point goes at the beginning of INITIAL. The default for INITIAL
5133 is `nil'--don't insert any file name. To see what INITIAL does,
5134 try the command `C-x C-v'.
5138 (read-file-name "The file is ")
5140 ;; After evaluation of the preceding expression,
5141 ;; the following appears in the minibuffer:
5143 ---------- Buffer: Minibuffer ----------
5144 The file is /gp/gnu/elisp/-!-
5145 ---------- Buffer: Minibuffer ----------
5147 Typing `manual <TAB>' results in the following:
5149 ---------- Buffer: Minibuffer ----------
5150 The file is /gp/gnu/elisp/manual.texi-!-
5151 ---------- Buffer: Minibuffer ----------
5153 If the user types <RET>, `read-file-name' returns the file name as
5154 the string `"/gp/gnu/elisp/manual.texi"'.
5156 -- User Option: insert-default-directory
5157 This variable is used by `read-file-name'. Its value controls
5158 whether `read-file-name' starts by placing the name of the default
5159 directory in the minibuffer, plus the initial file name if any.
5160 If the value of this variable is `nil', then `read-file-name' does
5161 not place any initial input in the minibuffer (unless you specify
5162 initial input with the INITIAL argument). In that case, the
5163 default directory is still used for completion of relative file
5164 names, but is not displayed.
5168 ;; Here the minibuffer starts out with the default directory.
5169 (let ((insert-default-directory t))
5170 (read-file-name "The file is "))
5172 ---------- Buffer: Minibuffer ----------
5173 The file is ~lewis/manual/-!-
5174 ---------- Buffer: Minibuffer ----------
5176 ;; Here the minibuffer is empty and only the prompt
5177 ;; appears on its line.
5178 (let ((insert-default-directory nil))
5179 (read-file-name "The file is "))
5181 ---------- Buffer: Minibuffer ----------
5183 ---------- Buffer: Minibuffer ----------
5186 File: lispref.info, Node: Programmed Completion, Prev: Reading File Names, Up: Completion
5188 24.5.6 Programmed Completion
5189 ----------------------------
5191 Sometimes it is not possible to create an alist or an obarray
5192 containing all the intended possible completions. In such a case, you
5193 can supply your own function to compute the completion of a given
5194 string. This is called "programmed completion".
5196 To use this feature, pass a symbol with a function definition as the
5197 COLLECTION argument to `completing-read'. The function
5198 `completing-read' arranges to pass your completion function along to
5199 `try-completion' and `all-completions', which will then let your
5200 function do all the work.
5202 The completion function should accept three arguments:
5204 * The string to be completed.
5206 * The predicate function to filter possible matches, or `nil' if
5207 none. Your function should call the predicate for each possible
5208 match, and ignore the possible match if the predicate returns
5211 * A flag specifying the type of operation.
5213 There are three flag values for three operations:
5215 * `nil' specifies `try-completion'. The completion function should
5216 return the completion of the specified string, or `t' if the
5217 string is a unique and exact match already, or `nil' if the string
5218 matches no possibility.
5220 If the string is an exact match for one possibility, but also
5221 matches other longer possibilities, the function should return the
5224 * `t' specifies `all-completions'. The completion function should
5225 return a list of all possible completions of the specified string.
5227 * `lambda' specifies a test for an exact match. The completion
5228 function should return `t' if the specified string is an exact
5229 match for some possibility; `nil' otherwise.
5231 It would be consistent and clean for completion functions to allow
5232 lambda expressions (lists that are functions) as well as function
5233 symbols as COLLECTION, but this is impossible. Lists as completion
5234 tables are already assigned another meaning--as alists. It would be
5235 unreliable to fail to handle an alist normally because it is also a
5236 possible function. So you must arrange for any function you wish to
5237 use for completion to be encapsulated in a symbol.
5239 Emacs uses programmed completion when completing file names. *Note
5240 File Name Completion::.
5243 File: lispref.info, Node: Yes-or-No Queries, Next: Multiple Queries, Prev: Completion, Up: Minibuffers
5245 24.6 Yes-or-No Queries
5246 ======================
5248 This section describes functions used to ask the user a yes-or-no
5249 question. The function `y-or-n-p' can be answered with a single
5250 character; it is useful for questions where an inadvertent wrong answer
5251 will not have serious consequences. `yes-or-no-p' is suitable for more
5252 momentous questions, since it requires three or four characters to
5253 answer. Variations of these functions can be used to ask a yes-or-no
5254 question using a dialog box, or optionally using one.
5256 If either of these functions is called in a command that was invoked
5257 using the mouse, then it uses a dialog box or pop-up menu to ask the
5258 question. Otherwise, it uses keyboard input.
5260 Strictly speaking, `yes-or-no-p' uses the minibuffer and `y-or-n-p'
5261 does not; but it seems best to describe them together.
5263 -- Function: y-or-n-p prompt
5264 This function asks the user a question, expecting input in the echo
5265 area. It returns `t' if the user types `y', `nil' if the user
5266 types `n'. This function also accepts <SPC> to mean yes and <DEL>
5267 to mean no. It accepts `C-]' to mean "quit", like `C-g', because
5268 the question might look like a minibuffer and for that reason the
5269 user might try to use `C-]' to get out. The answer is a single
5270 character, with no <RET> needed to terminate it. Upper and lower
5271 case are equivalent.
5273 "Asking the question" means printing PROMPT in the echo area,
5274 followed by the string `(y or n) '. If the input is not one of
5275 the expected answers (`y', `n', `<SPC>', `<DEL>', or something
5276 that quits), the function responds `Please answer y or n.', and
5277 repeats the request.
5279 This function does not actually use the minibuffer, since it does
5280 not allow editing of the answer. It actually uses the echo area
5281 (*note The Echo Area::), which uses the same screen space as the
5282 minibuffer. The cursor moves to the echo area while the question
5285 The answers and their meanings, even `y' and `n', are not
5286 hardwired. The keymap `query-replace-map' specifies them. *Note
5287 Search and Replace::.
5289 In the following example, the user first types `q', which is
5290 invalid. At the next prompt the user types `y'.
5292 (y-or-n-p "Do you need a lift? ")
5294 ;; After evaluation of the preceding expression,
5295 ;; the following prompt appears in the echo area:
5297 ---------- Echo area ----------
5298 Do you need a lift? (y or n)
5299 ---------- Echo area ----------
5301 ;; If the user then types `q', the following appears:
5303 ---------- Echo area ----------
5304 Please answer y or n. Do you need a lift? (y or n)
5305 ---------- Echo area ----------
5307 ;; When the user types a valid answer,
5308 ;; it is displayed after the question:
5310 ---------- Echo area ----------
5311 Do you need a lift? (y or n) y
5312 ---------- Echo area ----------
5314 We show successive lines of echo area messages, but only one
5315 actually appears on the screen at a time.
5317 -- Function: yes-or-no-p prompt
5318 This function asks the user a question, expecting input in the
5319 minibuffer. It returns `t' if the user enters `yes', `nil' if the
5320 user types `no'. The user must type <RET> to finalize the
5321 response. Upper and lower case are equivalent.
5323 `yes-or-no-p' starts by displaying PROMPT in the echo area,
5324 followed by `(yes or no) '. The user must type one of the
5325 expected responses; otherwise, the function responds `Please answer
5326 yes or no.', waits about two seconds and repeats the request.
5328 `yes-or-no-p' requires more work from the user than `y-or-n-p' and
5329 is appropriate for more crucial decisions.
5333 (yes-or-no-p "Do you really want to remove everything? ")
5335 ;; After evaluation of the preceding expression,
5336 ;; the following prompt appears,
5337 ;; with an empty minibuffer:
5339 ---------- Buffer: minibuffer ----------
5340 Do you really want to remove everything? (yes or no)
5341 ---------- Buffer: minibuffer ----------
5343 If the user first types `y <RET>', which is invalid because this
5344 function demands the entire word `yes', it responds by displaying
5345 these prompts, with a brief pause between them:
5347 ---------- Buffer: minibuffer ----------
5348 Please answer yes or no.
5349 Do you really want to remove everything? (yes or no)
5350 ---------- Buffer: minibuffer ----------
5352 -- Function: yes-or-no-p-dialog-box prompt
5353 This function asks the user a "y or n" question with a popup dialog
5354 box. It returns `t' if the answer is "yes". PROMPT is the string
5355 to display to ask the question.
5357 The following functions ask a question either in the minibuffer or a
5358 dialog box, depending on whether the last user event (which presumably
5359 invoked this command) was a keyboard or mouse event. When XEmacs is
5360 running on a window system, the functions `y-or-n-p' and `yes-or-no-p'
5361 are replaced with the following functions, so that menu items bring up
5362 dialog boxes instead of minibuffer questions.
5364 -- Function: y-or-n-p-maybe-dialog-box prompt
5365 This function asks user a "y or n" question, using either a dialog
5366 box or the minibuffer, as appropriate.
5368 -- Function: yes-or-no-p-maybe-dialog-box prompt
5369 This function asks user a "yes or no" question, using either a
5370 dialog box or the minibuffer, as appropriate.
5373 File: lispref.info, Node: Multiple Queries, Next: Reading a Password, Prev: Yes-or-No Queries, Up: Minibuffers
5375 24.7 Asking Multiple Y-or-N Questions
5376 =====================================
5378 When you have a series of similar questions to ask, such as "Do you
5379 want to save this buffer" for each buffer in turn, you should use
5380 `map-y-or-n-p' to ask the collection of questions, rather than asking
5381 each question individually. This gives the user certain convenient
5382 facilities such as the ability to answer the whole series at once.
5384 -- Function: map-y-or-n-p prompter actor list &optional help
5386 This function, new in Emacs 19, asks the user a series of
5387 questions, reading a single-character answer in the echo area for
5390 The value of LIST specifies the objects to ask questions about.
5391 It should be either a list of objects or a generator function. If
5392 it is a function, it should expect no arguments, and should return
5393 either the next object to ask about, or `nil' meaning stop asking
5396 The argument PROMPTER specifies how to ask each question. If
5397 PROMPTER is a string, the question text is computed like this:
5399 (format PROMPTER OBJECT)
5401 where OBJECT is the next object to ask about (as obtained from
5404 If not a string, PROMPTER should be a function of one argument
5405 (the next object to ask about) and should return the question
5406 text. If the value is a string, that is the question to ask the
5407 user. The function can also return `t' meaning do act on this
5408 object (and don't ask the user), or `nil' meaning ignore this
5409 object (and don't ask the user).
5411 The argument ACTOR says how to act on the answers that the user
5412 gives. It should be a function of one argument, and it is called
5413 with each object that the user says yes for. Its argument is
5414 always an object obtained from LIST.
5416 If the argument HELP is given, it should be a list of this form:
5418 (SINGULAR PLURAL ACTION)
5420 where SINGULAR is a string containing a singular noun that
5421 describes the objects conceptually being acted on, PLURAL is the
5422 corresponding plural noun, and ACTION is a transitive verb
5423 describing what ACTOR does.
5425 If you don't specify HELP, the default is `("object" "objects"
5428 Each time a question is asked, the user may enter `y', `Y', or
5429 <SPC> to act on that object; `n', `N', or <DEL> to skip that
5430 object; `!' to act on all following objects; <ESC> or `q' to exit
5431 (skip all following objects); `.' (period) to act on the current
5432 object and then exit; or `C-h' to get help. These are the same
5433 answers that `query-replace' accepts. The keymap
5434 `query-replace-map' defines their meaning for `map-y-or-n-p' as
5435 well as for `query-replace'; see *Note Search and Replace::.
5437 You can use ACTION-ALIST to specify additional possible answers
5438 and what they mean. It is an alist of elements of the form `(CHAR
5439 FUNCTION HELP)', each of which defines one additional answer. In
5440 this element, CHAR is a character (the answer); FUNCTION is a
5441 function of one argument (an object from LIST); HELP is a string.
5443 When the user responds with CHAR, `map-y-or-n-p' calls FUNCTION.
5444 If it returns non-`nil', the object is considered "acted upon",
5445 and `map-y-or-n-p' advances to the next object in LIST. If it
5446 returns `nil', the prompt is repeated for the same object.
5448 If `map-y-or-n-p' is called in a command that was invoked using the
5449 mouse--more precisely, if `last-nonmenu-event' (*note Command Loop
5450 Info::) is either `nil' or a list--then it uses a dialog box or
5451 pop-up menu to ask the question. In this case, it does not use
5452 keyboard input or the echo area. You can force use of the mouse
5453 or use of keyboard input by binding `last-nonmenu-event' to a
5454 suitable value around the call.
5456 The return value of `map-y-or-n-p' is the number of objects acted
5460 File: lispref.info, Node: Reading a Password, Next: Minibuffer Misc, Prev: Multiple Queries, Up: Minibuffers
5462 24.8 Reading a Password
5463 =======================
5465 To read a password to pass to another program, you can use the function
5468 -- Function: read-passwd prompt &optional confirm default
5469 This function reads a password, prompting with PROMPT. It does
5470 not echo the password as the user types it; instead, it echoes `.'
5471 for each character in the password.
5473 The optional argument CONFIRM, if non-`nil', says to read the
5474 password twice and insist it must be the same both times. If it
5475 isn't the same, the user has to type it over and over until the
5476 last two times match.
5478 The optional argument DEFAULT specifies the default password to
5479 return if the user enters empty input. It is translated to `.'
5480 and inserted in the minibuffer. If DEFAULT is `nil', then
5481 `read-passwd' returns the null string in that case.
5483 -- User Option: passwd-invert-frame-when-keyboard-grabbed
5484 If non-`nil', swap the foreground and background colors of all
5485 faces while reading a password. Default values is `t', unless
5486 feature `infodock' is provided.
5488 -- User Option: passwd-echo
5489 This specifies the character echoed when typing a password. When
5490 `nil', nothing is echoed.
5493 File: lispref.info, Node: Minibuffer Misc, Prev: Reading a Password, Up: Minibuffers
5495 24.9 Minibuffer Miscellany
5496 ==========================
5498 This section describes some basic functions and variables related to
5501 -- Command: exit-minibuffer
5502 This command exits the active minibuffer. It is normally bound to
5503 keys in minibuffer local keymaps.
5505 -- Command: self-insert-and-exit
5506 This command exits the active minibuffer after inserting the last
5507 character typed on the keyboard (found in `last-command-char';
5508 *note Command Loop Info::).
5510 -- Command: previous-history-element n
5511 This command replaces the minibuffer contents with the value of the
5512 Nth previous (older) history element.
5514 -- Command: next-history-element n
5515 This command replaces the minibuffer contents with the value of the
5516 Nth more recent history element.
5518 -- Command: previous-matching-history-element pattern
5519 This command replaces the minibuffer contents with the value of the
5520 previous (older) history element that matches PATTERN (a regular
5523 -- Command: next-matching-history-element pattern
5524 This command replaces the minibuffer contents with the value of
5525 the next (newer) history element that matches PATTERN (a regular
5528 -- Function: minibuffer-prompt
5529 This function returns the prompt string of the currently active
5530 minibuffer. If no minibuffer is active, it returns `nil'.
5532 -- Function: minibuffer-prompt-width
5533 This function returns the display width of the prompt string of the
5534 currently active minibuffer. If no minibuffer is active, it
5537 -- Variable: minibuffer-setup-hook
5538 This is a normal hook that is run whenever the minibuffer is
5539 entered. *Note Hooks::.
5541 -- Variable: minibuffer-exit-hook
5542 This is a normal hook that is run whenever the minibuffer is
5543 exited. *Note Hooks::.
5545 -- Variable: minibuffer-help-form
5546 The current value of this variable is used to rebind `help-form'
5547 locally inside the minibuffer (*note Help Functions::).
5549 -- Function: active-minibuffer-window
5550 This function returns the currently active minibuffer window, or
5551 `nil' if none is currently active.
5553 -- Function: minibuffer-window &optional frame
5554 This function returns the minibuffer window used for frame FRAME.
5555 If FRAME is `nil', that stands for the current frame. Note that
5556 the minibuffer window used by a frame need not be part of that
5557 frame--a frame that has no minibuffer of its own necessarily uses
5558 some other frame's minibuffer window.
5560 -- Function: window-minibuffer-p &optional window
5561 This function returns non-`nil' if WINDOW is a minibuffer window.
5563 It is not correct to determine whether a given window is a
5564 minibuffer by comparing it with the result of `(minibuffer-window)',
5565 because there can be more than one minibuffer window if there is more
5568 -- Function: minibuffer-window-active-p window
5569 This function returns non-`nil' if WINDOW, assumed to be a
5570 minibuffer window, is currently active.
5572 -- Variable: minibuffer-scroll-window
5573 If the value of this variable is non-`nil', it should be a window
5574 object. When the function `scroll-other-window' is called in the
5575 minibuffer, it scrolls this window.
5577 Finally, some functions and variables deal with recursive minibuffers
5578 (*note Recursive Editing::):
5580 -- Function: minibuffer-depth
5581 This function returns the current depth of activations of the
5582 minibuffer, a nonnegative integer. If no minibuffers are active,
5585 -- User Option: enable-recursive-minibuffers
5586 If this variable is non-`nil', you can invoke commands (such as
5587 `find-file') that use minibuffers even while the minibuffer window
5588 is active. Such invocation produces a recursive editing level for
5589 a new minibuffer. The outer-level minibuffer is invisible while
5590 you are editing the inner one.
5592 This variable only affects invoking the minibuffer while the
5593 minibuffer window is selected. If you switch windows while in the
5594 minibuffer, you can always invoke minibuffer commands while some
5595 other window is selected.
5597 In FSF Emacs 19, if a command name has a property
5598 `enable-recursive-minibuffers' that is non-`nil', then the command can
5599 use the minibuffer to read arguments even if it is invoked from the
5600 minibuffer. The minibuffer command `next-matching-history-element'
5601 (normally `M-s' in the minibuffer) uses this feature.
5603 This is not implemented in XEmacs because it is a kludge. If you
5604 want to explicitly set the value of `enable-recursive-minibuffers' in
5605 this fashion, just use an evaluated interactive spec and bind
5606 `enable-recursive-minibuffers' while reading from the minibuffer. See
5607 the definition of `next-matching-history-element' in `lisp/minibuf.el'.
5610 File: lispref.info, Node: Command Loop, Next: Keymaps, Prev: Minibuffers, Up: Top
5615 When you run XEmacs, it enters the "editor command loop" almost
5616 immediately. This loop reads events, executes their definitions, and
5617 displays the results. In this chapter, we describe how these things
5618 are done, and the subroutines that allow Lisp programs to do them.
5622 * Command Overview:: How the command loop reads commands.
5623 * Defining Commands:: Specifying how a function should read arguments.
5624 * Interactive Call:: Calling a command, so that it will read arguments.
5625 * Command Loop Info:: Variables set by the command loop for you to examine.
5626 * Events:: What input looks like when you read it.
5627 * Reading Input:: How to read input events from the keyboard or mouse.
5628 * Waiting:: Waiting for user input or elapsed time.
5629 * Quitting:: How C-g works. How to catch or defer quitting.
5630 * Prefix Command Arguments:: How the commands to set prefix args work.
5631 * Recursive Editing:: Entering a recursive edit,
5632 and why you usually shouldn't.
5633 * Disabling Commands:: How the command loop handles disabled commands.
5634 * Command History:: How the command history is set up, and how accessed.
5635 * Keyboard Macros:: How keyboard macros are implemented.
5638 File: lispref.info, Node: Command Overview, Next: Defining Commands, Up: Command Loop
5640 25.1 Command Loop Overview
5641 ==========================
5643 The command loop in XEmacs is a standard event loop, reading events one
5644 at a time with `next-event' and handling them with `dispatch-event'.
5645 An event is typically a single user action, such as a keypress, mouse
5646 movement, or menu selection; but they can also be notifications from
5647 the window system, informing XEmacs that (for example) part of its
5648 window was just uncovered and needs to be redrawn. *Note Events::.
5649 Pending events are held in a first-in, first-out list called the "event
5650 queue": events are read from the head of the list, and newly arriving
5651 events are added to the tail. In this way, events are always processed
5652 in the order in which they arrive.
5654 `dispatch-event' does most of the work of handling user actions.
5655 The first thing it must do is put the events together into a key
5656 sequence, which is a sequence of events that translates into a command.
5657 It does this by consulting the active keymaps, which specify what the
5658 valid key sequences are and how to translate them into commands. *Note
5659 Key Lookup::, for information on how this is done. The result of the
5660 translation should be a keyboard macro or an interactively callable
5661 function. If the key is `M-x', then it reads the name of another
5662 command, which it then calls. This is done by the command
5663 `execute-extended-command' (*note Interactive Call::).
5665 To execute a command requires first reading the arguments for it.
5666 This is done by calling `command-execute' (*note Interactive Call::).
5667 For commands written in Lisp, the `interactive' specification says how
5668 to read the arguments. This may use the prefix argument (*note Prefix
5669 Command Arguments::) or may read with prompting in the minibuffer
5670 (*note Minibuffers::). For example, the command `find-file' has an
5671 `interactive' specification which says to read a file name using the
5672 minibuffer. The command's function body does not use the minibuffer;
5673 if you call this command from Lisp code as a function, you must supply
5674 the file name string as an ordinary Lisp function argument.
5676 If the command is a string or vector (i.e., a keyboard macro) then
5677 `execute-kbd-macro' is used to execute it. You can call this function
5678 yourself (*note Keyboard Macros::).
5680 To terminate the execution of a running command, type `C-g'. This
5681 character causes "quitting" (*note Quitting::).
5683 -- Variable: pre-command-hook
5684 The editor command loop runs this normal hook before each command.
5685 At that time, `this-command' contains the command that is about to
5686 run, and `last-command' describes the previous command. *Note
5689 -- Variable: post-command-hook
5690 The editor command loop runs this normal hook after each command.
5691 (In FSF Emacs, it is also run when the command loop is entered, or
5692 reentered after an error or quit.) At that time, `this-command'
5693 describes the command that just ran, and `last-command' describes
5694 the command before that. *Note Hooks::.
5696 Quitting is suppressed while running `pre-command-hook' and
5697 `post-command-hook'. If an error happens while executing one of these
5698 hooks, it terminates execution of the hook, but that is all it does.
5701 File: lispref.info, Node: Defining Commands, Next: Interactive Call, Prev: Command Overview, Up: Command Loop
5703 25.2 Defining Commands
5704 ======================
5706 A Lisp function becomes a command when its body contains, at top level,
5707 a form that calls the special form `interactive'. This form does
5708 nothing when actually executed, but its presence serves as a flag to
5709 indicate that interactive calling is permitted. Its argument controls
5710 the reading of arguments for an interactive call.
5714 * Using Interactive:: General rules for `interactive'.
5715 * Interactive Codes:: The standard letter-codes for reading arguments
5717 * Interactive Examples:: Examples of how to read interactive arguments.
5720 File: lispref.info, Node: Using Interactive, Next: Interactive Codes, Up: Defining Commands
5722 25.2.1 Using `interactive'
5723 --------------------------
5725 This section describes how to write the `interactive' form that makes a
5726 Lisp function an interactively-callable command.
5728 -- Special Form: interactive arg-descriptor
5729 This special form declares that the function in which it appears
5730 is a command, and that it may therefore be called interactively
5731 (via `M-x' or by entering a key sequence bound to it). The
5732 argument ARG-DESCRIPTOR declares how to compute the arguments to
5733 the command when the command is called interactively.
5735 A command may be called from Lisp programs like any other
5736 function, but then the caller supplies the arguments and
5737 ARG-DESCRIPTOR has no effect.
5739 The `interactive' form has its effect because the command loop
5740 (actually, its subroutine `call-interactively') scans through the
5741 function definition looking for it, before calling the function.
5742 Once the function is called, all its body forms including the
5743 `interactive' form are executed, but at this time `interactive'
5744 simply returns `nil' without even evaluating its argument.
5746 There are three possibilities for the argument ARG-DESCRIPTOR:
5748 * It may be omitted or `nil'; then the command is called with no
5749 arguments. This leads quickly to an error if the command requires
5750 one or more arguments.
5752 * It may be a Lisp expression that is not a string; then it should
5753 be a form that is evaluated to get a list of arguments to pass to
5756 If this expression reads keyboard input (this includes using the
5757 minibuffer), keep in mind that the integer value of point or the
5758 mark before reading input may be incorrect after reading input.
5759 This is because the current buffer may be receiving subprocess
5760 output; if subprocess output arrives while the command is waiting
5761 for input, it could relocate point and the mark.
5763 Here's an example of what _not_ to do:
5766 (list (region-beginning) (region-end)
5767 (read-string "Foo: " nil 'my-history)))
5769 Here's how to avoid the problem, by examining point and the mark
5770 only after reading the keyboard input:
5773 (let ((string (read-string "Foo: " nil 'my-history)))
5774 (list (region-beginning) (region-end) string)))
5776 * It may be a string; then its contents should consist of a code
5777 character followed by a prompt (which some code characters use and
5778 some ignore). The prompt ends either with the end of the string
5779 or with a newline. Here is a simple example:
5781 (interactive "bFrobnicate buffer: ")
5783 The code letter `b' says to read the name of an existing buffer,
5784 with completion. The buffer name is the sole argument passed to
5785 the command. The rest of the string is a prompt.
5787 If there is a newline character in the string, it terminates the
5788 prompt. If the string does not end there, then the rest of the
5789 string should contain another code character and prompt,
5790 specifying another argument. You can specify any number of
5791 arguments in this way.
5793 The prompt string can use `%' to include previous argument values
5794 (starting with the first argument) in the prompt. This is done
5795 using `format' (*note Formatting Strings::). For example, here is
5796 how you could read the name of an existing buffer followed by a
5797 new name to give to that buffer:
5799 (interactive "bBuffer to rename: \nsRename buffer %s to: ")
5801 If the first character in the string is `*', then an error is
5802 signaled if the buffer is read-only.
5804 If the first character in the string is `@', and if the key
5805 sequence used to invoke the command includes any mouse events, then
5806 the window associated with the first of those events is selected
5807 before the command is run.
5809 If the first character in the string is `_', then this command will
5810 not cause the region to be deactivated when it completes; that is,
5811 `zmacs-region-stays' will be set to `t' when the command exits
5814 You can use `*', `@', and `_' together; the order does not matter.
5815 Actual reading of arguments is controlled by the rest of the
5816 prompt string (starting with the first character that is not `*',
5819 -- Function: function-interactive function
5820 This function retrieves the interactive specification of FUNCTION,
5821 which may be any funcallable object. The specification will be
5822 returned as the list of the symbol `interactive' and the specs. If
5823 FUNCTION is not interactive, `nil' will be returned.
5826 File: lispref.info, Node: Interactive Codes, Next: Interactive Examples, Prev: Using Interactive, Up: Defining Commands
5828 25.2.2 Code Characters for `interactive'
5829 ----------------------------------------
5831 The code character descriptions below contain a number of key words,
5832 defined here as follows:
5835 Provide completion. <TAB>, <SPC>, and <RET> perform name
5836 completion because the argument is read using `completing-read'
5837 (*note Completion::). `?' displays a list of possible completions.
5840 Require the name of an existing object. An invalid name is not
5841 accepted; the commands to exit the minibuffer do not exit if the
5842 current input is not valid.
5845 A default value of some sort is used if the user enters no text in
5846 the minibuffer. The default depends on the code character.
5849 This code letter computes an argument without reading any input.
5850 Therefore, it does not use a prompt string, and any prompt string
5851 you supply is ignored.
5853 Even though the code letter doesn't use a prompt string, you must
5854 follow it with a newline if it is not the last code character in
5858 A prompt immediately follows the code character. The prompt ends
5859 either with the end of the string or with a newline.
5862 This code character is meaningful only at the beginning of the
5863 interactive string, and it does not look for a prompt or a newline.
5864 It is a single, isolated character.
5866 Here are the code character descriptions for use with `interactive':
5869 Signal an error if the current buffer is read-only. Special.
5872 Select the window mentioned in the first mouse event in the key
5873 sequence that invoked this command. Special.
5876 Do not cause the region to be deactivated when this command
5880 A function name (i.e., a symbol satisfying `fboundp'). Existing,
5884 The name of an existing buffer. By default, uses the name of the
5885 current buffer (*note Buffers::). Existing, Completion, Default,
5889 A buffer name. The buffer need not exist. By default, uses the
5890 name of a recently used buffer other than the current buffer.
5891 Completion, Default, Prompt.
5894 A character. The cursor does not move into the echo area. Prompt.
5897 A command name (i.e., a symbol satisfying `commandp'). Existing,
5901 The position of point, as an integer (*note Point::). No I/O.
5904 A directory name. The default is the current default directory of
5905 the current buffer, `default-directory' (*note System
5906 Environment::). Existing, Completion, Default, Prompt.
5909 The last mouse-button or misc-user event in the key sequence that
5910 invoked the command. No I/O.
5912 You can use `e' more than once in a single command's interactive
5913 specification. If the key sequence that invoked the command has N
5914 mouse-button or misc-user events, the Nth `e' provides the Nth
5918 A file name of an existing file (*note File Names::). The default
5919 directory is `default-directory'. Existing, Completion, Default,
5923 A file name. The file need not exist. Completion, Default,
5927 A key sequence (*note Keymap Terminology::). This keeps reading
5928 events until a command (or undefined command) is found in the
5929 current key maps. The key sequence argument is represented as a
5930 vector of events. The cursor does not move into the echo area.
5933 This kind of input is used by commands such as `describe-key' and
5937 A key sequence, whose definition you intend to change. This works
5938 like `k', except that it suppresses, for the last input event in
5939 the key sequence, the conversions that are normally used (when
5940 necessary) to convert an undefined key into a defined one.
5943 The position of the mark, as an integer. No I/O.
5946 A number read with the minibuffer. If the input is not a number,
5947 the user is asked to try again. The prefix argument, if any, is
5951 The raw prefix argument. If the prefix argument is `nil', then
5952 read a number as with `n'. Requires a number. *Note Prefix
5953 Command Arguments::. Prompt.
5956 The numeric prefix argument. (Note that this `p' is lower case.)
5960 The raw prefix argument. (Note that this `P' is upper case.) No
5964 Point and the mark, as two numeric arguments, smallest first.
5965 This is the only code letter that specifies two successive
5966 arguments rather than one. No I/O.
5969 Arbitrary text, read in the minibuffer and returned as a string
5970 (*note Text from Minibuffer::). Terminate the input with either
5971 <LFD> or <RET>. (`C-q' may be used to include either of these
5972 characters in the input.) Prompt.
5975 An interned symbol whose name is read in the minibuffer. Any
5976 whitespace character terminates the input. (Use `C-q' to include
5977 whitespace in the string.) Other characters that normally
5978 terminate a symbol (e.g., parentheses and brackets) do not do so
5982 A variable declared to be a user option (i.e., satisfying the
5983 predicate `user-variable-p'). *Note High-Level Completion::.
5984 Existing, Completion, Prompt.
5987 A Lisp object, specified with its read syntax, terminated with a
5988 <LFD> or <RET>. The object is not evaluated. *Note Object from
5989 Minibuffer::. Prompt.
5992 A Lisp form is read as with `x', but then evaluated so that its
5993 value becomes the argument for the command. Prompt.
5996 File: lispref.info, Node: Interactive Examples, Prev: Interactive Codes, Up: Defining Commands
5998 25.2.3 Examples of Using `interactive'
5999 --------------------------------------
6001 Here are some examples of `interactive':
6003 (defun foo1 () ; `foo1' takes no arguments,
6004 (interactive) ; just moves forward two words.
6008 (defun foo2 (n) ; `foo2' takes one argument,
6009 (interactive "p") ; which is the numeric prefix.
6010 (forward-word (* 2 n)))
6013 (defun foo3 (n) ; `foo3' takes one argument,
6014 (interactive "nCount:") ; which is read with the Minibuffer.
6015 (forward-word (* 2 n)))
6018 (defun three-b (b1 b2 b3)
6019 "Select three existing buffers.
6020 Put them into three windows, selecting the last one."
6021 (interactive "bBuffer1:\nbBuffer2:\nbBuffer3:")
6022 (delete-other-windows)
6023 (split-window (selected-window) 8)
6024 (switch-to-buffer b1)
6026 (split-window (selected-window) 8)
6027 (switch-to-buffer b2)
6029 (switch-to-buffer b3))
6031 (three-b "*scratch*" "declarations.texi" "*mail*")
6035 File: lispref.info, Node: Interactive Call, Next: Command Loop Info, Prev: Defining Commands, Up: Command Loop
6037 25.3 Interactive Call
6038 =====================
6040 After the command loop has translated a key sequence into a definition,
6041 it invokes that definition using the function `command-execute'. If
6042 the definition is a function that is a command, `command-execute' calls
6043 `call-interactively', which reads the arguments and calls the command.
6044 You can also call these functions yourself.
6046 -- Function: commandp function
6047 Returns `t' if FUNCTION is suitable for calling interactively;
6048 that is, if FUNCTION is a command. Otherwise, returns `nil'.
6050 The interactively callable objects include strings and vectors
6051 (treated as keyboard macros), lambda expressions that contain a
6052 top-level call to `interactive', compiled-function objects made
6053 from such lambda expressions, autoload objects that are declared
6054 as interactive (non-`nil' fourth argument to `autoload'), and some
6055 of the primitive functions.
6057 A symbol is `commandp' if its function definition is `commandp'.
6059 Keys and keymaps are not commands. Rather, they are used to look
6060 up commands (*note Keymaps::).
6062 See `documentation' in *Note Accessing Documentation::, for a
6063 realistic example of using `commandp'.
6065 -- Function: call-interactively command &optional record-flag keys
6066 This function calls the interactively callable function COMMAND,
6067 reading arguments according to its interactive calling
6068 specifications. An error is signaled if COMMAND is not a function
6069 or if it cannot be called interactively (i.e., is not a command).
6070 Note that keyboard macros (strings and vectors) are not accepted,
6071 even though they are considered commands, because they are not
6074 If RECORD-FLAG is the symbol `lambda', the interactive calling
6075 arguments for COMMAND are read and returned as a list, but the
6076 function is not called on them.
6078 If RECORD-FLAG is `t', then this command and its arguments are
6079 unconditionally added to the list `command-history'. Otherwise,
6080 the command is added only if it uses the minibuffer to read an
6081 argument. *Note Command History::.
6083 -- Function: command-execute command &optional record-flag keys
6084 This function executes COMMAND as an editing command. The
6085 argument COMMAND must satisfy the `commandp' predicate; i.e., it
6086 must be an interactively callable function or a keyboard macro.
6088 A string or vector as COMMAND is executed with
6089 `execute-kbd-macro'. A function is passed to
6090 `call-interactively', along with the optional RECORD-FLAG.
6092 A symbol is handled by using its function definition in its place.
6093 A symbol with an `autoload' definition counts as a command if it
6094 was declared to stand for an interactively callable function.
6095 Such a definition is handled by loading the specified library and
6096 then rechecking the definition of the symbol.
6098 -- Command: execute-extended-command prefix-argument
6099 This function reads a command name from the minibuffer using
6100 `completing-read' (*note Completion::). Then it uses
6101 `command-execute' to call the specified command. Whatever that
6102 command returns becomes the value of `execute-extended-command'.
6104 If the command asks for a prefix argument, it receives the value
6105 PREFIX-ARGUMENT. If `execute-extended-command' is called
6106 interactively, the current raw prefix argument is used for
6107 PREFIX-ARGUMENT, and thus passed on to whatever command is run.
6109 `execute-extended-command' is the normal definition of `M-x', so
6110 it uses the string `M-x ' as a prompt. (It would be better to
6111 take the prompt from the events used to invoke
6112 `execute-extended-command', but that is painful to implement.) A
6113 description of the value of the prefix argument, if any, also
6114 becomes part of the prompt.
6116 (execute-extended-command 1)
6117 ---------- Buffer: Minibuffer ----------
6118 1 M-x forward-word RET
6119 ---------- Buffer: Minibuffer ----------
6122 -- Function: interactive-p
6123 This function returns `t' if the containing function (the one that
6124 called `interactive-p') was called interactively, with the function
6125 `call-interactively'. (It makes no difference whether
6126 `call-interactively' was called from Lisp or directly from the
6127 editor command loop.) If the containing function was called by
6128 Lisp evaluation (or with `apply' or `funcall'), then it was not
6129 called interactively.
6131 The most common use of `interactive-p' is for deciding whether to
6132 print an informative message. As a special exception,
6133 `interactive-p' returns `nil' whenever a keyboard macro is being
6134 run. This is to suppress the informative messages and speed
6135 execution of the macro.
6141 (and (interactive-p)
6147 (setq foobar (list (foo) (interactive-p))))
6154 ;; This does not print anything.
6160 File: lispref.info, Node: Command Loop Info, Next: Events, Prev: Interactive Call, Up: Command Loop
6162 25.4 Information from the Command Loop
6163 ======================================
6165 The editor command loop sets several Lisp variables to keep status
6166 records for itself and for commands that are run.
6168 -- Variable: last-command
6169 This variable records the name of the previous command executed by
6170 the command loop (the one before the current command). Normally
6171 the value is a symbol with a function definition, but this is not
6174 The value is copied from `this-command' when a command returns to
6175 the command loop, except when the command specifies a prefix
6176 argument for the following command.
6178 -- Variable: this-command
6179 This variable records the name of the command now being executed by
6180 the editor command loop. Like `last-command', it is normally a
6181 symbol with a function definition.
6183 The command loop sets this variable just before running a command,
6184 and copies its value into `last-command' when the command finishes
6185 (unless the command specifies a prefix argument for the following
6188 Some commands set this variable during their execution, as a flag
6189 for whatever command runs next. In particular, the functions for
6190 killing text set `this-command' to `kill-region' so that any kill
6191 commands immediately following will know to append the killed text
6192 to the previous kill.
6194 If you do not want a particular command to be recognized as the
6195 previous command in the case where it got an error, you must code that
6196 command to prevent this. One way is to set `this-command' to `t' at the
6197 beginning of the command, and set `this-command' back to its proper
6198 value at the end, like this:
6200 (defun foo (args...)
6202 (let ((old-this-command this-command))
6203 (setq this-command t)
6205 (setq this-command old-this-command)))
6207 -- Function: this-command-keys
6208 This function returns a vector containing the key and mouse events
6209 that invoked the present command, plus any previous commands that
6210 generated the prefix argument for this command. (Note: this is not
6211 the same as in FSF Emacs, which can return a string.) *Note
6214 This function copies the vector and the events; it is safe to keep
6218 ;; Now use `C-u C-x C-e' to evaluate that.
6219 => [#<keypress-event control-U> #<keypress-event control-X> #<keypress-event control-E>]
6221 -- Variable: last-command-event
6222 This variable is set to the last input event that was read by the
6223 command loop as part of a command. The principal use of this
6224 variable is in `self-insert-command', which uses it to decide which
6225 character to insert.
6227 This variable is off limits: you may not set its value or modify
6228 the event that is its value, as it is destructively modified by
6229 `read-key-sequence'. If you want to keep a pointer to this value,
6230 you must use `copy-event'.
6232 Note that this variable is an alias for `last-command-char' in FSF
6236 ;; Now type `C-u C-x C-e'.
6237 => #<keypress-event control-E>
6239 -- Variable: last-command-char
6240 If the value of `last-command-event' is a keyboard event, then this
6241 is the nearest character equivalent to it (or `nil' if there is no
6242 character equivalent). `last-command-char' is the character that
6243 `self-insert-command' will insert in the buffer. Remember that
6244 there is _not_ a one-to-one mapping between keyboard events and
6245 XEmacs characters: many keyboard events have no corresponding
6246 character, and when the Mule feature is available, most characters
6247 can not be input on standard keyboards, except possibly with help
6248 from an input method. So writing code that examines this variable
6249 to determine what key has been typed is bad practice, unless you
6250 are certain that it will be one of a small set of characters.
6252 This variable exists for compatibility with Emacs version 18.
6255 ;; Now use `C-u C-x C-e' to evaluate that.
6259 -- Variable: current-mouse-event
6260 This variable holds the mouse-button event which invoked this
6261 command, or `nil'. This is what `(interactive "e")' returns.
6263 -- Variable: echo-keystrokes
6264 This variable determines how much time should elapse before command
6265 characters echo. Its value must be an integer, which specifies the
6266 number of seconds to wait before echoing. If the user types a
6267 prefix key (say `C-x') and then delays this many seconds before
6268 continuing, the key `C-x' is echoed in the echo area. Any
6269 subsequent characters in the same command will be echoed as well.
6271 If the value is zero, then command input is not echoed.
6274 File: lispref.info, Node: Events, Next: Reading Input, Prev: Command Loop Info, Up: Command Loop
6279 The XEmacs command loop reads a sequence of "events" that represent
6280 keyboard or mouse activity. Unlike in Emacs 18 and in FSF Emacs,
6281 events are a primitive Lisp type that must be manipulated using their
6282 own accessor and settor primitives. This section describes the
6283 representation and meaning of input events in detail.
6285 A key sequence that starts with a mouse event is read using the
6286 keymaps of the buffer in the window that the mouse was in, not the
6287 current buffer. This does not imply that clicking in a window selects
6288 that window or its buffer--that is entirely under the control of the
6289 command binding of the key sequence.
6291 For information about how exactly the XEmacs command loop works,
6292 *Note Reading Input::.
6294 -- Function: eventp object
6295 This function returns non-`nil' if OBJECT is an input event.
6299 * Event Types:: Events come in different types.
6300 * Event Contents:: What the contents of each event type are.
6301 * Event Predicates:: Querying whether an event is of a
6303 * Accessing Mouse Event Positions::
6304 Determining where a mouse event occurred,
6306 * Accessing Other Event Info:: Accessing non-positional event info.
6307 * Working With Events:: Creating, copying, and destroying events.
6308 * Converting Events:: Converting between events, keys, and
6312 File: lispref.info, Node: Event Types, Next: Event Contents, Up: Events
6317 Events represent keyboard or mouse activity or status changes of various
6318 sorts, such as process input being available or a timeout being
6319 triggered. The different event types are as follows:
6322 A key was pressed. Note that modifier keys such as "control",
6323 "shift", and "alt" do not generate events; instead, they are
6324 tracked internally by XEmacs, and non-modifier key presses
6325 generate events that specify both the key pressed and the
6326 modifiers that were held down at the time.
6329 button-release event
6330 A button was pressed or released. Along with the button that was
6331 pressed or released, button events specify the modifier keys that
6332 were held down at the time and the position of the pointer at the
6336 The pointer was moved. Along with the position of the pointer,
6337 these events also specify the modifier keys that were held down at
6341 A menu item was selected, the scrollbar was used, or a drag or a
6345 Input is available on a process.
6348 A timeout has triggered.
6351 Some window-system-specific action (such as a frame being resized
6352 or a portion of a frame needing to be redrawn) has occurred. The
6353 contents of this event are not accessible at the E-Lisp level, but
6354 `dispatch-event' knows what to do with an event of this type.
6357 This is a special kind of event specifying that a particular
6358 function needs to be called when this event is dispatched. An
6359 event of this type is sometimes placed in the event queue when a
6360 magic event is processed. This kind of event should generally
6361 just be passed off to `dispatch-event'. *Note Dispatching an
6365 File: lispref.info, Node: Event Contents, Next: Event Predicates, Prev: Event Types, Up: Events
6367 25.5.2 Contents of the Different Types of Events
6368 ------------------------------------------------
6370 Every event, no matter what type it is, contains a timestamp (which is
6371 typically an offset in milliseconds from when the X server was started)
6372 indicating when the event occurred. In addition, many events contain a
6373 "channel", which specifies which frame the event occurred on, and/or a
6374 value indicating which modifier keys (shift, control, etc.) were held
6375 down at the time of the event.
6377 The contents of each event are as follows:
6386 Which key was pressed. This is an integer (in the printing
6387 ASCII range: >32 and <127) or a symbol such as `left' or
6388 `right'. Note that many physical keys are actually treated
6389 as two separate keys, depending on whether the shift key is
6390 pressed; for example, the "a" key is treated as either "a" or
6391 "A" depending on the state of the shift key, and the "1" key
6392 is similarly treated as either "1" or "!" on most keyboards.
6393 In such cases, the shift key does not show up in the modifier
6394 list. For other keys, such as `backspace', the shift key
6395 shows up as a regular modifier.
6398 Which modifier keys were pressed. As mentioned above, the
6399 shift key is not treated as a modifier for many keys and will
6400 not show up in this list in such cases.
6403 button-release event
6410 What button went down or up. Buttons are numbered starting
6414 Which modifier keys were pressed. The special business
6415 mentioned above for the shift key does _not_ apply to mouse
6420 The position of the pointer (in pixels) at the time of the
6423 pointer-motion event
6431 The position of the pointer (in pixels) after it moved.
6434 Which modifier keys were pressed. The special business
6435 mentioned above for the shift key does _not_ apply to mouse
6443 The E-Lisp function to call for this event. This is normally
6444 either `eval' or `call-interactively'.
6447 The object to pass to the function. This is normally the
6448 callback that was specified in the menu description.
6451 What button went down or up. Buttons are numbered starting
6455 Which modifier keys were pressed. The special business
6456 mentioned above for the shift key does _not_ apply to mouse
6461 The position of the pointer (in pixels) at the time of the
6469 The Emacs "process" object in question.
6476 The E-Lisp function to call for this timeout. It is called
6477 with one argument, the event.
6480 Some Lisp object associated with this timeout, to make it
6481 easier to tell them apart. The function and object for this
6482 event were specified when the timeout was set.
6487 (The rest of the information in this event is not user-accessible.)
6494 An E-Lisp function to call when this event is dispatched.
6497 The object to pass to the function. The function and object
6498 are set when the event is created.
6500 -- Function: event-type event
6501 Return the type of EVENT.
6503 This will be a symbol; one of
6509 A mouse button was pressed.
6512 A mouse button was released.
6518 Some other user action happened; typically, this is a menu
6519 selection, scrollbar action, or drag and drop action.
6522 Input is available from a subprocess.
6525 A timeout has expired.
6528 This causes a specified action to occur when dispatched.
6531 Some window-system-specific event has occurred.
6534 File: lispref.info, Node: Event Predicates, Next: Accessing Mouse Event Positions, Prev: Event Contents, Up: Events
6536 25.5.3 Event Predicates
6537 -----------------------
6539 The following predicates return whether an object is an event of a
6542 -- Function: key-press-event-p object
6543 This is true if OBJECT is a key-press event.
6545 -- Function: button-event-p object
6546 This is true if OBJECT is a mouse button-press or button-release
6549 -- Function: button-press-event-p object
6550 This is true if OBJECT is a mouse button-press event.
6552 -- Function: button-release-event-p object
6553 This is true if OBJECT is a mouse button-release event.
6555 -- Function: motion-event-p object
6556 This is true if OBJECT is a mouse motion event.
6558 -- Function: mouse-event-p object
6559 This is true if OBJECT is a mouse button-press, button-release or
6562 -- Function: eval-event-p object
6563 This is true if OBJECT is an eval event.
6565 -- Function: misc-user-event-p object
6566 This is true if OBJECT is a misc-user event.
6568 -- Function: process-event-p object
6569 This is true if OBJECT is a process event.
6571 -- Function: timeout-event-p object
6572 This is true if OBJECT is a timeout event.
6574 -- Function: event-live-p object
6575 This is true if OBJECT is any event that has not been deallocated.
6578 File: lispref.info, Node: Accessing Mouse Event Positions, Next: Accessing Other Event Info, Prev: Event Predicates, Up: Events
6580 25.5.4 Accessing the Position of a Mouse Event
6581 ----------------------------------------------
6583 Unlike other events, mouse events (i.e. motion, button-press,
6584 button-release, and drag or drop type misc-user events) occur in a
6585 particular location on the screen. Many primitives are provided for
6586 determining exactly where the event occurred and what is under that
6591 * Frame-Level Event Position Info::
6592 * Window-Level Event Position Info::
6593 * Event Text Position Info::
6594 * Event Glyph Position Info::
6595 * Event Toolbar Position Info::
6596 * Other Event Position Info::
6599 File: lispref.info, Node: Frame-Level Event Position Info, Next: Window-Level Event Position Info, Up: Accessing Mouse Event Positions
6601 25.5.4.1 Frame-Level Event Position Info
6602 ........................................
6604 The following functions return frame-level information about where a
6605 mouse event occurred.
6607 -- Function: event-frame event
6608 This function returns the "channel" or frame that the given mouse
6609 motion, button press, button release, or misc-user event occurred
6610 in. This will be `nil' for non-mouse events.
6612 -- Function: event-x-pixel event
6613 This function returns the X position in pixels of the given mouse
6614 event. The value returned is relative to the frame the event
6615 occurred in. This will signal an error if the event is not a
6618 -- Function: event-y-pixel event
6619 This function returns the Y position in pixels of the given mouse
6620 event. The value returned is relative to the frame the event
6621 occurred in. This will signal an error if the event is not a
6625 File: lispref.info, Node: Window-Level Event Position Info, Next: Event Text Position Info, Prev: Frame-Level Event Position Info, Up: Accessing Mouse Event Positions
6627 25.5.4.2 Window-Level Event Position Info
6628 .........................................
6630 The following functions return window-level information about where a
6631 mouse event occurred.
6633 -- Function: event-window event
6634 Given a mouse motion, button press, button release, or misc-user
6635 event, compute and return the window on which that event occurred.
6636 This may be `nil' if the event occurred in the border or over a
6637 toolbar. The modeline is considered to be within the window it
6640 -- Function: event-buffer event
6641 Given a mouse motion, button press, button release, or misc-user
6642 event, compute and return the buffer of the window on which that
6643 event occurred. This may be `nil' if the event occurred in the
6644 border or over a toolbar. The modeline is considered to be within
6645 the window it describes. This is equivalent to calling
6646 `event-window' and then calling `window-buffer' on the result if
6649 -- Function: event-window-x-pixel event
6650 This function returns the X position in pixels of the given mouse
6651 event. The value returned is relative to the window the event
6652 occurred in. This will signal an error if the event is not a
6653 mouse-motion, button-press, button-release, or misc-user event.
6655 -- Function: event-window-y-pixel event
6656 This function returns the Y position in pixels of the given mouse
6657 event. The value returned is relative to the window the event
6658 occurred in. This will signal an error if the event is not a
6659 mouse-motion, button-press, button-release, or misc-user event.
6662 File: lispref.info, Node: Event Text Position Info, Next: Event Glyph Position Info, Prev: Window-Level Event Position Info, Up: Accessing Mouse Event Positions
6664 25.5.4.3 Event Text Position Info
6665 .................................
6667 The following functions return information about the text (including the
6668 modeline) that a mouse event occurred over or near.
6670 -- Function: event-over-text-area-p event
6671 Given a mouse-motion, button-press, button-release, or misc-user
6672 event, this function returns `t' if the event is over the text
6673 area of a window. Otherwise, `nil' is returned. The modeline is
6674 not considered to be part of the text area.
6676 -- Function: event-over-modeline-p event
6677 Given a mouse-motion, button-press, button-release, or misc-user
6678 event, this function returns `t' if the event is over the modeline
6679 of a window. Otherwise, `nil' is returned.
6681 -- Function: event-x event
6682 This function returns the X position of the given mouse-motion,
6683 button-press, button-release, or misc-user event in characters.
6684 This is relative to the window the event occurred over.
6686 -- Function: event-y event
6687 This function returns the Y position of the given mouse-motion,
6688 button-press, button-release, or misc-user event in characters.
6689 This is relative to the window the event occurred over.
6691 -- Function: event-point event
6692 This function returns the character position of the given
6693 mouse-motion, button-press, button-release, or misc-user event.
6694 If the event did not occur over a window, or did not occur over
6695 text, then this returns `nil'. Otherwise, it returns an index
6696 into the buffer visible in the event's window.
6698 -- Function: event-closest-point event
6699 This function returns the character position of the given
6700 mouse-motion, button-press, button-release, or misc-user event.
6701 If the event did not occur over a window or over text, it returns
6702 the closest point to the location of the event. If the Y pixel
6703 position overlaps a window and the X pixel position is to the left
6704 of that window, the closest point is the beginning of the line
6705 containing the Y position. If the Y pixel position overlaps a
6706 window and the X pixel position is to the right of that window,
6707 the closest point is the end of the line containing the Y
6708 position. If the Y pixel position is above a window, 0 is
6709 returned. If it is below a window, the value of `(window-end)' is
6713 File: lispref.info, Node: Event Glyph Position Info, Next: Event Toolbar Position Info, Prev: Event Text Position Info, Up: Accessing Mouse Event Positions
6715 25.5.4.4 Event Glyph Position Info
6716 ..................................
6718 The following functions return information about the glyph (if any) that
6719 a mouse event occurred over.
6721 -- Function: event-over-glyph-p event
6722 Given a mouse-motion, button-press, button-release, or misc-user
6723 event, this function returns `t' if the event is over a glyph.
6724 Otherwise, `nil' is returned.
6726 -- Function: event-glyph-extent event
6727 If the given mouse-motion, button-press, button-release, or
6728 misc-user event happened on top of a glyph, this returns its
6729 extent; else `nil' is returned.
6731 -- Function: event-glyph-x-pixel event
6732 Given a mouse-motion, button-press, button-release, or misc-user
6733 event over a glyph, this function returns the X position of the
6734 pointer relative to the upper left of the glyph. If the event is
6735 not over a glyph, it returns `nil'.
6737 -- Function: event-glyph-y-pixel event
6738 Given a mouse-motion, button-press, button-release, or misc-user
6739 event over a glyph, this function returns the Y position of the
6740 pointer relative to the upper left of the glyph. If the event is
6741 not over a glyph, it returns `nil'.
6744 File: lispref.info, Node: Event Toolbar Position Info, Next: Other Event Position Info, Prev: Event Glyph Position Info, Up: Accessing Mouse Event Positions
6746 25.5.4.5 Event Toolbar Position Info
6747 ....................................
6749 -- Function: event-over-toolbar-p event
6750 Given a mouse-motion, button-press, button-release, or misc-user
6751 event, this function returns `t' if the event is over a toolbar.
6752 Otherwise, `nil' is returned.
6754 -- Function: event-toolbar-button event
6755 If the given mouse-motion, button-press, button-release, or
6756 misc-user event happened on top of a toolbar button, this function
6757 returns the button. Otherwise, `nil' is returned.
6760 File: lispref.info, Node: Other Event Position Info, Prev: Event Toolbar Position Info, Up: Accessing Mouse Event Positions
6762 25.5.4.6 Other Event Position Info
6763 ..................................
6765 -- Function: event-over-border-p event
6766 Given a mouse-motion, button-press, button-release, or misc-user
6767 event, this function returns `t' if the event is over an internal
6768 toolbar. Otherwise, `nil' is returned.
6771 File: lispref.info, Node: Accessing Other Event Info, Next: Working With Events, Prev: Accessing Mouse Event Positions, Up: Events
6773 25.5.5 Accessing the Other Contents of Events
6774 ---------------------------------------------
6776 The following functions allow access to the contents of events other
6777 than the position info described in the previous section.
6779 -- Function: event-timestamp event
6780 This function returns the timestamp of the given event object.
6782 -- Function: event-device event
6783 This function returns the device that the given event occurred on.
6785 -- Function: event-key event
6786 This function returns the Keysym of the given key-press event.
6787 This will be the ASCII code of a printing character, or a symbol.
6789 -- Function: event-button event
6790 This function returns the button-number of the given button-press
6791 or button-release event.
6793 -- Function: event-modifiers event
6794 This function returns a list of symbols, the names of the modifier
6795 keys which were down when the given mouse or keyboard event was
6798 -- Function: event-modifier-bits event
6799 This function returns a number representing the modifier keys
6800 which were down when the given mouse or keyboard event was
6803 -- Function: event-function event
6804 This function returns the callback function of the given timeout,
6805 misc-user, or eval event.
6807 -- Function: event-object event
6808 This function returns the callback function argument of the given
6809 timeout, misc-user, or eval event.
6811 -- Function: event-process event
6812 This function returns the process of the given process event.
6815 File: lispref.info, Node: Working With Events, Next: Converting Events, Prev: Accessing Other Event Info, Up: Events
6817 25.5.6 Working With Events
6818 --------------------------
6820 XEmacs provides primitives for creating, copying, and destroying event
6821 objects. Many functions that return events take an event object as an
6822 argument and fill in the fields of this event; or they make accept
6823 either an event object or `nil', creating the event object first in the
6826 -- Function: make-event &optional type plist
6827 This function creates a new event structure. If no arguments are
6828 specified, the created event will be empty. To specify the event
6829 type, use the TYPE argument. The allowed types are `empty',
6830 `key-press', `button-press', `button-release', `motion', or
6833 PLIST is a property list, the properties being compatible to those
6834 returned by `event-properties'. For events other than `empty', it
6835 is mandatory to specify certain properties. For `empty' events,
6836 PLIST must be `nil'. The list is "canonicalized", which means
6837 that if a property keyword is present more than once, only the
6838 first instance is taken into account. Specifying an unknown or
6839 illegal property signals an error.
6841 The following properties are allowed:
6844 The event channel. This is a frame or a console. For mouse
6845 events (of type `button-press', `button-release' and
6846 `motion'), this must be a frame. For key-press events, it
6847 must be a console. If channel is unspecified by PLIST, it
6848 will be set to the selected frame or selected console, as
6852 The event key. This is either a symbol or a character. It
6853 is allowed (and required) only for key-press events.
6856 The event button. This an integer, either 1, 2 or 3. It is
6857 allowed only for button-press and button-release events.
6860 The event modifiers. This is a list of modifier symbols. It
6861 is allowed for key-press, button-press, button-release and
6865 The event X coordinate. This is an integer. It is relative
6866 to the channel's root window, and is allowed for
6867 button-press, button-release and motion events.
6870 The event Y coordinate. This is an integer. It is relative
6871 to the channel's root window, and is allowed for
6872 button-press, button-release and motion events. This means
6873 that, for instance, to access the toolbar, the `y' property
6874 will have to be negative.
6877 The event timestamp, a non-negative integer. Allowed for all
6880 _WARNING_: the event object returned by this function may be a
6881 reused one; see the function `deallocate-event'.
6883 The events created by `make-event' can be used as non-interactive
6884 arguments to the functions with an `(interactive "e")'
6887 Here are some basic examples of usage:
6889 ;; Create an empty event.
6893 ;; Try creating a key-press event.
6894 (make-event 'key-press)
6895 error--> Undefined key for keypress event
6897 ;; Creating a key-press event, try 2
6898 (make-event 'key-press '(key home))
6899 => #<keypress-event home>
6901 ;; Create a key-press event of dubious fame.
6902 (make-event 'key-press '(key escape modifiers (meta alt control shift)))
6903 => #<keypress-event control-meta-alt-shift-escape>
6905 ;; Create a M-button1 event at coordinates defined by variables
6907 (make-event 'button-press `(button 1 modifiers (meta) x ,x y ,y))
6908 => #<buttondown-event meta-button1>
6910 ;; Create a similar button-release event.
6911 (make-event 'button-release `(button 1 modifiers (meta) x ,x y ,x))
6912 => #<buttonup-event meta-button1up>
6914 ;; Create a mouse-motion event.
6915 (make-event 'motion '(x 20 y 30))
6916 => #<motion-event 20, 30>
6918 (event-properties (make-event 'motion '(x 20 y 30)))
6919 => (channel #<x-frame "emacs" 0x8e2> x 20 y 30
6920 modifiers nil timestamp 0)
6922 In conjunction with `event-properties', you can use `make-event'
6923 to create modified copies of existing events. For instance, the
6924 following code will return an `equal' copy of EVENT:
6926 (make-event (event-type EVENT)
6927 (event-properties EVENT))
6929 Note, however, that you cannot use `make-event' as the generic
6930 replacement for `copy-event', because it does not allow creating
6931 all of the event types.
6933 To create a modified copy of an event, you can use the
6934 canonicalization feature of PLIST. The following example creates
6935 a copy of EVENT, but with `modifiers' reset to `nil'.
6937 (make-event (event-type EVENT)
6938 (append '(modifiers nil)
6939 (event-properties EVENT)))
6941 -- Function: copy-event event1 &optional event2
6942 This function makes a copy of the event object EVENT1. If a
6943 second event argument EVENT2 is given, EVENT1 is copied into
6944 EVENT2 and EVENT2 is returned. If EVENT2 is not supplied (or is
6945 `nil') then a new event will be made, as with `make-event'.
6947 -- Function: deallocate-event event
6948 This function allows the given event structure to be reused. You
6949 *MUST NOT* use this event object after calling this function with
6950 it. You will lose. It is not necessary to call this function, as
6951 event objects are garbage-collected like all other objects;
6952 however, it may be more efficient to explicitly deallocate events
6953 when you are sure that it is safe to do so.
6956 File: lispref.info, Node: Converting Events, Prev: Working With Events, Up: Events
6958 25.5.7 Converting Events
6959 ------------------------
6961 XEmacs provides some auxiliary functions for converting between events
6962 and other ways of representing keys. These are useful when working with
6963 ASCII strings and with keymaps.
6965 -- Function: character-to-event key-description &optional event
6966 console use-console-meta-flag
6967 This function converts a keystroke description to an event
6968 structure. KEY-DESCRIPTION is the specification of a key stroke,
6969 and EVENT is the event object to fill in. This function contains
6970 knowledge about what the codes "mean"--for example, the number 9 is
6971 converted to the character <Tab>, not the distinct character
6974 Note that KEY-DESCRIPTION can be an integer, a character, a symbol
6975 such as `clear' or a list such as `(control backspace)'.
6977 If optional arg EVENT is non-`nil', it is modified; otherwise, a
6978 new event object is created. In both cases, the event is returned.
6980 Optional third arg CONSOLE is the console to store in the event,
6981 and defaults to the selected console.
6983 If KEY-DESCRIPTION is an integer or character, the high bit may be
6984 interpreted as the meta key. (This is done for backward
6985 compatibility in lots of places.) If USE-CONSOLE-META-FLAG is
6986 `nil', this will always be the case. If USE-CONSOLE-META-FLAG is
6987 non-`nil', the `meta' flag for CONSOLE affects whether the high
6988 bit is interpreted as a meta key. (See `set-input-mode'.) If you
6989 don't want this silly meta interpretation done, you should pass in
6990 a list containing the character.
6992 Beware that `character-to-event' and `event-to-character' are not
6993 strictly inverse functions, since events contain much more
6994 information than the ASCII character set can encode.
6996 -- Function: event-to-character event &optional allow-extra-modifiers
6997 allow-meta allow-non-ascii
6998 This function returns the closest ASCII approximation to EVENT.
6999 If the event isn't a keypress, this returns `nil'.
7001 If ALLOW-EXTRA-MODIFIERS is non-`nil', then this is lenient in its
7002 translation; it will ignore modifier keys other than <control> and
7003 <meta>, and will ignore the <shift> modifier on those characters
7004 which have no shifted ASCII equivalent (<Control-Shift-A> for
7005 example, will be mapped to the same ASCII code as <Control-A>).
7007 If ALLOW-META is non-`nil', then the <Meta> modifier will be
7008 represented by turning on the high bit of the byte returned;
7009 otherwise, `nil' will be returned for events containing the <Meta>
7012 If ALLOW-NON-ASCII is non-`nil', then characters which are present
7013 in the prevailing character set (*note variable
7014 `character-set-property': Keymaps.) will be returned as their code
7015 in that character set, instead of the return value being
7016 restricted to ASCII.
7018 Note that specifying both ALLOW-META and ALLOW-NON-ASCII is
7019 ambiguous, as both use the high bit; <M-x> and <oslash> will be
7022 -- Function: events-to-keys events &optional no-mice
7023 Given a vector of event objects, this function returns a vector of
7024 key descriptors, or a string (if they all fit in the ASCII range).
7025 Optional arg NO-MICE means that button events are not allowed.
7028 File: lispref.info, Node: Reading Input, Next: Waiting, Prev: Events, Up: Command Loop
7033 The editor command loop reads keyboard input using the function
7034 `next-event' and constructs key sequences out of the events using
7035 `dispatch-event'. Lisp programs can also use the function
7036 `read-key-sequence', which reads input a key sequence at a time. See
7037 also `momentary-string-display' in *Note Temporary Displays::, and
7038 `sit-for' in *Note Waiting::. *Note Terminal Input::, for functions
7039 and variables for controlling terminal input modes and debugging
7042 For higher-level input facilities, see *Note Minibuffers::.
7046 * Key Sequence Input:: How to read one key sequence.
7047 * Reading One Event:: How to read just one event.
7048 * Dispatching an Event:: What to do with an event once it has been read.
7049 * Quoted Character Input:: Asking the user to specify a character.
7050 * Peeking and Discarding:: How to reread or throw away input events.
7053 File: lispref.info, Node: Key Sequence Input, Next: Reading One Event, Up: Reading Input
7055 25.6.1 Key Sequence Input
7056 -------------------------
7058 Lisp programs can read input a key sequence at a time by calling
7059 `read-key-sequence'; for example, `describe-key' uses it to read the
7062 -- Function: read-key-sequence prompt &optional continue-echo
7064 This function reads a sequence of keystrokes or mouse clicks and
7065 returns it as a vector of event objects read. It keeps reading
7066 events until it has accumulated a full key sequence; that is,
7067 enough to specify a non-prefix command using the currently active
7070 The vector and the event objects it contains are freshly created
7071 (and so will not be side-effected by subsequent calls to this
7074 The function `read-key-sequence' suppresses quitting: `C-g' typed
7075 while reading with this function works like any other character,
7076 and does not set `quit-flag'. *Note Quitting::.
7078 The argument PROMPT is either a string to be displayed in the echo
7079 area as a prompt, or `nil', meaning not to display a prompt.
7081 Second optional arg CONTINUE-ECHO non-`nil' means this key echoes
7082 as a continuation of the previous key.
7084 Third optional arg DONT-DOWNCASE-LAST non-`nil' means do not
7085 convert the last event to lower case. (Normally any upper case
7086 event is converted to lower case if the original event is
7087 undefined and the lower case equivalent is defined.) This argument
7088 is provided mostly for FSF compatibility; the equivalent effect
7089 can be achieved more generally by binding
7090 `retry-undefined-key-binding-unshifted' to `nil' around the call
7091 to `read-key-sequence'.
7093 If the user selects a menu item while we are prompting for a key
7094 sequence, the returned value will be a vector of a single
7095 menu-selection event (a misc-user event). An error will be
7096 signalled if you pass this value to `lookup-key' or a related
7099 In the example below, the prompt `?' is displayed in the echo area,
7100 and the user types `C-x C-f'.
7102 (read-key-sequence "?")
7104 ---------- Echo Area ----------
7106 ---------- Echo Area ----------
7108 => [#<keypress-event control-X> #<keypress-event control-F>]
7110 If an input character is an upper-case letter and has no key binding,
7111 but its lower-case equivalent has one, then `read-key-sequence'
7112 converts the character to lower case. Note that `lookup-key' does not
7113 perform case conversion in this way.
7116 File: lispref.info, Node: Reading One Event, Next: Dispatching an Event, Prev: Key Sequence Input, Up: Reading Input
7118 25.6.2 Reading One Event
7119 ------------------------
7121 The lowest level functions for command input are those which read a
7122 single event. These functions often make a distinction between
7123 "command events", which are user actions (keystrokes and mouse
7124 actions), and other events, which serve as communication between XEmacs
7125 and the window system.
7127 -- Function: next-event &optional event prompt
7128 This function reads and returns the next available event from the
7129 window system or terminal driver, waiting if necessary until an
7130 event is available. Pass this object to `dispatch-event' to
7131 handle it. If an event object is supplied, it is filled in and
7132 returned; otherwise a new event object will be created.
7134 Events can come directly from the user, from a keyboard macro, or
7135 from `unread-command-events'.
7137 In most cases, the function `next-command-event' is more
7140 -- Function: next-command-event &optional event prompt
7141 This function returns the next available "user" event from the
7142 window system or terminal driver. Pass this object to
7143 `dispatch-event' to handle it. If an event object is supplied, it
7144 is filled in and returned, otherwise a new event object will be
7147 The event returned will be a keyboard, mouse press, or mouse
7148 release event. If there are non-command events available (mouse
7149 motion, sub-process output, etc) then these will be executed (with
7150 `dispatch-event') and discarded. This function is provided as a
7151 convenience; it is equivalent to the Lisp code
7155 (not (or (key-press-event-p event)
7156 (button-press-event-p event)
7157 (button-release-event-p event)
7158 (menu-event-p event))))
7159 (dispatch-event event))
7161 Here is what happens if you call `next-command-event' and then
7162 press the right-arrow function key:
7164 (next-command-event)
7165 => #<keypress-event right>
7167 -- Function: read-char
7168 This function reads and returns a character of command input. If a
7169 mouse click is detected, an error is signalled. The character
7170 typed is returned as an ASCII value. This function is retained for
7171 compatibility with Emacs 18, and is most likely the wrong thing
7172 for you to be using: consider using `next-command-event' instead.
7174 -- Function: enqueue-eval-event function object
7175 This function adds an eval event to the back of the queue. The
7176 eval event will be the next event read after all pending events.
7179 File: lispref.info, Node: Dispatching an Event, Next: Quoted Character Input, Prev: Reading One Event, Up: Reading Input
7181 25.6.3 Dispatching an Event
7182 ---------------------------
7184 -- Function: dispatch-event event
7185 Given an event object returned by `next-event', this function
7186 executes it. This is the basic function that makes XEmacs respond
7187 to user input; it also deals with notifications from the window
7188 system (such as Expose events).
7191 File: lispref.info, Node: Quoted Character Input, Next: Peeking and Discarding, Prev: Dispatching an Event, Up: Reading Input
7193 25.6.4 Quoted Character Input
7194 -----------------------------
7196 You can use the function `read-quoted-char' to ask the user to specify
7197 a character, and allow the user to specify a control or meta character
7198 conveniently, either literally or as an octal character code. The
7199 command `quoted-insert' uses this function.
7201 -- Function: read-quoted-char &optional prompt
7202 This function is like `read-char', except that if the first
7203 character read is an octal digit (0-7), it reads up to two more
7204 octal digits (but stopping if a non-octal digit is found) and
7205 returns the character represented by those digits in octal.
7207 Quitting is suppressed when the first character is read, so that
7208 the user can enter a `C-g'. *Note Quitting::.
7210 If PROMPT is supplied, it specifies a string for prompting the
7211 user. The prompt string is always displayed in the echo area,
7212 followed by a single `-'.
7214 In the following example, the user types in the octal number 177
7215 (which is 127 in decimal).
7217 (read-quoted-char "What character")
7219 ---------- Echo Area ----------
7221 ---------- Echo Area ----------