This is ../../info/elisp, produced by makeinfo version 4.11 from elisp.texi. This is edition 3.0 of the GNU Emacs Lisp Reference Manual, corresponding to Emacs version 23.2. Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "GNU General Public License," with the Front-Cover texts being "A GNU Manual," and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled "GNU Free Documentation License." (a) The FSF's Back-Cover Text is: "You have the freedom to copy and modify this GNU manual. Buying copies from the FSF supports it in developing GNU and promoting software freedom." INFO-DIR-SECTION Emacs START-INFO-DIR-ENTRY * Elisp: (elisp). The Emacs Lisp Reference Manual. END-INFO-DIR-ENTRY  File: elisp, Node: Simple Types, Next: Composite Types, Up: Customization Types 14.4.1 Simple Types ------------------- This section describes all the simple customization types. `sexp' The value may be any Lisp object that can be printed and read back. You can use `sexp' as a fall-back for any option, if you don't want to take the time to work out a more specific type to use. `integer' The value must be an integer, and is represented textually in the customization buffer. `number' The value must be a number (floating point or integer), and is represented textually in the customization buffer. `float' The value must be a floating point number, and is represented textually in the customization buffer. `string' The value must be a string, and the customization buffer shows just the contents, with no delimiting `"' characters and no quoting with `\'. `regexp' Like `string' except that the string must be a valid regular expression. `character' The value must be a character code. A character code is actually an integer, but this type shows the value by inserting the character in the buffer, rather than by showing the number. `file' The value must be a file name, and you can do completion with `M-'. `(file :must-match t)' The value must be a file name for an existing file, and you can do completion with `M-'. `directory' The value must be a directory name, and you can do completion with `M-'. `hook' The value must be a list of functions (or a single function, but that is obsolete usage). This customization type is used for hook variables. You can use the `:options' keyword in a hook variable's `defcustom' to specify a list of functions recommended for use in the hook; see *note Variable Definitions::. `alist' The value must be a list of cons-cells, the CAR of each cell representing a key, and the CDR of the same cell representing an associated value. The user can add and delete key/value pairs, and edit both the key and the value of each pair. You can specify the key and value types like this: (alist :key-type KEY-TYPE :value-type VALUE-TYPE) where KEY-TYPE and VALUE-TYPE are customization type specifications. The default key type is `sexp', and the default value type is `sexp'. The user can add any key matching the specified key type, but you can give some keys a preferential treatment by specifying them with the `:options' (see *note Variable Definitions::). The specified keys will always be shown in the customize buffer (together with a suitable value), with a checkbox to include or exclude or disable the key/value pair from the alist. The user will not be able to edit the keys specified by the `:options' keyword argument. The argument to the `:options' keywords should be a list of specifications for reasonable keys in the alist. Ordinarily, they are simply atoms, which stand for themselves as. For example: :options '("foo" "bar" "baz") specifies that there are three "known" keys, namely `"foo"', `"bar"' and `"baz"', which will always be shown first. You may want to restrict the value type for specific keys, for example, the value associated with the `"bar"' key can only be an integer. You can specify this by using a list instead of an atom in the list. The first element will specify the key, like before, while the second element will specify the value type. For example: :options '("foo" ("bar" integer) "baz") Finally, you may want to change how the key is presented. By default, the key is simply shown as a `const', since the user cannot change the special keys specified with the `:options' keyword. However, you may want to use a more specialized type for presenting the key, like `function-item' if you know it is a symbol with a function binding. This is done by using a customization type specification instead of a symbol for the key. :options '("foo" ((function-item some-function) integer) "baz") Many alists use lists with two elements, instead of cons cells. For example, (defcustom list-alist '(("foo" 1) ("bar" 2) ("baz" 3)) "Each element is a list of the form (KEY VALUE).") instead of (defcustom cons-alist '(("foo" . 1) ("bar" . 2) ("baz" . 3)) "Each element is a cons-cell (KEY . VALUE).") Because of the way lists are implemented on top of cons cells, you can treat `list-alist' in the example above as a cons cell alist, where the value type is a list with a single element containing the real value. (defcustom list-alist '(("foo" 1) ("bar" 2) ("baz" 3)) "Each element is a list of the form (KEY VALUE)." :type '(alist :value-type (group integer))) The `group' widget is used here instead of `list' only because the formatting is better suited for the purpose. Similarly, you can have alists with more values associated with each key, using variations of this trick: (defcustom person-data '(("brian" 50 t) ("dorith" 55 nil) ("ken" 52 t)) "Alist of basic info about people. Each element has the form (NAME AGE MALE-FLAG)." :type '(alist :value-type (group integer boolean))) (defcustom pets '(("brian") ("dorith" "dog" "guppy") ("ken" "cat")) "Alist of people's pets. In an element (KEY . VALUE), KEY is the person's name, and the VALUE is a list of that person's pets." :type '(alist :value-type (repeat string))) `plist' The `plist' custom type is similar to the `alist' (see above), except that the information is stored as a property list, i.e. a list of this form: (KEY VALUE KEY VALUE KEY VALUE ...) The default `:key-type' for `plist' is `symbol', rather than `sexp'. `symbol' The value must be a symbol. It appears in the customization buffer as the name of the symbol. `function' The value must be either a lambda expression or a function name. When it is a function name, you can do completion with `M-'. `variable' The value must be a variable name, and you can do completion with `M-'. `face' The value must be a symbol which is a face name, and you can do completion with `M-'. `boolean' The value is boolean--either `nil' or `t'. Note that by using `choice' and `const' together (see the next section), you can specify that the value must be `nil' or `t', but also specify the text to describe each value in a way that fits the specific meaning of the alternative. `coding-system' The value must be a coding-system name, and you can do completion with `M-'. `color' The value must be a valid color name, and you can do completion with `M-'. A sample is provided.  File: elisp, Node: Composite Types, Next: Splicing into Lists, Prev: Simple Types, Up: Customization Types 14.4.2 Composite Types ---------------------- When none of the simple types is appropriate, you can use composite types, which build new types from other types or from specified data. The specified types or data are called the "arguments" of the composite type. The composite type normally looks like this: (CONSTRUCTOR ARGUMENTS...) but you can also add keyword-value pairs before the arguments, like this: (CONSTRUCTOR {KEYWORD VALUE}... ARGUMENTS...) Here is a table of constructors and how to use them to write composite types: `(cons CAR-TYPE CDR-TYPE)' The value must be a cons cell, its CAR must fit CAR-TYPE, and its CDR must fit CDR-TYPE. For example, `(cons string symbol)' is a customization type which matches values such as `("foo" . foo)'. In the customization buffer, the CAR and the CDR are displayed and edited separately, each according to the type that you specify for it. `(list ELEMENT-TYPES...)' The value must be a list with exactly as many elements as the ELEMENT-TYPES given; and each element must fit the corresponding ELEMENT-TYPE. For example, `(list integer string function)' describes a list of three elements; the first element must be an integer, the second a string, and the third a function. In the customization buffer, each element is displayed and edited separately, according to the type specified for it. `(group ELEMENT-TYPES...)' This works like `list' except for the formatting of text in the Custom buffer. `list' labels each element value with its tag; `group' does not. `(vector ELEMENT-TYPES...)' Like `list' except that the value must be a vector instead of a list. The elements work the same as in `list'. `(choice ALTERNATIVE-TYPES...)' The value must fit at least one of ALTERNATIVE-TYPES. For example, `(choice integer string)' allows either an integer or a string. In the customization buffer, the user selects an alternative using a menu, and can then edit the value in the usual way for that alternative. Normally the strings in this menu are determined automatically from the choices; however, you can specify different strings for the menu by including the `:tag' keyword in the alternatives. For example, if an integer stands for a number of spaces, while a string is text to use verbatim, you might write the customization type this way, (choice (integer :tag "Number of spaces") (string :tag "Literal text")) so that the menu offers `Number of spaces' and `Literal text'. In any alternative for which `nil' is not a valid value, other than a `const', you should specify a valid default for that alternative using the `:value' keyword. *Note Type Keywords::. If some values are covered by more than one of the alternatives, customize will choose the first alternative that the value fits. This means you should always list the most specific types first, and the most general last. Here's an example of proper usage: (choice (const :tag "Off" nil) symbol (sexp :tag "Other")) This way, the special value `nil' is not treated like other symbols, and symbols are not treated like other Lisp expressions. `(radio ELEMENT-TYPES...)' This is similar to `choice', except that the choices are displayed using `radio buttons' rather than a menu. This has the advantage of displaying documentation for the choices when applicable and so is often a good choice for a choice between constant functions (`function-item' customization types). `(const VALUE)' The value must be VALUE--nothing else is allowed. The main use of `const' is inside of `choice'. For example, `(choice integer (const nil))' allows either an integer or `nil'. `:tag' is often used with `const', inside of `choice'. For example, (choice (const :tag "Yes" t) (const :tag "No" nil) (const :tag "Ask" foo)) describes a variable for which `t' means yes, `nil' means no, and `foo' means "ask." `(other VALUE)' This alternative can match any Lisp value, but if the user chooses this alternative, that selects the value VALUE. The main use of `other' is as the last element of `choice'. For example, (choice (const :tag "Yes" t) (const :tag "No" nil) (other :tag "Ask" foo)) describes a variable for which `t' means yes, `nil' means no, and anything else means "ask." If the user chooses `Ask' from the menu of alternatives, that specifies the value `foo'; but any other value (not `t', `nil' or `foo') displays as `Ask', just like `foo'. `(function-item FUNCTION)' Like `const', but used for values which are functions. This displays the documentation string as well as the function name. The documentation string is either the one you specify with `:doc', or FUNCTION's own documentation string. `(variable-item VARIABLE)' Like `const', but used for values which are variable names. This displays the documentation string as well as the variable name. The documentation string is either the one you specify with `:doc', or VARIABLE's own documentation string. `(set TYPES...)' The value must be a list, and each element of the list must match one of the TYPES specified. This appears in the customization buffer as a checklist, so that each of TYPES may have either one corresponding element or none. It is not possible to specify two different elements that match the same one of TYPES. For example, `(set integer symbol)' allows one integer and/or one symbol in the list; it does not allow multiple integers or multiple symbols. As a result, it is rare to use nonspecific types such as `integer' in a `set'. Most often, the TYPES in a `set' are `const' types, as shown here: (set (const :bold) (const :italic)) Sometimes they describe possible elements in an alist: (set (cons :tag "Height" (const height) integer) (cons :tag "Width" (const width) integer)) That lets the user specify a height value optionally and a width value optionally. `(repeat ELEMENT-TYPE)' The value must be a list and each element of the list must fit the type ELEMENT-TYPE. This appears in the customization buffer as a list of elements, with `[INS]' and `[DEL]' buttons for adding more elements or removing elements. `(restricted-sexp :match-alternatives CRITERIA)' This is the most general composite type construct. The value may be any Lisp object that satisfies one of CRITERIA. CRITERIA should be a list, and each element should be one of these possibilities: * A predicate--that is, a function of one argument that has no side effects, and returns either `nil' or non-`nil' according to the argument. Using a predicate in the list says that objects for which the predicate returns non-`nil' are acceptable. * A quoted constant--that is, `'OBJECT'. This sort of element in the list says that OBJECT itself is an acceptable value. For example, (restricted-sexp :match-alternatives (integerp 't 'nil)) allows integers, `t' and `nil' as legitimate values. The customization buffer shows all legitimate values using their read syntax, and the user edits them textually. Here is a table of the keywords you can use in keyword-value pairs in a composite type: `:tag TAG' Use TAG as the name of this alternative, for user communication purposes. This is useful for a type that appears inside of a `choice'. `:match-alternatives CRITERIA' Use CRITERIA to match possible values. This is used only in `restricted-sexp'. `:args ARGUMENT-LIST' Use the elements of ARGUMENT-LIST as the arguments of the type construct. For instance, `(const :args (foo))' is equivalent to `(const foo)'. You rarely need to write `:args' explicitly, because normally the arguments are recognized automatically as whatever follows the last keyword-value pair.  File: elisp, Node: Splicing into Lists, Next: Type Keywords, Prev: Composite Types, Up: Customization Types 14.4.3 Splicing into Lists -------------------------- The `:inline' feature lets you splice a variable number of elements into the middle of a list or vector. You use it in a `set', `choice' or `repeat' type which appears among the element-types of a `list' or `vector'. Normally, each of the element-types in a `list' or `vector' describes one and only one element of the list or vector. Thus, if an element-type is a `repeat', that specifies a list of unspecified length which appears as one element. But when the element-type uses `:inline', the value it matches is merged directly into the containing sequence. For example, if it matches a list with three elements, those become three elements of the overall sequence. This is analogous to using `,@' in the backquote construct. For example, to specify a list whose first element must be `baz' and whose remaining arguments should be zero or more of `foo' and `bar', use this customization type: (list (const baz) (set :inline t (const foo) (const bar))) This matches values such as `(baz)', `(baz foo)', `(baz bar)' and `(baz foo bar)'. When the element-type is a `choice', you use `:inline' not in the `choice' itself, but in (some of) the alternatives of the `choice'. For example, to match a list which must start with a file name, followed either by the symbol `t' or two strings, use this customization type: (list file (choice (const t) (list :inline t string string))) If the user chooses the first alternative in the choice, then the overall list has two elements and the second element is `t'. If the user chooses the second alternative, then the overall list has three elements and the second and third must be strings.  File: elisp, Node: Type Keywords, Next: Defining New Types, Prev: Splicing into Lists, Up: Customization Types 14.4.4 Type Keywords -------------------- You can specify keyword-argument pairs in a customization type after the type name symbol. Here are the keywords you can use, and their meanings: `:value DEFAULT' This is used for a type that appears as an alternative inside of `choice'; it specifies the default value to use, at first, if and when the user selects this alternative with the menu in the customization buffer. Of course, if the actual value of the option fits this alternative, it will appear showing the actual value, not DEFAULT. If `nil' is not a valid value for the alternative, then it is essential to specify a valid default with `:value'. `:format FORMAT-STRING' This string will be inserted in the buffer to represent the value corresponding to the type. The following `%' escapes are available for use in FORMAT-STRING: `%[BUTTON%]' Display the text BUTTON marked as a button. The `:action' attribute specifies what the button will do if the user invokes it; its value is a function which takes two arguments--the widget which the button appears in, and the event. There is no way to specify two different buttons with different actions. `%{SAMPLE%}' Show SAMPLE in a special face specified by `:sample-face'. `%v' Substitute the item's value. How the value is represented depends on the kind of item, and (for variables) on the customization type. `%d' Substitute the item's documentation string. `%h' Like `%d', but if the documentation string is more than one line, add an active field to control whether to show all of it or just the first line. `%t' Substitute the tag here. You specify the tag with the `:tag' keyword. `%%' Display a literal `%'. `:action ACTION' Perform ACTION if the user clicks on a button. `:button-face FACE' Use the face FACE (a face name or a list of face names) for button text displayed with `%[...%]'. `:button-prefix PREFIX' `:button-suffix SUFFIX' These specify the text to display before and after a button. Each can be: `nil' No text is inserted. a string The string is inserted literally. a symbol The symbol's value is used. `:tag TAG' Use TAG (a string) as the tag for the value (or part of the value) that corresponds to this type. `:doc DOC' Use DOC as the documentation string for this value (or part of the value) that corresponds to this type. In order for this to work, you must specify a value for `:format', and use `%d' or `%h' in that value. The usual reason to specify a documentation string for a type is to provide more information about the meanings of alternatives inside a `:choice' type or the parts of some other composite type. `:help-echo MOTION-DOC' When you move to this item with `widget-forward' or `widget-backward', it will display the string MOTION-DOC in the echo area. In addition, MOTION-DOC is used as the mouse `help-echo' string and may actually be a function or form evaluated to yield a help string. If it is a function, it is called with one argument, the widget. `:match FUNCTION' Specify how to decide whether a value matches the type. The corresponding value, FUNCTION, should be a function that accepts two arguments, a widget and a value; it should return non-`nil' if the value is acceptable. `:validate FUNCTION' Specify a validation function for input. FUNCTION takes a widget as an argument, and should return `nil' if the widget's current value is valid for the widget. Otherwise, it should return the widget containing the invalid data, and set that widget's `:error' property to a string explaining the error.  File: elisp, Node: Defining New Types, Prev: Type Keywords, Up: Customization Types 14.4.5 Defining New Types ------------------------- In the previous sections we have described how to construct elaborate type specifications for `defcustom'. In some cases you may want to give such a type specification a name. The obvious case is when you are using the same type for many user options: rather than repeat the specification for each option, you can give the type specification a name, and use that name each `defcustom'. The other case is when a user option's value is a recursive data structure. To make it possible for a datatype to refer to itself, it needs to have a name. Since custom types are implemented as widgets, the way to define a new customize type is to define a new widget. We are not going to describe the widget interface here in details, see *note Introduction: (widget)Top, for that. Instead we are going to demonstrate the minimal functionality needed for defining new customize types by a simple example. (define-widget 'binary-tree-of-string 'lazy "A binary tree made of cons-cells and strings." :offset 4 :tag "Node" :type '(choice (string :tag "Leaf" :value "") (cons :tag "Interior" :value ("" . "") binary-tree-of-string binary-tree-of-string))) (defcustom foo-bar "" "Sample variable holding a binary tree of strings." :type 'binary-tree-of-string) The function to define a new widget is called `define-widget'. The first argument is the symbol we want to make a new widget type. The second argument is a symbol representing an existing widget, the new widget is going to be defined in terms of difference from the existing widget. For the purpose of defining new customization types, the `lazy' widget is perfect, because it accepts a `:type' keyword argument with the same syntax as the keyword argument to `defcustom' with the same name. The third argument is a documentation string for the new widget. You will be able to see that string with the `M-x widget-browse binary-tree-of-string ' command. After these mandatory arguments follow the keyword arguments. The most important is `:type', which describes the data type we want to match with this widget. Here a `binary-tree-of-string' is described as being either a string, or a cons-cell whose car and cdr are themselves both `binary-tree-of-string'. Note the reference to the widget type we are currently in the process of defining. The `:tag' attribute is a string to name the widget in the user interface, and the `:offset' argument is there to ensure that child nodes are indented four spaces relative to the parent node, making the tree structure apparent in the customization buffer. The `defcustom' shows how the new widget can be used as an ordinary customization type. The reason for the name `lazy' is that the other composite widgets convert their inferior widgets to internal form when the widget is instantiated in a buffer. This conversion is recursive, so the inferior widgets will convert _their_ inferior widgets. If the data structure is itself recursive, this conversion is an infinite recursion. The `lazy' widget prevents the recursion: it convert its `:type' argument only when needed.  File: elisp, Node: Loading, Next: Byte Compilation, Prev: Customization, Up: Top 15 Loading ********** Loading a file of Lisp code means bringing its contents into the Lisp environment in the form of Lisp objects. Emacs finds and opens the file, reads the text, evaluates each form, and then closes the file. The load functions evaluate all the expressions in a file just as the `eval-buffer' function evaluates all the expressions in a buffer. The difference is that the load functions read and evaluate the text in the file as found on disk, not the text in an Emacs buffer. The loaded file must contain Lisp expressions, either as source code or as byte-compiled code. Each form in the file is called a "top-level form". There is no special format for the forms in a loadable file; any form in a file may equally well be typed directly into a buffer and evaluated there. (Indeed, most code is tested this way.) Most often, the forms are function definitions and variable definitions. A file containing Lisp code is often called a "library". Thus, the "Rmail library" is a file containing code for Rmail mode. Similarly, a "Lisp library directory" is a directory of files containing Lisp code. * Menu: * How Programs Do Loading:: The `load' function and others. * Load Suffixes:: Details about the suffixes that `load' tries. * Library Search:: Finding a library to load. * Loading Non-ASCII:: Non-ASCII characters in Emacs Lisp files. * Autoload:: Setting up a function to autoload. * Repeated Loading:: Precautions about loading a file twice. * Named Features:: Loading a library if it isn't already loaded. * Where Defined:: Finding which file defined a certain symbol. * Unloading:: How to "unload" a library that was loaded. * Hooks for Loading:: Providing code to be run when particular libraries are loaded.  File: elisp, Node: How Programs Do Loading, Next: Load Suffixes, Up: Loading 15.1 How Programs Do Loading ============================ Emacs Lisp has several interfaces for loading. For example, `autoload' creates a placeholder object for a function defined in a file; trying to call the autoloading function loads the file to get the function's real definition (*note Autoload::). `require' loads a file if it isn't already loaded (*note Named Features::). Ultimately, all these facilities call the `load' function to do the work. -- Function: load filename &optional missing-ok nomessage nosuffix must-suffix This function finds and opens a file of Lisp code, evaluates all the forms in it, and closes the file. To find the file, `load' first looks for a file named `FILENAME.elc', that is, for a file whose name is FILENAME with the extension `.elc' appended. If such a file exists, it is loaded. If there is no file by that name, then `load' looks for a file named `FILENAME.el'. If that file exists, it is loaded. Finally, if neither of those names is found, `load' looks for a file named FILENAME with nothing appended, and loads it if it exists. (The `load' function is not clever about looking at FILENAME. In the perverse case of a file named `foo.el.el', evaluation of `(load "foo.el")' will indeed find it.) If Auto Compression mode is enabled, as it is by default, then if `load' can not find a file, it searches for a compressed version of the file before trying other file names. It decompresses and loads it if it exists. It looks for compressed versions by appending each of the suffixes in `jka-compr-load-suffixes' to the file name. The value of this variable must be a list of strings. Its standard value is `(".gz")'. If the optional argument NOSUFFIX is non-`nil', then `load' does not try the suffixes `.elc' and `.el'. In this case, you must specify the precise file name you want, except that, if Auto Compression mode is enabled, `load' will still use `jka-compr-load-suffixes' to find compressed versions. By specifying the precise file name and using `t' for NOSUFFIX, you can prevent perverse file names such as `foo.el.el' from being tried. If the optional argument MUST-SUFFIX is non-`nil', then `load' insists that the file name used must end in either `.el' or `.elc' (possibly extended with a compression suffix), unless it contains an explicit directory name. If FILENAME is a relative file name, such as `foo' or `baz/foo.bar', `load' searches for the file using the variable `load-path'. It appends FILENAME to each of the directories listed in `load-path', and loads the first file it finds whose name matches. The current default directory is tried only if it is specified in `load-path', where `nil' stands for the default directory. `load' tries all three possible suffixes in the first directory in `load-path', then all three suffixes in the second directory, and so on. *Note Library Search::. If you get a warning that `foo.elc' is older than `foo.el', it means you should consider recompiling `foo.el'. *Note Byte Compilation::. When loading a source file (not compiled), `load' performs character set translation just as Emacs would do when visiting the file. *Note Coding Systems::. Messages like `Loading foo...' and `Loading foo...done' appear in the echo area during loading unless NOMESSAGE is non-`nil'. Any unhandled errors while loading a file terminate loading. If the load was done for the sake of `autoload', any function definitions made during the loading are undone. If `load' can't find the file to load, then normally it signals the error `file-error' (with `Cannot open load file FILENAME'). But if MISSING-OK is non-`nil', then `load' just returns `nil'. You can use the variable `load-read-function' to specify a function for `load' to use instead of `read' for reading expressions. See below. `load' returns `t' if the file loads successfully. -- Command: load-file filename This command loads the file FILENAME. If FILENAME is a relative file name, then the current default directory is assumed. This command does not use `load-path', and does not append suffixes. However, it does look for compressed versions (if Auto Compression Mode is enabled). Use this command if you wish to specify precisely the file name to load. -- Command: load-library library This command loads the library named LIBRARY. It is equivalent to `load', except for the way it reads its argument interactively. *Note Lisp Libraries: (emacs)Lisp Libraries. -- Variable: load-in-progress This variable is non-`nil' if Emacs is in the process of loading a file, and it is `nil' otherwise. -- Variable: load-read-function This variable specifies an alternate expression-reading function for `load' and `eval-region' to use instead of `read'. The function should accept one argument, just as `read' does. Normally, the variable's value is `nil', which means those functions should use `read'. Instead of using this variable, it is cleaner to use another, newer feature: to pass the function as the READ-FUNCTION argument to `eval-region'. *Note Eval: Definition of eval-region. For information about how `load' is used in building Emacs, see *note Building Emacs::.  File: elisp, Node: Load Suffixes, Next: Library Search, Prev: How Programs Do Loading, Up: Loading 15.2 Load Suffixes ================== We now describe some technical details about the exact suffixes that `load' tries. -- Variable: load-suffixes This is a list of suffixes indicating (compiled or source) Emacs Lisp files. It should not include the empty string. `load' uses these suffixes in order when it appends Lisp suffixes to the specified file name. The standard value is `(".elc" ".el")' which produces the behavior described in the previous section. -- Variable: load-file-rep-suffixes This is a list of suffixes that indicate representations of the same file. This list should normally start with the empty string. When `load' searches for a file it appends the suffixes in this list, in order, to the file name, before searching for another file. Enabling Auto Compression mode appends the suffixes in `jka-compr-load-suffixes' to this list and disabling Auto Compression mode removes them again. The standard value of `load-file-rep-suffixes' if Auto Compression mode is disabled is `("")'. Given that the standard value of `jka-compr-load-suffixes' is `(".gz")', the standard value of `load-file-rep-suffixes' if Auto Compression mode is enabled is `("" ".gz")'. -- Function: get-load-suffixes This function returns the list of all suffixes that `load' should try, in order, when its MUST-SUFFIX argument is non-`nil'. This takes both `load-suffixes' and `load-file-rep-suffixes' into account. If `load-suffixes', `jka-compr-load-suffixes' and `load-file-rep-suffixes' all have their standard values, this function returns `(".elc" ".elc.gz" ".el" ".el.gz")' if Auto Compression mode is enabled and `(".elc" ".el")' if Auto Compression mode is disabled. To summarize, `load' normally first tries the suffixes in the value of `(get-load-suffixes)' and then those in `load-file-rep-suffixes'. If NOSUFFIX is non-`nil', it skips the former group, and if MUST-SUFFIX is non-`nil', it skips the latter group.  File: elisp, Node: Library Search, Next: Loading Non-ASCII, Prev: Load Suffixes, Up: Loading 15.3 Library Search =================== When Emacs loads a Lisp library, it searches for the library in a list of directories specified by the variable `load-path'. -- User Option: load-path The value of this variable is a list of directories to search when loading files with `load'. Each element is a string (which must be a directory name) or `nil' (which stands for the current working directory). The value of `load-path' is initialized from the environment variable `EMACSLOADPATH', if that exists; otherwise its default value is specified in `emacs/src/epaths.h' when Emacs is built. Then the list is expanded by adding subdirectories of the directories in the list. The syntax of `EMACSLOADPATH' is the same as used for `PATH'; `:' (or `;', according to the operating system) separates directory names, and `.' is used for the current default directory. Here is an example of how to set your `EMACSLOADPATH' variable from a `csh' `.login' file: setenv EMACSLOADPATH .:/user/bil/emacs:/usr/local/share/emacs/20.3/lisp Here is how to set it using `sh': export EMACSLOADPATH EMACSLOADPATH=.:/user/bil/emacs:/usr/local/share/emacs/20.3/lisp Here is an example of code you can place in your init file (*note Init File::) to add several directories to the front of your default `load-path': (setq load-path (append (list nil "/user/bil/emacs" "/usr/local/lisplib" "~/emacs") load-path)) In this example, the path searches the current working directory first, followed then by the `/user/bil/emacs' directory, the `/usr/local/lisplib' directory, and the `~/emacs' directory, which are then followed by the standard directories for Lisp code. Dumping Emacs uses a special value of `load-path'. If the value of `load-path' at the end of dumping is unchanged (that is, still the same special value), the dumped Emacs switches to the ordinary `load-path' value when it starts up, as described above. But if `load-path' has any other value at the end of dumping, that value is used for execution of the dumped Emacs also. Therefore, if you want to change `load-path' temporarily for loading a few libraries in `site-init.el' or `site-load.el', you should bind `load-path' locally with `let' around the calls to `load'. The default value of `load-path', when running an Emacs which has been installed on the system, includes two special directories (and their subdirectories as well): "/usr/local/share/emacs/VERSION/site-lisp" and "/usr/local/share/emacs/site-lisp" The first one is for locally installed packages for a particular Emacs version; the second is for locally installed packages meant for use with all installed Emacs versions. There are several reasons why a Lisp package that works well in one Emacs version can cause trouble in another. Sometimes packages need updating for incompatible changes in Emacs; sometimes they depend on undocumented internal Emacs data that can change without notice; sometimes a newer Emacs version incorporates a version of the package, and should be used only with that version. Emacs finds these directories' subdirectories and adds them to `load-path' when it starts up. Both immediate subdirectories and subdirectories multiple levels down are added to `load-path'. Not all subdirectories are included, though. Subdirectories whose names do not start with a letter or digit are excluded. Subdirectories named `RCS' or `CVS' are excluded. Also, a subdirectory which contains a file named `.nosearch' is excluded. You can use these methods to prevent certain subdirectories of the `site-lisp' directories from being searched. If you run Emacs from the directory where it was built--that is, an executable that has not been formally installed--then `load-path' normally contains two additional directories. These are the `lisp' and `site-lisp' subdirectories of the main build directory. (Both are represented as absolute file names.) -- Command: locate-library library &optional nosuffix path interactive-call This command finds the precise file name for library LIBRARY. It searches for the library in the same way `load' does, and the argument NOSUFFIX has the same meaning as in `load': don't add suffixes `.elc' or `.el' to the specified name LIBRARY. If the PATH is non-`nil', that list of directories is used instead of `load-path'. When `locate-library' is called from a program, it returns the file name as a string. When the user runs `locate-library' interactively, the argument INTERACTIVE-CALL is `t', and this tells `locate-library' to display the file name in the echo area.  File: elisp, Node: Loading Non-ASCII, Next: Autoload, Prev: Library Search, Up: Loading 15.4 Loading Non-ASCII Characters ================================= When Emacs Lisp programs contain string constants with non-ASCII characters, these can be represented within Emacs either as unibyte strings or as multibyte strings (*note Text Representations::). Which representation is used depends on how the file is read into Emacs. If it is read with decoding into multibyte representation, the text of the Lisp program will be multibyte text, and its string constants will be multibyte strings. If a file containing Latin-1 characters (for example) is read without decoding, the text of the program will be unibyte text, and its string constants will be unibyte strings. *Note Coding Systems::. To make the results more predictable, Emacs always performs decoding into the multibyte representation when loading Lisp files, even if it was started with the `--unibyte' option. This means that string constants with non-ASCII characters translate into multibyte strings. The only exception is when a particular file specifies no decoding. The reason Emacs is designed this way is so that Lisp programs give predictable results, regardless of how Emacs was started. In addition, this enables programs that depend on using multibyte text to work even in a unibyte Emacs. In most Emacs Lisp programs, the fact that non-ASCII strings are multibyte strings should not be noticeable, since inserting them in unibyte buffers converts them to unibyte automatically. However, if this does make a difference, you can force a particular Lisp file to be interpreted as unibyte by writing `-*-unibyte: t;-*-' in a comment on the file's first line. With that designator, the file will unconditionally be interpreted as unibyte, even in an ordinary multibyte Emacs session. This can matter when making keybindings to non-ASCII characters written as `?vLITERAL'.  File: elisp, Node: Autoload, Next: Repeated Loading, Prev: Loading Non-ASCII, Up: Loading 15.5 Autoload ============= The "autoload" facility allows you to make a function or macro known in Lisp, but put off loading the file that defines it. The first call to the function automatically reads the proper file to install the real definition and other associated code, then runs the real definition as if it had been loaded all along. There are two ways to set up an autoloaded function: by calling `autoload', and by writing a special "magic" comment in the source before the real definition. `autoload' is the low-level primitive for autoloading; any Lisp program can call `autoload' at any time. Magic comments are the most convenient way to make a function autoload, for packages installed along with Emacs. These comments do nothing on their own, but they serve as a guide for the command `update-file-autoloads', which constructs calls to `autoload' and arranges to execute them when Emacs is built. -- Function: autoload function filename &optional docstring interactive type This function defines the function (or macro) named FUNCTION so as to load automatically from FILENAME. The string FILENAME specifies the file to load to get the real definition of FUNCTION. If FILENAME does not contain either a directory name, or the suffix `.el' or `.elc', then `autoload' insists on adding one of these suffixes, and it will not load from a file whose name is just FILENAME with no added suffix. (The variable `load-suffixes' specifies the exact required suffixes.) The argument DOCSTRING is the documentation string for the function. Specifying the documentation string in the call to `autoload' makes it possible to look at the documentation without loading the function's real definition. Normally, this should be identical to the documentation string in the function definition itself. If it isn't, the function definition's documentation string takes effect when it is loaded. If INTERACTIVE is non-`nil', that says FUNCTION can be called interactively. This lets completion in `M-x' work without loading FUNCTION's real definition. The complete interactive specification is not given here; it's not needed unless the user actually calls FUNCTION, and when that happens, it's time to load the real definition. You can autoload macros and keymaps as well as ordinary functions. Specify TYPE as `macro' if FUNCTION is really a macro. Specify TYPE as `keymap' if FUNCTION is really a keymap. Various parts of Emacs need to know this information without loading the real definition. An autoloaded keymap loads automatically during key lookup when a prefix key's binding is the symbol FUNCTION. Autoloading does not occur for other kinds of access to the keymap. In particular, it does not happen when a Lisp program gets the keymap from the value of a variable and calls `define-key'; not even if the variable name is the same symbol FUNCTION. If FUNCTION already has a non-void function definition that is not an autoload object, `autoload' does nothing and returns `nil'. If the function cell of FUNCTION is void, or is already an autoload object, then it is defined as an autoload object like this: (autoload FILENAME DOCSTRING INTERACTIVE TYPE) For example, (symbol-function 'run-prolog) => (autoload "prolog" 169681 t nil) In this case, `"prolog"' is the name of the file to load, 169681 refers to the documentation string in the `emacs/etc/DOC-VERSION' file (*note Documentation Basics::), `t' means the function is interactive, and `nil' that it is not a macro or a keymap. The autoloaded file usually contains other definitions and may require or provide one or more features. If the file is not completely loaded (due to an error in the evaluation of its contents), any function definitions or `provide' calls that occurred during the load are undone. This is to ensure that the next attempt to call any function autoloading from this file will try again to load the file. If not for this, then some of the functions in the file might be defined by the aborted load, but fail to work properly for the lack of certain subroutines not loaded successfully because they come later in the file. If the autoloaded file fails to define the desired Lisp function or macro, then an error is signaled with data `"Autoloading failed to define function FUNCTION-NAME"'. A magic autoload comment (often called an "autoload cookie") consists of `;;;###autoload', on a line by itself, just before the real definition of the function in its autoloadable source file. The command `M-x update-file-autoloads' writes a corresponding `autoload' call into `loaddefs.el'. (The string that serves as the autoload cookie and the name of the file generated by `update-file-autoloads' can be changed from the above defaults, see below.) Building Emacs loads `loaddefs.el' and thus calls `autoload'. `M-x update-directory-autoloads' is even more powerful; it updates autoloads for all files in the current directory. The same magic comment can copy any kind of form into `loaddefs.el'. If the form following the magic comment is not a function-defining form or a `defcustom' form, it is copied verbatim. "Function-defining forms" include `define-skeleton', `define-derived-mode', `define-generic-mode' and `define-minor-mode' as well as `defun' and `defmacro'. To save space, a `defcustom' form is converted to a `defvar' in `loaddefs.el', with some additional information if it uses `:require'. You can also use a magic comment to execute a form at build time _without_ executing it when the file itself is loaded. To do this, write the form _on the same line_ as the magic comment. Since it is in a comment, it does nothing when you load the source file; but `M-x update-file-autoloads' copies it to `loaddefs.el', where it is executed while building Emacs. The following example shows how `doctor' is prepared for autoloading with a magic comment: ;;;###autoload (defun doctor () "Switch to *doctor* buffer and start giving psychotherapy." (interactive) (switch-to-buffer "*doctor*") (doctor-mode)) Here's what that produces in `loaddefs.el': (autoload (quote doctor) "doctor" "\ Switch to *doctor* buffer and start giving psychotherapy. \(fn)" t nil) The backslash and newline immediately following the double-quote are a convention used only in the preloaded uncompiled Lisp files such as `loaddefs.el'; they tell `make-docfile' to put the documentation string in the `etc/DOC' file. *Note Building Emacs::. See also the commentary in `lib-src/make-docfile.c'. `(fn)' in the usage part of the documentation string is replaced with the function's name when the various help functions (*note Help Functions::) display it. If you write a function definition with an unusual macro that is not one of the known and recognized function definition methods, use of an ordinary magic autoload comment would copy the whole definition into `loaddefs.el'. That is not desirable. You can put the desired `autoload' call into `loaddefs.el' instead by writing this: ;;;###autoload (autoload 'foo "myfile") (mydefunmacro foo ...) You can use a non-default string as the autoload cookie and have the corresponding autoload calls written into a file whose name is different from the default `loaddefs.el'. Emacs provides two variables to control this: -- Variable: generate-autoload-cookie The value of this variable should be a string whose syntax is a Lisp comment. `M-x update-file-autoloads' copies the Lisp form that follows the cookie into the autoload file it generates. The default value of this variable is `";;;###autoload"'. -- Variable: generated-autoload-file The value of this variable names an Emacs Lisp file where the autoload calls should go. The default value is `loaddefs.el', but you can override that, e.g., in the "Local Variables" section of a `.el' file (*note File Local Variables::). The autoload file is assumed to contain a trailer starting with a formfeed character.  File: elisp, Node: Repeated Loading, Next: Named Features, Prev: Autoload, Up: Loading 15.6 Repeated Loading ===================== You can load a given file more than once in an Emacs session. For example, after you have rewritten and reinstalled a function definition by editing it in a buffer, you may wish to return to the original version; you can do this by reloading the file it came from. When you load or reload files, bear in mind that the `load' and `load-library' functions automatically load a byte-compiled file rather than a non-compiled file of similar name. If you rewrite a file that you intend to save and reinstall, you need to byte-compile the new version; otherwise Emacs will load the older, byte-compiled file instead of your newer, non-compiled file! If that happens, the message displayed when loading the file includes, `(compiled; note, source is newer)', to remind you to recompile it. When writing the forms in a Lisp library file, keep in mind that the file might be loaded more than once. For example, think about whether each variable should be reinitialized when you reload the library; `defvar' does not change the value if the variable is already initialized. (*Note Defining Variables::.) The simplest way to add an element to an alist is like this: (push '(leif-mode " Leif") minor-mode-alist) But this would add multiple elements if the library is reloaded. To avoid the problem, use `add-to-list' (*note List Variables::): (add-to-list 'minor-mode-alist '(leif-mode " Leif")) Occasionally you will want to test explicitly whether a library has already been loaded. If the library uses `provide' to provide a named feature, you can use `featurep' earlier in the file to test whether the `provide' call has been executed before (*note Named Features::). Alternatively, you could use something like this: (defvar foo-was-loaded nil) (unless foo-was-loaded EXECUTE-FIRST-TIME-ONLY (setq foo-was-loaded t))  File: elisp, Node: Named Features, Next: Where Defined, Prev: Repeated Loading, Up: Loading 15.7 Features ============= `provide' and `require' are an alternative to `autoload' for loading files automatically. They work in terms of named "features". Autoloading is triggered by calling a specific function, but a feature is loaded the first time another program asks for it by name. A feature name is a symbol that stands for a collection of functions, variables, etc. The file that defines them should "provide" the feature. Another program that uses them may ensure they are defined by "requiring" the feature. This loads the file of definitions if it hasn't been loaded already. To require the presence of a feature, call `require' with the feature name as argument. `require' looks in the global variable `features' to see whether the desired feature has been provided already. If not, it loads the feature from the appropriate file. This file should call `provide' at the top level to add the feature to `features'; if it fails to do so, `require' signals an error. For example, in `emacs/lisp/prolog.el', the definition for `run-prolog' includes the following code: (defun run-prolog () "Run an inferior Prolog process, with I/O via buffer *prolog*." (interactive) (require 'comint) (switch-to-buffer (make-comint "prolog" prolog-program-name)) (inferior-prolog-mode)) The expression `(require 'comint)' loads the file `comint.el' if it has not yet been loaded. This ensures that `make-comint' is defined. Features are normally named after the files that provide them, so that `require' need not be given the file name. The `comint.el' file contains the following top-level expression: (provide 'comint) This adds `comint' to the global `features' list, so that `(require 'comint)' will henceforth know that nothing needs to be done. When `require' is used at top level in a file, it takes effect when you byte-compile that file (*note Byte Compilation::) as well as when you load it. This is in case the required package contains macros that the byte compiler must know about. It also avoids byte compiler warnings for functions and variables defined in the file loaded with `require'. Although top-level calls to `require' are evaluated during byte compilation, `provide' calls are not. Therefore, you can ensure that a file of definitions is loaded before it is byte-compiled by including a `provide' followed by a `require' for the same feature, as in the following example. (provide 'my-feature) ; Ignored by byte compiler, ; evaluated by `load'. (require 'my-feature) ; Evaluated by byte compiler. The compiler ignores the `provide', then processes the `require' by loading the file in question. Loading the file does execute the `provide' call, so the subsequent `require' call does nothing when the file is loaded. -- Function: provide feature &optional subfeatures This function announces that FEATURE is now loaded, or being loaded, into the current Emacs session. This means that the facilities associated with FEATURE are or will be available for other Lisp programs. The direct effect of calling `provide' is if not already in FEATURES then to add FEATURE to the front of that list and call any `eval-after-load' code waiting for it (*note Hooks for Loading::). The argument FEATURE must be a symbol. `provide' returns FEATURE. If provided, SUBFEATURES should be a list of symbols indicating a set of specific subfeatures provided by this version of FEATURE. You can test the presence of a subfeature using `featurep'. The idea of subfeatures is that you use them when a package (which is one FEATURE) is complex enough to make it useful to give names to various parts or functionalities of the package, which might or might not be loaded, or might or might not be present in a given version. *Note Network Feature Testing::, for an example. features => (bar bish) (provide 'foo) => foo features => (foo bar bish) When a file is loaded to satisfy an autoload, and it stops due to an error in the evaluation of its contents, any function definitions or `provide' calls that occurred during the load are undone. *Note Autoload::. -- Function: require feature &optional filename noerror This function checks whether FEATURE is present in the current Emacs session (using `(featurep FEATURE)'; see below). The argument FEATURE must be a symbol. If the feature is not present, then `require' loads FILENAME with `load'. If FILENAME is not supplied, then the name of the symbol FEATURE is used as the base file name to load. However, in this case, `require' insists on finding FEATURE with an added `.el' or `.elc' suffix (possibly extended with a compression suffix); a file whose name is just FEATURE won't be used. (The variable `load-suffixes' specifies the exact required Lisp suffixes.) If NOERROR is non-`nil', that suppresses errors from actual loading of the file. In that case, `require' returns `nil' if loading the file fails. Normally, `require' returns FEATURE. If loading the file succeeds but does not provide FEATURE, `require' signals an error, `Required feature FEATURE was not provided'. -- Function: featurep feature &optional subfeature This function returns `t' if FEATURE has been provided in the current Emacs session (i.e., if FEATURE is a member of `features'.) If SUBFEATURE is non-`nil', then the function returns `t' only if that subfeature is provided as well (i.e. if SUBFEATURE is a member of the `subfeature' property of the FEATURE symbol.) -- Variable: features The value of this variable is a list of symbols that are the features loaded in the current Emacs session. Each symbol was put in this list with a call to `provide'. The order of the elements in the `features' list is not significant.  File: elisp, Node: Where Defined, Next: Unloading, Prev: Named Features, Up: Loading 15.8 Which File Defined a Certain Symbol ======================================== -- Function: symbol-file symbol &optional type This function returns the name of the file that defined SYMBOL. If TYPE is `nil', then any kind of definition is acceptable. If TYPE is `defun', `defvar', or `defface', that specifies function definition, variable definition, or face definition only. The value is normally an absolute file name. It can also be `nil', if the definition is not associated with any file. If SYMBOL specifies an autoloaded function, the value can be a relative file name without extension. The basis for `symbol-file' is the data in the variable `load-history'. -- Variable: load-history The value of this variable is an alist that associates the names of loaded library files with the names of the functions and variables they defined, as well as the features they provided or required. Each element in this alist describes one loaded library (including libraries that are preloaded at startup). It is a list whose CAR is the absolute file name of the library (a string). The rest of the list elements have these forms: `VAR' The symbol VAR was defined as a variable. `(defun . FUN)' The function FUN was defined. `(t . FUN)' The function FUN was previously an autoload before this library redefined it as a function. The following element is always `(defun . FUN)', which represents defining FUN as a function. `(autoload . FUN)' The function FUN was defined as an autoload. `(defface . FACE)' The face FACE was defined. `(require . FEATURE)' The feature FEATURE was required. `(provide . FEATURE)' The feature FEATURE was provided. The value of `load-history' may have one element whose CAR is `nil'. This element describes definitions made with `eval-buffer' on a buffer that is not visiting a file. The command `eval-region' updates `load-history', but does so by adding the symbols defined to the element for the file being visited, rather than replacing that element. *Note Eval::.  File: elisp, Node: Unloading, Next: Hooks for Loading, Prev: Where Defined, Up: Loading 15.9 Unloading ============== You can discard the functions and variables loaded by a library to reclaim memory for other Lisp objects. To do this, use the function `unload-feature': -- Command: unload-feature feature &optional force This command unloads the library that provided feature FEATURE. It undefines all functions, macros, and variables defined in that library with `defun', `defalias', `defsubst', `defmacro', `defconst', `defvar', and `defcustom'. It then restores any autoloads formerly associated with those symbols. (Loading saves these in the `autoload' property of the symbol.) Before restoring the previous definitions, `unload-feature' runs `remove-hook' to remove functions in the library from certain hooks. These hooks include variables whose names end in `hook' or `-hooks', plus those listed in `unload-feature-special-hooks', as well as `auto-mode-alist'. This is to prevent Emacs from ceasing to function because important hooks refer to functions that are no longer defined. Standard unloading activities also undoes ELP profiling of functions in that library, unprovides any features provided by the library, and cancels timers held in variables defined by the library. If these measures are not sufficient to prevent malfunction, a library can define an explicit unloader named `FEATURE-unload-function'. If that symbol is defined as a function, `unload-feature' calls it with no arguments before doing anything else. It can do whatever is appropriate to unload the library. If it returns `nil', `unload-feature' proceeds to take the normal unload actions. Otherwise it considers the job to be done. Ordinarily, `unload-feature' refuses to unload a library on which other loaded libraries depend. (A library A depends on library B if A contains a `require' for B.) If the optional argument FORCE is non-`nil', dependencies are ignored and you can unload any library. The `unload-feature' function is written in Lisp; its actions are based on the variable `load-history'. -- Variable: unload-feature-special-hooks This variable holds a list of hooks to be scanned before unloading a library, to remove functions defined in the library.  File: elisp, Node: Hooks for Loading, Prev: Unloading, Up: Loading 15.10 Hooks for Loading ======================= You can ask for code to be executed each time Emacs loads a library, by using the variable `after-load-functions': -- Variable: after-load-functions This abnormal hook is run after loading a file. Each function in the hook is called with a single argument, the absolute filename of the file that was just loaded. If you want code to be executed when a _particular_ library is loaded, use the function `eval-after-load': -- Function: eval-after-load library form This function arranges to evaluate FORM at the end of loading the file LIBRARY, each time LIBRARY is loaded. If LIBRARY is already loaded, it evaluates FORM right away. Don't forget to quote FORM! You don't need to give a directory or extension in the file name LIBRARY. Normally, you just give a bare file name, like this: (eval-after-load "edebug" '(def-edebug-spec c-point t)) To restrict which files can trigger the evaluation, include a directory or an extension or both in LIBRARY. Only a file whose absolute true name (i.e., the name with all symbolic links chased out) matches all the given name components will match. In the following example, `my_inst.elc' or `my_inst.elc.gz' in some directory `..../foo/bar' will trigger the evaluation, but not `my_inst.el': (eval-after-load "foo/bar/my_inst.elc" ...) LIBRARY can also be a feature (i.e. a symbol), in which case FORM is evaluated when `(provide LIBRARY)' is called. An error in FORM does not undo the load, but does prevent execution of the rest of FORM. Normally, well-designed Lisp programs should not use `eval-after-load'. If you need to examine and set the variables defined in another library (those meant for outside use), you can do it immediately--there is no need to wait until the library is loaded. If you need to call functions defined by that library, you should load the library, preferably with `require' (*note Named Features::). But it is OK to use `eval-after-load' in your personal customizations if you don't feel that they must meet the design standards for programs meant for wider use. -- Variable: after-load-alist This variable stores an alist built by `eval-after-load', containing the expressions to evaluate when certain libraries are loaded. Each element looks like this: (REGEXP-OR-FEATURE FORMS...) The key REGEXP-OR-FEATURE is either a regular expression or a symbol, and the value is a list of forms. The forms are evaluated when the key matches the absolute true name or feature name of the library being loaded.  File: elisp, Node: Byte Compilation, Next: Advising Functions, Prev: Loading, Up: Top 16 Byte Compilation ******************* Emacs Lisp has a "compiler" that translates functions written in Lisp into a special representation called "byte-code" that can be executed more efficiently. The compiler replaces Lisp function definitions with byte-code. When a byte-code function is called, its definition is evaluated by the "byte-code interpreter". Because the byte-compiled code is evaluated by the byte-code interpreter, instead of being executed directly by the machine's hardware (as true compiled code is), byte-code is completely transportable from machine to machine without recompilation. It is not, however, as fast as true compiled code. Compiling a Lisp file with the Emacs byte compiler always reads the file as multibyte text, even if Emacs was started with `--unibyte', unless the file specifies otherwise. This is so that compilation gives results compatible with running the same file without compilation. *Note Loading Non-ASCII::. In general, any version of Emacs can run byte-compiled code produced by recent earlier versions of Emacs, but the reverse is not true. If you do not want a Lisp file to be compiled, ever, put a file-local variable binding for `no-byte-compile' into it, like this: ;; -*-no-byte-compile: t; -*- *Note Compilation Errors::, for how to investigate errors occurring in byte compilation. * Menu: * Speed of Byte-Code:: An example of speedup from byte compilation. * Compilation Functions:: Byte compilation functions. * Docs and Compilation:: Dynamic loading of documentation strings. * Dynamic Loading:: Dynamic loading of individual functions. * Eval During Compile:: Code to be evaluated when you compile. * Compiler Errors:: Handling compiler error messages. * Byte-Code Objects:: The data type used for byte-compiled functions. * Disassembly:: Disassembling byte-code; how to read byte-code.  File: elisp, Node: Speed of Byte-Code, Next: Compilation Functions, Up: Byte Compilation 16.1 Performance of Byte-Compiled Code ====================================== A byte-compiled function is not as efficient as a primitive function written in C, but runs much faster than the version written in Lisp. Here is an example: (defun silly-loop (n) "Return time before and after N iterations of a loop." (let ((t1 (current-time-string))) (while (> (setq n (1- n)) 0)) (list t1 (current-time-string)))) => silly-loop (silly-loop 50000000) => ("Wed Mar 11 21:10:19 2009" "Wed Mar 11 21:10:41 2009") ; 22 seconds (byte-compile 'silly-loop) => [Compiled code not shown] (silly-loop 50000000) => ("Wed Mar 11 21:12:26 2009" "Wed Mar 11 21:12:32 2009") ; 6 seconds In this example, the interpreted code required 22 seconds to run, whereas the byte-compiled code required 6 seconds. These results are representative, but actual results will vary greatly.  File: elisp, Node: Compilation Functions, Next: Docs and Compilation, Prev: Speed of Byte-Code, Up: Byte Compilation 16.2 The Compilation Functions ============================== You can byte-compile an individual function or macro definition with the `byte-compile' function. You can compile a whole file with `byte-compile-file', or several files with `byte-recompile-directory' or `batch-byte-compile'. The byte compiler produces error messages and warnings about each file in a buffer called `*Compile-Log*'. These report things in your program that suggest a problem but are not necessarily erroneous. Be careful when writing macro calls in files that you may someday byte-compile. Macro calls are expanded when they are compiled, so the macros must already be defined for proper compilation. For more details, see *note Compiling Macros::. If a program does not work the same way when compiled as it does when interpreted, erroneous macro definitions are one likely cause (*note Problems with Macros::). Inline (`defsubst') functions are less troublesome; if you compile a call to such a function before its definition is known, the call will still work right, it will just run slower. Normally, compiling a file does not evaluate the file's contents or load the file. But it does execute any `require' calls at top level in the file. One way to ensure that necessary macro definitions are available during compilation is to require the file that defines them (*note Named Features::). To avoid loading the macro definition files when someone _runs_ the compiled program, write `eval-when-compile' around the `require' calls (*note Eval During Compile::). -- Function: byte-compile symbol This function byte-compiles the function definition of SYMBOL, replacing the previous definition with the compiled one. The function definition of SYMBOL must be the actual code for the function; i.e., the compiler does not follow indirection to another symbol. `byte-compile' returns the new, compiled definition of SYMBOL. If SYMBOL's definition is a byte-code function object, `byte-compile' does nothing and returns `nil'. Lisp records only one function definition for any symbol, and if that is already compiled, non-compiled code is not available anywhere. So there is no way to "compile the same definition again." (defun factorial (integer) "Compute factorial of INTEGER." (if (= 1 integer) 1 (* integer (factorial (1- integer))))) => factorial (byte-compile 'factorial) => #[(integer) "^H\301U\203^H^@\301\207\302^H\303^HS!\"\207" [integer 1 * factorial] 4 "Compute factorial of INTEGER."] The result is a byte-code function object. The string it contains is the actual byte-code; each character in it is an instruction or an operand of an instruction. The vector contains all the constants, variable names and function names used by the function, except for certain primitives that are coded as special instructions. If the argument to `byte-compile' is a `lambda' expression, it returns the corresponding compiled code, but does not store it anywhere. -- Command: compile-defun &optional arg This command reads the defun containing point, compiles it, and evaluates the result. If you use this on a defun that is actually a function definition, the effect is to install a compiled version of that function. `compile-defun' normally displays the result of evaluation in the echo area, but if ARG is non-`nil', it inserts the result in the current buffer after the form it compiled. -- Command: byte-compile-file filename &optional load This function compiles a file of Lisp code named FILENAME into a file of byte-code. The output file's name is made by changing the `.el' suffix into `.elc'; if FILENAME does not end in `.el', it adds `.elc' to the end of FILENAME. Compilation works by reading the input file one form at a time. If it is a definition of a function or macro, the compiled function or macro definition is written out. Other forms are batched together, then each batch is compiled, and written so that its compiled code will be executed when the file is read. All comments are discarded when the input file is read. This command returns `t' if there were no errors and `nil' otherwise. When called interactively, it prompts for the file name. If LOAD is non-`nil', this command loads the compiled file after compiling it. Interactively, LOAD is the prefix argument. % ls -l push* -rw-r--r-- 1 lewis 791 Oct 5 20:31 push.el (byte-compile-file "~/emacs/push.el") => t % ls -l push* -rw-r--r-- 1 lewis 791 Oct 5 20:31 push.el -rw-rw-rw- 1 lewis 638 Oct 8 20:25 push.elc -- Command: byte-recompile-directory directory &optional flag force This command recompiles every `.el' file in DIRECTORY (or its subdirectories) that needs recompilation. A file needs recompilation if a `.elc' file exists but is older than the `.el' file. When a `.el' file has no corresponding `.elc' file, FLAG says what to do. If it is `nil', this command ignores these files. If FLAG is 0, it compiles them. If it is neither `nil' nor 0, it asks the user whether to compile each such file, and asks about each subdirectory as well. Interactively, `byte-recompile-directory' prompts for DIRECTORY and FLAG is the prefix argument. If FORCE is non-`nil', this command recompiles every `.el' file that has a `.elc' file. The returned value is unpredictable. -- Function: batch-byte-compile &optional noforce This function runs `byte-compile-file' on files specified on the command line. This function must be used only in a batch execution of Emacs, as it kills Emacs on completion. An error in one file does not prevent processing of subsequent files, but no output file will be generated for it, and the Emacs process will terminate with a nonzero status code. If NOFORCE is non-`nil', this function does not recompile files that have an up-to-date `.elc' file. % emacs -batch -f batch-byte-compile *.el -- Function: byte-code code-string data-vector max-stack This function actually interprets byte-code. A byte-compiled function is actually defined with a body that calls `byte-code'. Don't call this function yourself--only the byte compiler knows how to generate valid calls to this function. In Emacs version 18, byte-code was always executed by way of a call to the function `byte-code'. Nowadays, byte-code is usually executed as part of a byte-code function object, and only rarely through an explicit call to `byte-code'.  File: elisp, Node: Docs and Compilation, Next: Dynamic Loading, Prev: Compilation Functions, Up: Byte Compilation 16.3 Documentation Strings and Compilation ========================================== Functions and variables loaded from a byte-compiled file access their documentation strings dynamically from the file whenever needed. This saves space within Emacs, and makes loading faster because the documentation strings themselves need not be processed while loading the file. Actual access to the documentation strings becomes slower as a result, but this normally is not enough to bother users. Dynamic access to documentation strings does have drawbacks: * If you delete or move the compiled file after loading it, Emacs can no longer access the documentation strings for the functions and variables in the file. * If you alter the compiled file (such as by compiling a new version), then further access to documentation strings in this file will probably give nonsense results. If your site installs Emacs following the usual procedures, these problems will never normally occur. Installing a new version uses a new directory with a different name; as long as the old version remains installed, its files will remain unmodified in the places where they are expected to be. However, if you have built Emacs yourself and use it from the directory where you built it, you will experience this problem occasionally if you edit and recompile Lisp files. When it happens, you can cure the problem by reloading the file after recompiling it. You can turn off this feature at compile time by setting `byte-compile-dynamic-docstrings' to `nil'; this is useful mainly if you expect to change the file, and you want Emacs processes that have already loaded it to keep working when the file changes. You can do this globally, or for one source file by specifying a file-local binding for the variable. One way to do that is by adding this string to the file's first line: -*-byte-compile-dynamic-docstrings: nil;-*- -- Variable: byte-compile-dynamic-docstrings If this is non-`nil', the byte compiler generates compiled files that are set up for dynamic loading of documentation strings. The dynamic documentation string feature writes compiled files that use a special Lisp reader construct, `#@COUNT'. This construct skips the next COUNT characters. It also uses the `#$' construct, which stands for "the name of this file, as a string." It is usually best not to use these constructs in Lisp source files, since they are not designed to be clear to humans reading the file.  File: elisp, Node: Dynamic Loading, Next: Eval During Compile, Prev: Docs and Compilation, Up: Byte Compilation 16.4 Dynamic Loading of Individual Functions ============================================ When you compile a file, you can optionally enable the "dynamic function loading" feature (also known as "lazy loading"). With dynamic function loading, loading the file doesn't fully read the function definitions in the file. Instead, each function definition contains a place-holder which refers to the file. The first time each function is called, it reads the full definition from the file, to replace the place-holder. The advantage of dynamic function loading is that loading the file becomes much faster. This is a good thing for a file which contains many separate user-callable functions, if using one of them does not imply you will probably also use the rest. A specialized mode which provides many keyboard commands often has that usage pattern: a user may invoke the mode, but use only a few of the commands it provides. The dynamic loading feature has certain disadvantages: * If you delete or move the compiled file after loading it, Emacs can no longer load the remaining function definitions not already loaded. * If you alter the compiled file (such as by compiling a new version), then trying to load any function not already loaded will usually yield nonsense results. These problems will never happen in normal circumstances with installed Emacs files. But they are quite likely to happen with Lisp files that you are changing. The easiest way to prevent these problems is to reload the new compiled file immediately after each recompilation. The byte compiler uses the dynamic function loading feature if the variable `byte-compile-dynamic' is non-`nil' at compilation time. Do not set this variable globally, since dynamic loading is desirable only for certain files. Instead, enable the feature for specific source files with file-local variable bindings. For example, you could do it by writing this text in the source file's first line: -*-byte-compile-dynamic: t;-*- -- Variable: byte-compile-dynamic If this is non-`nil', the byte compiler generates compiled files that are set up for dynamic function loading. -- Function: fetch-bytecode function If FUNCTION is a byte-code function object, this immediately finishes loading the byte code of FUNCTION from its byte-compiled file, if it is not fully loaded already. Otherwise, it does nothing. It always returns FUNCTION.  File: elisp, Node: Eval During Compile, Next: Compiler Errors, Prev: Dynamic Loading, Up: Byte Compilation 16.5 Evaluation During Compilation ================================== These features permit you to write code to be evaluated during compilation of a program. -- Special Form: eval-and-compile body... This form marks BODY to be evaluated both when you compile the containing code and when you run it (whether compiled or not). You can get a similar result by putting BODY in a separate file and referring to that file with `require'. That method is preferable when BODY is large. Effectively `require' is automatically `eval-and-compile', the package is loaded both when compiling and executing. `autoload' is also effectively `eval-and-compile' too. It's recognized when compiling, so uses of such a function don't produce "not known to be defined" warnings. Most uses of `eval-and-compile' are fairly sophisticated. If a macro has a helper function to build its result, and that macro is used both locally and outside the package, then `eval-and-compile' should be used to get the helper both when compiling and then later when running. If functions are defined programmatically (with `fset' say), then `eval-and-compile' can be used to have that done at compile-time as well as run-time, so calls to those functions are checked (and warnings about "not known to be defined" suppressed). -- Special Form: eval-when-compile body... This form marks BODY to be evaluated at compile time but not when the compiled program is loaded. The result of evaluation by the compiler becomes a constant which appears in the compiled program. If you load the source file, rather than compiling it, BODY is evaluated normally. If you have a constant that needs some calculation to produce, `eval-when-compile' can do that at compile-time. For example, (defvar my-regexp (eval-when-compile (regexp-opt '("aaa" "aba" "abb")))) If you're using another package, but only need macros from it (the byte compiler will expand those), then `eval-when-compile' can be used to load it for compiling, but not executing. For example, (eval-when-compile (require 'my-macro-package)) ;; only macros needed from this The same sort of thing goes for macros and `defsubst' functions defined locally and only for use within the file. They are needed for compiling the file, but in most cases they are not needed for execution of the compiled file. For example, (eval-when-compile (unless (fboundp 'some-new-thing) (defmacro 'some-new-thing () (compatibility code)))) This is often good for code that's only a fallback for compatibility with other versions of Emacs. *Common Lisp Note:* At top level, `eval-when-compile' is analogous to the Common Lisp idiom `(eval-when (compile eval) ...)'. Elsewhere, the Common Lisp `#.' reader macro (but not when interpreting) is closer to what `eval-when-compile' does.  File: elisp, Node: Compiler Errors, Next: Byte-Code Objects, Prev: Eval During Compile, Up: Byte Compilation 16.6 Compiler Errors ==================== Byte compilation outputs all errors and warnings into the buffer `*Compile-Log*'. The messages include file names and line numbers that identify the location of the problem. The usual Emacs commands for operating on compiler diagnostics work properly on these messages. However, the warnings about functions that were used but not defined are always "located" at the end of the file, so these commands won't find the places they are really used. To do that, you must search for the function names. You can suppress the compiler warning for calling an undefined function FUNC by conditionalizing the function call on an `fboundp' test, like this: (if (fboundp 'FUNC) ...(FUNC ...)...) The call to FUNC must be in the THEN-FORM of the `if', and FUNC must appear quoted in the call to `fboundp'. (This feature operates for `cond' as well.) You can tell the compiler that a function is defined using `declare-function' (*note Declaring Functions::). Likewise, you can tell the compiler that a variable is defined using `defvar' with no initial value. You can suppress the compiler warning for a specific use of an undefined variable VARIABLE by conditionalizing its use on a `boundp' test, like this: (if (boundp 'VARIABLE) ...VARIABLE...) The reference to VARIABLE must be in the THEN-FORM of the `if', and VARIABLE must appear quoted in the call to `boundp'. You can suppress any and all compiler warnings within a certain expression using the construct `with-no-warnings': -- Special Form: with-no-warnings body... In execution, this is equivalent to `(progn BODY...)', but the compiler does not issue warnings for anything that occurs inside BODY. We recommend that you use this construct around the smallest possible piece of code, to avoid missing possible warnings other than one one you intend to suppress. More precise control of warnings is possible by setting the variable `byte-compile-warnings'.  File: elisp, Node: Byte-Code Objects, Next: Disassembly, Prev: Compiler Errors, Up: Byte Compilation 16.7 Byte-Code Function Objects =============================== Byte-compiled functions have a special data type: they are "byte-code function objects". Internally, a byte-code function object is much like a vector; however, the evaluator handles this data type specially when it appears as a function to be called. The printed representation for a byte-code function object is like that for a vector, with an additional `#' before the opening `['. A byte-code function object must have at least four elements; there is no maximum number, but only the first six elements have any normal use. They are: ARGLIST The list of argument symbols. BYTE-CODE The string containing the byte-code instructions. CONSTANTS The vector of Lisp objects referenced by the byte code. These include symbols used as function names and variable names. STACKSIZE The maximum stack size this function needs. DOCSTRING The documentation string (if any); otherwise, `nil'. The value may be a number or a list, in case the documentation string is stored in a file. Use the function `documentation' to get the real documentation string (*note Accessing Documentation::). INTERACTIVE The interactive spec (if any). This can be a string or a Lisp expression. It is `nil' for a function that isn't interactive. Here's an example of a byte-code function object, in printed representation. It is the definition of the command `backward-sexp'. #[(&optional arg) "^H\204^F^@\301^P\302^H[!\207" [arg 1 forward-sexp] 2 254435 "p"] The primitive way to create a byte-code object is with `make-byte-code': -- Function: make-byte-code &rest elements This function constructs and returns a byte-code function object with ELEMENTS as its elements. You should not try to come up with the elements for a byte-code function yourself, because if they are inconsistent, Emacs may crash when you call the function. Always leave it to the byte compiler to create these objects; it makes the elements consistent (we hope). You can access the elements of a byte-code object using `aref'; you can also use `vconcat' to create a vector with the same elements.  File: elisp, Node: Disassembly, Prev: Byte-Code Objects, Up: Byte Compilation 16.8 Disassembled Byte-Code =========================== People do not write byte-code; that job is left to the byte compiler. But we provide a disassembler to satisfy a cat-like curiosity. The disassembler converts the byte-compiled code into human-readable form. The byte-code interpreter is implemented as a simple stack machine. It pushes values onto a stack of its own, then pops them off to use them in calculations whose results are themselves pushed back on the stack. When a byte-code function returns, it pops a value off the stack and returns it as the value of the function. In addition to the stack, byte-code functions can use, bind, and set ordinary Lisp variables, by transferring values between variables and the stack. -- Command: disassemble object &optional buffer-or-name This command displays the disassembled code for OBJECT. In interactive use, or if BUFFER-OR-NAME is `nil' or omitted, the output goes in a buffer named `*Disassemble*'. If BUFFER-OR-NAME is non-`nil', it must be a buffer or the name of an existing buffer. Then the output goes there, at point, and point is left before the output. The argument OBJECT can be a function name, a lambda expression or a byte-code object. If it is a lambda expression, `disassemble' compiles it and disassembles the resulting compiled code. Here are two examples of using the `disassemble' function. We have added explanatory comments to help you relate the byte-code to the Lisp source; these do not appear in the output of `disassemble'. (defun factorial (integer) "Compute factorial of an integer." (if (= 1 integer) 1 (* integer (factorial (1- integer))))) => factorial (factorial 4) => 24 (disassemble 'factorial) -| byte-code for factorial: doc: Compute factorial of an integer. args: (integer) 0 varref integer ; Get the value of `integer' ; and push it onto the stack. 1 constant 1 ; Push 1 onto stack. 2 eqlsign ; Pop top two values off stack, compare ; them, and push result onto stack. 3 goto-if-nil 1 ; Pop and test top of stack; ; if `nil', go to 1, ; else continue. 6 constant 1 ; Push 1 onto top of stack. 7 return ; Return the top element ; of the stack. 8:1 varref integer ; Push value of `integer' onto stack. 9 constant factorial ; Push `factorial' onto stack. 10 varref integer ; Push value of `integer' onto stack. 11 sub1 ; Pop `integer', decrement value, ; push new value onto stack. 12 call 1 ; Call function `factorial' using ; the first (i.e., the top) element ; of the stack as the argument; ; push returned value onto stack. 13 mult ; Pop top two values off stack, multiply ; them, and push result onto stack. 14 return ; Return the top element of stack. The `silly-loop' function is somewhat more complex: (defun silly-loop (n) "Return time before and after N iterations of a loop." (let ((t1 (current-time-string))) (while (> (setq n (1- n)) 0)) (list t1 (current-time-string)))) => silly-loop (disassemble 'silly-loop) -| byte-code for silly-loop: doc: Return time before and after N iterations of a loop. args: (n) 0 constant current-time-string ; Push ; `current-time-string' ; onto top of stack. 1 call 0 ; Call `current-time-string' ; with no argument, ; pushing result onto stack. 2 varbind t1 ; Pop stack and bind `t1' ; to popped value. 3:1 varref n ; Get value of `n' from ; the environment and push ; the value onto the stack. 4 sub1 ; Subtract 1 from top of stack. 5 dup ; Duplicate the top of the stack; ; i.e., copy the top of ; the stack and push the ; copy onto the stack. 6 varset n ; Pop the top of the stack, ; and bind `n' to the value. ; In effect, the sequence `dup varset' ; copies the top of the stack ; into the value of `n' ; without popping it. 7 constant 0 ; Push 0 onto stack. 8 gtr ; Pop top two values off stack, ; test if N is greater than 0 ; and push result onto stack. 9 goto-if-not-nil 1 ; Goto 1 if `n' > 0 ; (this continues the while loop) ; else continue. 12 varref t1 ; Push value of `t1' onto stack. 13 constant current-time-string ; Push `current-time-string' ; onto top of stack. 14 call 0 ; Call `current-time-string' again. 15 unbind 1 ; Unbind `t1' in local environment. 16 list2 ; Pop top two elements off stack, ; create a list of them, ; and push list onto stack. 17 return ; Return value of the top of stack.  File: elisp, Node: Advising Functions, Next: Debugging, Prev: Byte Compilation, Up: Top 17 Advising Emacs Lisp Functions ******************************** The "advice" feature lets you add to the existing definition of a function, by "advising the function". This is a cleaner method for a library to customize functions defined within Emacs--cleaner than redefining the whole function. Each function can have multiple "pieces of advice", separately defined. Each defined piece of advice can be "enabled" or "disabled" explicitly. All the enabled pieces of advice for any given function actually take effect when you "activate" advice for that function, or when you define or redefine the function. Note that enabling a piece of advice and activating advice for a function are not the same thing. *Usage Note:* Advice is useful for altering the behavior of existing calls to an existing function. If you want the new behavior for new calls, or for key bindings, you should define a new function (or a new command) which uses the existing function. *Usage note:* Advising a function can cause confusion in debugging, since people who debug calls to the original function may not notice that it has been modified with advice. Therefore, if you have the possibility to change the code of that function (or ask someone to do so) to run a hook, please solve the problem that way. Advice should be reserved for the cases where you cannot get the function changed. In particular, this means that a file in Emacs should not put advice on a function in Emacs. There are currently a few exceptions to this convention, but we aim to correct them. * Menu: * Simple Advice:: A simple example to explain the basics of advice. * Defining Advice:: Detailed description of `defadvice'. * Around-Advice:: Wrapping advice around a function's definition. * Computed Advice:: ...is to `defadvice' as `fset' is to `defun'. * Activation of Advice:: Advice doesn't do anything until you activate it. * Enabling Advice:: You can enable or disable each piece of advice. * Preactivation:: Preactivation is a way of speeding up the loading of compiled advice. * Argument Access in Advice:: How advice can access the function's arguments. * Advising Primitives:: Accessing arguments when advising a primitive. * Combined Definition:: How advice is implemented.  File: elisp, Node: Simple Advice, Next: Defining Advice, Up: Advising Functions 17.1 A Simple Advice Example ============================ The command `next-line' moves point down vertically one or more lines; it is the standard binding of `C-n'. When used on the last line of the buffer, this command inserts a newline to create a line to move to if `next-line-add-newlines' is non-`nil' (its default is `nil'.) Suppose you wanted to add a similar feature to `previous-line', which would insert a new line at the beginning of the buffer for the command to move to (when `next-line-add-newlines' is non-`nil'). How could you do this? You could do it by redefining the whole function, but that is not modular. The advice feature provides a cleaner alternative: you can effectively add your code to the existing function definition, without actually changing or even seeing that definition. Here is how to do this: (defadvice previous-line (before next-line-at-end (&optional arg try-vscroll)) "Insert an empty line when moving up from the top line." (if (and next-line-add-newlines (= arg 1) (save-excursion (beginning-of-line) (bobp))) (progn (beginning-of-line) (newline)))) This expression defines a "piece of advice" for the function `previous-line'. This piece of advice is named `next-line-at-end', and the symbol `before' says that it is "before-advice" which should run before the regular definition of `previous-line'. `(&optional arg try-vscroll)' specifies how the advice code can refer to the function's arguments. When this piece of advice runs, it creates an additional line, in the situation where that is appropriate, but does not move point to that line. This is the correct way to write the advice, because the normal definition will run afterward and will move back to the newly inserted line. Defining the advice doesn't immediately change the function `previous-line'. That happens when you "activate" the advice, like this: (ad-activate 'previous-line) This is what actually begins to use the advice that has been defined so far for the function `previous-line'. Henceforth, whenever that function is run, whether invoked by the user with `C-p' or `M-x', or called from Lisp, it runs the advice first, and its regular definition second. This example illustrates before-advice, which is one "class" of advice: it runs before the function's base definition. There are two other advice classes: "after-advice", which runs after the base definition, and "around-advice", which lets you specify an expression to wrap around the invocation of the base definition.  File: elisp, Node: Defining Advice, Next: Around-Advice, Prev: Simple Advice, Up: Advising Functions 17.2 Defining Advice ==================== To define a piece of advice, use the macro `defadvice'. A call to `defadvice' has the following syntax, which is based on the syntax of `defun' and `defmacro', but adds more: (defadvice FUNCTION (CLASS NAME [POSITION] [ARGLIST] FLAGS...) [DOCUMENTATION-STRING] [INTERACTIVE-FORM] BODY-FORMS...) Here, FUNCTION is the name of the function (or macro or special form) to be advised. From now on, we will write just "function" when describing the entity being advised, but this always includes macros and special forms. In place of the argument list in an ordinary definition, an advice definition calls for several different pieces of information. CLASS specifies the "class" of the advice--one of `before', `after', or `around'. Before-advice runs before the function itself; after-advice runs after the function itself; around-advice is wrapped around the execution of the function itself. After-advice and around-advice can override the return value by setting `ad-return-value'. -- Variable: ad-return-value While advice is executing, after the function's original definition has been executed, this variable holds its return value, which will ultimately be returned to the caller after finishing all the advice. After-advice and around-advice can arrange to return some other value by storing it in this variable. The argument NAME is the name of the advice, a non-`nil' symbol. The advice name uniquely identifies one piece of advice, within all the pieces of advice in a particular class for a particular FUNCTION. The name allows you to refer to the piece of advice--to redefine it, or to enable or disable it. The optional POSITION specifies where, in the current list of advice of the specified CLASS, this new advice should be placed. It should be either `first', `last' or a number that specifies a zero-based position (`first' is equivalent to 0). If no position is specified, the default is `first'. Position values outside the range of existing positions in this class are mapped to the beginning or the end of the range, whichever is closer. The POSITION value is ignored when redefining an existing piece of advice. The optional ARGLIST can be used to define the argument list for the sake of advice. This becomes the argument list of the combined definition that is generated in order to run the advice (*note Combined Definition::). Therefore, the advice expressions can use the argument variables in this list to access argument values. The argument list used in advice need not be the same as the argument list used in the original function, but must be compatible with it, so that it can handle the ways the function is actually called. If two pieces of advice for a function both specify an argument list, they must specify the same argument list. *Note Argument Access in Advice::, for more information about argument lists and advice, and a more flexible way for advice to access the arguments. The remaining elements, FLAGS, are symbols that specify further information about how to use this piece of advice. Here are the valid symbols and their meanings: `activate' Activate the advice for FUNCTION now. Changes in a function's advice always take effect the next time you activate advice for the function; this flag says to do so, for FUNCTION, immediately after defining this piece of advice. This flag has no immediate effect if FUNCTION itself is not defined yet (a situation known as "forward advice"), because it is impossible to activate an undefined function's advice. However, defining FUNCTION will automatically activate its advice. `protect' Protect this piece of advice against non-local exits and errors in preceding code and advice. Protecting advice places it as a cleanup in an `unwind-protect' form, so that it will execute even if the previous code gets an error or uses `throw'. *Note Cleanups::. `compile' Compile the combined definition that is used to run the advice. This flag is ignored unless `activate' is also specified. *Note Combined Definition::. `disable' Initially disable this piece of advice, so that it will not be used unless subsequently explicitly enabled. *Note Enabling Advice::. `preactivate' Activate advice for FUNCTION when this `defadvice' is compiled or macroexpanded. This generates a compiled advised definition according to the current advice state, which will be used during activation if appropriate. *Note Preactivation::. This is useful only if this `defadvice' is byte-compiled. The optional DOCUMENTATION-STRING serves to document this piece of advice. When advice is active for FUNCTION, the documentation for FUNCTION (as returned by `documentation') combines the documentation strings of all the advice for FUNCTION with the documentation string of its original function definition. The optional INTERACTIVE-FORM form can be supplied to change the interactive behavior of the original function. If more than one piece of advice has an INTERACTIVE-FORM, then the first one (the one with the smallest position) found among all the advice takes precedence. The possibly empty list of BODY-FORMS specifies the body of the advice. The body of an advice can access or change the arguments, the return value, the binding environment, and perform any other kind of side effect. *Warning:* When you advise a macro, keep in mind that macros are expanded when a program is compiled, not when a compiled program is run. All subroutines used by the advice need to be available when the byte compiler expands the macro. -- Command: ad-unadvise function This command deletes the advice from FUNCTION. -- Command: ad-unadvise-all This command deletes all pieces of advice from all functions.  File: elisp, Node: Around-Advice, Next: Computed Advice, Prev: Defining Advice, Up: Advising Functions 17.3 Around-Advice ================== Around-advice lets you "wrap" a Lisp expression "around" the original function definition. You specify where the original function definition should go by means of the special symbol `ad-do-it'. Where this symbol occurs inside the around-advice body, it is replaced with a `progn' containing the forms of the surrounded code. Here is an example: (defadvice foo (around foo-around) "Ignore case in `foo'." (let ((case-fold-search t)) ad-do-it)) Its effect is to make sure that case is ignored in searches when the original definition of `foo' is run. -- Variable: ad-do-it This is not really a variable, rather a place-holder that looks like a variable. You use it in around-advice to specify the place to run the function's original definition and other "earlier" around-advice. If the around-advice does not use `ad-do-it', then it does not run the original function definition. This provides a way to override the original definition completely. (It also overrides lower-positioned pieces of around-advice). If the around-advice uses `ad-do-it' more than once, the original definition is run at each place. In this way, around-advice can execute the original definition (and lower-positioned pieces of around-advice) several times. Another way to do that is by using `ad-do-it' inside of a loop.  File: elisp, Node: Computed Advice, Next: Activation of Advice, Prev: Around-Advice, Up: Advising Functions 17.4 Computed Advice ==================== The macro `defadvice' resembles `defun' in that the code for the advice, and all other information about it, are explicitly stated in the source code. You can also create advice whose details are computed, using the function `ad-add-advice'. -- Function: ad-add-advice function advice class position Calling `ad-add-advice' adds ADVICE as a piece of advice to FUNCTION in class CLASS. The argument ADVICE has this form: (NAME PROTECTED ENABLED DEFINITION) Here, PROTECTED and ENABLED are flags; if PROTECTED is non-`nil', the advice is protected against non-local exits (*note Defining Advice::), and if ENABLED is `nil' the advice is initially disabled (*note Enabling Advice::). DEFINITION should have the form (advice . LAMBDA) where LAMBDA is a lambda expression; this lambda expression is called in order to perform the advice. *Note Lambda Expressions::. If the FUNCTION argument to `ad-add-advice' already has one or more pieces of advice in the specified CLASS, then POSITION specifies where in the list to put the new piece of advice. The value of POSITION can either be `first', `last', or a number (counting from 0 at the beginning of the list). Numbers outside the range are mapped to the beginning or the end of the range, whichever is closer. The POSITION value is ignored when redefining an existing piece of advice. If FUNCTION already has a piece of ADVICE with the same name, then the position argument is ignored and the old advice is replaced with the new one.  File: elisp, Node: Activation of Advice, Next: Enabling Advice, Prev: Computed Advice, Up: Advising Functions 17.5 Activation of Advice ========================= By default, advice does not take effect when you define it--only when you "activate" advice for the function that was advised. However, the advice will be activated automatically if you define or redefine the function later. You can request the activation of advice for a function when you define the advice, by specifying the `activate' flag in the `defadvice'. But normally you activate the advice for a function by calling the function `ad-activate' or one of the other activation commands listed below. Separating the activation of advice from the act of defining it permits you to add several pieces of advice to one function efficiently, without redefining the function over and over as each advice is added. More importantly, it permits defining advice for a function before that function is actually defined. When a function's advice is first activated, the function's original definition is saved, and all enabled pieces of advice for that function are combined with the original definition to make a new definition. (Pieces of advice that are currently disabled are not used; see *note Enabling Advice::.) This definition is installed, and optionally byte-compiled as well, depending on conditions described below. In all of the commands to activate advice, if COMPILE is `t' (or anything but `nil' or a negative number), the command also compiles the combined definition which implements the advice. If it is `nil' or a negative number, what happens depends on `ad-default-compilation-action' as described below. -- Command: ad-activate function &optional compile This command activates all the advice defined for FUNCTION. Activating advice does nothing if FUNCTION's advice is already active. But if there is new advice, added since the previous time you activated advice for FUNCTION, it activates the new advice. -- Command: ad-deactivate function This command deactivates the advice for FUNCTION. -- Command: ad-update function &optional compile This command activates the advice for FUNCTION if its advice is already activated. This is useful if you change the advice. -- Command: ad-activate-all &optional compile This command activates the advice for all functions. -- Command: ad-deactivate-all This command deactivates the advice for all functions. -- Command: ad-update-all &optional compile This command activates the advice for all functions whose advice is already activated. This is useful if you change the advice of some functions. -- Command: ad-activate-regexp regexp &optional compile This command activates all pieces of advice whose names match REGEXP. More precisely, it activates all advice for any function which has at least one piece of advice that matches REGEXP. -- Command: ad-deactivate-regexp regexp This command deactivates all pieces of advice whose names match REGEXP. More precisely, it deactivates all advice for any function which has at least one piece of advice that matches REGEXP. -- Command: ad-update-regexp regexp &optional compile This command activates pieces of advice whose names match REGEXP, but only those for functions whose advice is already activated. Reactivating a function's advice is useful for putting into effect all the changes that have been made in its advice (including enabling and disabling specific pieces of advice; *note Enabling Advice::) since the last time it was activated. -- Command: ad-start-advice Turn on automatic advice activation when a function is defined or redefined. This is the default mode. -- Command: ad-stop-advice Turn off automatic advice activation when a function is defined or redefined. -- User Option: ad-default-compilation-action This variable controls whether to compile the combined definition that results from activating advice for a function. A value of `always' specifies to compile unconditionally. A value of `never' specifies never compile the advice. A value of `maybe' specifies to compile if the byte compiler is already loaded. A value of `like-original' specifies to compile the advice if the original definition of the advised function is compiled or a built-in function. This variable takes effect only if the COMPILE argument of `ad-activate' (or any of the above functions) did not force compilation. If the advised definition was constructed during "preactivation" (*note Preactivation::), then that definition must already be compiled, because it was constructed during byte-compilation of the file that contained the `defadvice' with the `preactivate' flag.  File: elisp, Node: Enabling Advice, Next: Preactivation, Prev: Activation of Advice, Up: Advising Functions 17.6 Enabling and Disabling Advice ================================== Each piece of advice has a flag that says whether it is enabled or not. By enabling or disabling a piece of advice, you can turn it on and off without having to undefine and redefine it. For example, here is how to disable a particular piece of advice named `my-advice' for the function `foo': (ad-disable-advice 'foo 'before 'my-advice) This function by itself only changes the enable flag for a piece of advice. To make the change take effect in the advised definition, you must activate the advice for `foo' again: (ad-activate 'foo) -- Command: ad-disable-advice function class name This command disables the piece of advice named NAME in class CLASS on FUNCTION. -- Command: ad-enable-advice function class name This command enables the piece of advice named NAME in class CLASS on FUNCTION. You can also disable many pieces of advice at once, for various functions, using a regular expression. As always, the changes take real effect only when you next reactivate advice for the functions in question. -- Command: ad-disable-regexp regexp This command disables all pieces of advice whose names match REGEXP, in all classes, on all functions. -- Command: ad-enable-regexp regexp This command enables all pieces of advice whose names match REGEXP, in all classes, on all functions.  File: elisp, Node: Preactivation, Next: Argument Access in Advice, Prev: Enabling Advice, Up: Advising Functions 17.7 Preactivation ================== Constructing a combined definition to execute advice is moderately expensive. When a library advises many functions, this can make loading the library slow. In that case, you can use "preactivation" to construct suitable combined definitions in advance. To use preactivation, specify the `preactivate' flag when you define the advice with `defadvice'. This `defadvice' call creates a combined definition which embodies this piece of advice (whether enabled or not) plus any other currently enabled advice for the same function, and the function's own definition. If the `defadvice' is compiled, that compiles the combined definition also. When the function's advice is subsequently activated, if the enabled advice for the function matches what was used to make this combined definition, then the existing combined definition is used, thus avoiding the need to construct one. Thus, preactivation never causes wrong results--but it may fail to do any good, if the enabled advice at the time of activation doesn't match what was used for preactivation. Here are some symptoms that can indicate that a preactivation did not work properly, because of a mismatch. * Activation of the advised function takes longer than usual. * The byte compiler gets loaded while an advised function gets activated. * `byte-compile' is included in the value of `features' even though you did not ever explicitly use the byte compiler. Compiled preactivated advice works properly even if the function itself is not defined until later; however, the function needs to be defined when you _compile_ the preactivated advice. There is no elegant way to find out why preactivated advice is not being used. What you can do is to trace the function `ad-cache-id-verification-code' (with the function `trace-function-background') before the advised function's advice is activated. After activation, check the value returned by `ad-cache-id-verification-code' for that function: `verified' means that the preactivated advice was used, while other values give some information about why they were considered inappropriate. *Warning:* There is one known case that can make preactivation fail, in that a preconstructed combined definition is used even though it fails to match the current state of advice. This can happen when two packages define different pieces of advice with the same name, in the same class, for the same function. But you should avoid that anyway.  File: elisp, Node: Argument Access in Advice, Next: Advising Primitives, Prev: Preactivation, Up: Advising Functions 17.8 Argument Access in Advice ============================== The simplest way to access the arguments of an advised function in the body of a piece of advice is to use the same names that the function definition uses. To do this, you need to know the names of the argument variables of the original function. While this simple method is sufficient in many cases, it has a disadvantage: it is not robust, because it hard-codes the argument names into the advice. If the definition of the original function changes, the advice might break. Another method is to specify an argument list in the advice itself. This avoids the need to know the original function definition's argument names, but it has a limitation: all the advice on any particular function must use the same argument list, because the argument list actually used for all the advice comes from the first piece of advice for that function. A more robust method is to use macros that are translated into the proper access forms at activation time, i.e., when constructing the advised definition. Access macros access actual arguments by their (zero-based) position, regardless of how these actual arguments get distributed onto the argument variables of a function. This is robust because in Emacs Lisp the meaning of an argument is strictly determined by its position in the argument list. -- Macro: ad-get-arg position This returns the actual argument that was supplied at POSITION. -- Macro: ad-get-args position This returns the list of actual arguments supplied starting at POSITION. -- Macro: ad-set-arg position value This sets the value of the actual argument at POSITION to VALUE -- Macro: ad-set-args position value-list This sets the list of actual arguments starting at POSITION to VALUE-LIST. Now an example. Suppose the function `foo' is defined as (defun foo (x y &optional z &rest r) ...) and is then called with (foo 0 1 2 3 4 5 6) which means that X is 0, Y is 1, Z is 2 and R is `(3 4 5 6)' within the body of `foo'. Here is what `ad-get-arg' and `ad-get-args' return in this case: (ad-get-arg 0) => 0 (ad-get-arg 1) => 1 (ad-get-arg 2) => 2 (ad-get-arg 3) => 3 (ad-get-args 2) => (2 3 4 5 6) (ad-get-args 4) => (4 5 6) Setting arguments also makes sense in this example: (ad-set-arg 5 "five") has the effect of changing the sixth argument to `"five"'. If this happens in advice executed before the body of `foo' is run, then R will be `(3 4 "five" 6)' within that body. Here is an example of setting a tail of the argument list: (ad-set-args 0 '(5 4 3 2 1 0)) If this happens in advice executed before the body of `foo' is run, then within that body, X will be 5, Y will be 4, Z will be 3, and R will be `(2 1 0)' inside the body of `foo'. These argument constructs are not really implemented as Lisp macros. Instead they are implemented specially by the advice mechanism.  File: elisp, Node: Advising Primitives, Next: Combined Definition, Prev: Argument Access in Advice, Up: Advising Functions 17.9 Advising Primitives ======================== Advising a primitive function (*note What Is a Function::) is risky. Some primitive functions are used by the advice mechanism; advising them could cause an infinite recursion. Also, many primitive functions are called directly from C code. Calls to the primitive from Lisp code will take note of the advice, but calls from C code will ignore the advice. When the advice facility constructs the combined definition, it needs to know the argument list of the original function. This is not always possible for primitive functions. When advice cannot determine the argument list, it uses `(&rest ad-subr-args)', which always works but is inefficient because it constructs a list of the argument values. You can use `ad-define-subr-args' to declare the proper argument names for a primitive function: -- Function: ad-define-subr-args function arglist This function specifies that ARGLIST should be used as the argument list for function FUNCTION. For example, (ad-define-subr-args 'fset '(sym newdef)) specifies the argument list for the function `fset'.  File: elisp, Node: Combined Definition, Prev: Advising Primitives, Up: Advising Functions 17.10 The Combined Definition ============================= Suppose that a function has N pieces of before-advice (numbered from 0 through N-1), M pieces of around-advice and K pieces of after-advice. Assuming no piece of advice is protected, the combined definition produced to implement the advice for a function looks like this: (lambda ARGLIST [ [ADVISED-DOCSTRING] [(interactive ...)] ] (let (ad-return-value) before-0-body-form... .... before-N-1-body-form... around-0-body-form... around-1-body-form... .... around-M-1-body-form... (setq ad-return-value apply original definition to ARGLIST) end-of-around-M-1-body-form... .... end-of-around-1-body-form... end-of-around-0-body-form... after-0-body-form... .... after-K-1-body-form... ad-return-value)) Macros are redefined as macros, which means adding `macro' to the beginning of the combined definition. The interactive form is present if the original function or some piece of advice specifies one. When an interactive primitive function is advised, advice uses a special method: it calls the primitive with `call-interactively' so that it will read its own arguments. In this case, the advice cannot access the arguments. The body forms of the various advice in each class are assembled according to their specified order. The forms of around-advice L are included in one of the forms of around-advice L - 1. The innermost part of the around advice onion is apply original definition to ARGLIST whose form depends on the type of the original function. The variable `ad-return-value' is set to whatever this returns. The variable is visible to all pieces of advice, which can access and modify it before it is actually returned from the advised function. The semantic structure of advised functions that contain protected pieces of advice is the same. The only difference is that `unwind-protect' forms ensure that the protected advice gets executed even if some previous piece of advice had an error or a non-local exit. If any around-advice is protected, then the whole around-advice onion is protected as a result.  File: elisp, Node: Debugging, Next: Read and Print, Prev: Advising Functions, Up: Top 18 Debugging Lisp Programs ************************** There are three ways to investigate a problem in an Emacs Lisp program, depending on what you are doing with the program when the problem appears. * If the problem occurs when you run the program, you can use a Lisp debugger to investigate what is happening during execution. In addition to the ordinary debugger, Emacs comes with a source-level debugger, Edebug. This chapter describes both of them. * If the problem is syntactic, so that Lisp cannot even read the program, you can use the Emacs facilities for editing Lisp to localize it. * If the problem occurs when trying to compile the program with the byte compiler, you need to know how to examine the compiler's input buffer. * Menu: * Debugger:: How the Emacs Lisp debugger is implemented. * Edebug:: A source-level Emacs Lisp debugger. * Syntax Errors:: How to find syntax errors. * Test Coverage:: Ensuring you have tested all branches in your code. * Compilation Errors:: How to find errors that show up in byte compilation. Another useful debugging tool is the dribble file. When a dribble file is open, Emacs copies all keyboard input characters to that file. Afterward, you can examine the file to find out what input was used. *Note Terminal Input::. For debugging problems in terminal descriptions, the `open-termscript' function can be useful. *Note Terminal Output::.  File: elisp, Node: Debugger, Next: Edebug, Up: Debugging 18.1 The Lisp Debugger ====================== The ordinary "Lisp debugger" provides the ability to suspend evaluation of a form. While evaluation is suspended (a state that is commonly known as a "break"), you may examine the run time stack, examine the values of local or global variables, or change those values. Since a break is a recursive edit, all the usual editing facilities of Emacs are available; you can even run programs that will enter the debugger recursively. *Note Recursive Editing::. * Menu: * Error Debugging:: Entering the debugger when an error happens. * Infinite Loops:: Stopping and debugging a program that doesn't exit. * Function Debugging:: Entering it when a certain function is called. * Explicit Debug:: Entering it at a certain point in the program. * Using Debugger:: What the debugger does; what you see while in it. * Debugger Commands:: Commands used while in the debugger. * Invoking the Debugger:: How to call the function `debug'. * Internals of Debugger:: Subroutines of the debugger, and global variables.  File: elisp, Node: Error Debugging, Next: Infinite Loops, Up: Debugger 18.1.1 Entering the Debugger on an Error ---------------------------------------- The most important time to enter the debugger is when a Lisp error happens. This allows you to investigate the immediate causes of the error. However, entry to the debugger is not a normal consequence of an error. Many commands frequently cause Lisp errors when invoked inappropriately, and during ordinary editing it would be very inconvenient to enter the debugger each time this happens. So if you want errors to enter the debugger, set the variable `debug-on-error' to non-`nil'. (The command `toggle-debug-on-error' provides an easy way to do this.) -- User Option: debug-on-error This variable determines whether the debugger is called when an error is signaled and not handled. If `debug-on-error' is `t', all kinds of errors call the debugger, except those listed in `debug-ignored-errors' (see below). If it is `nil', none call the debugger. (Note that `eval-expression-debug-on-error' affects the setting of this variable in some cases; see below.) The value can also be a list of error conditions that should call the debugger. For example, if you set it to the list `(void-variable)', then only errors about a variable that has no value invoke the debugger. When this variable is non-`nil', Emacs does not create an error handler around process filter functions and sentinels. Therefore, errors in these functions also invoke the debugger. *Note Processes::. -- User Option: debug-ignored-errors This variable specifies certain kinds of errors that should not enter the debugger. Its value is a list of error condition symbols and/or regular expressions. If the error has any of those condition symbols, or if the error message matches any of the regular expressions, then that error does not enter the debugger, regardless of the value of `debug-on-error'. The normal value of this variable lists several errors that happen often during editing but rarely result from bugs in Lisp programs. However, "rarely" is not "never"; if your program fails with an error that matches this list, you will need to change this list in order to debug the error. The easiest way is usually to set `debug-ignored-errors' to `nil'. -- User Option: eval-expression-debug-on-error If this variable has a non-`nil' value, then `debug-on-error' is set to `t' when evaluating with the command `eval-expression'. If `eval-expression-debug-on-error' is `nil', then the value of `debug-on-error' is not changed. *Note Evaluating Emacs-Lisp Expressions: (emacs)Lisp Eval. -- User Option: debug-on-signal Normally, errors that are caught by `condition-case' never run the debugger, even if `debug-on-error' is non-`nil'. In other words, `condition-case' gets a chance to handle the error before the debugger gets a chance. If you set `debug-on-signal' to a non-`nil' value, then the debugger gets the first chance at every error; an error will invoke the debugger regardless of any `condition-case', if it fits the criteria specified by the values of `debug-on-error' and `debug-ignored-errors'. *Warning:* This variable is strong medicine! Various parts of Emacs handle errors in the normal course of affairs, and you may not even realize that errors happen there. If you set `debug-on-signal' to a non-`nil' value, those errors will enter the debugger. *Warning:* `debug-on-signal' has no effect when `debug-on-error' is `nil'. To debug an error that happens during loading of the init file, use the option `--debug-init'. This binds `debug-on-error' to `t' while loading the init file, and bypasses the `condition-case' which normally catches errors in the init file.  File: elisp, Node: Infinite Loops, Next: Function Debugging, Prev: Error Debugging, Up: Debugger 18.1.2 Debugging Infinite Loops ------------------------------- When a program loops infinitely and fails to return, your first problem is to stop the loop. On most operating systems, you can do this with `C-g', which causes a "quit". Ordinary quitting gives no information about why the program was looping. To get more information, you can set the variable `debug-on-quit' to non-`nil'. Quitting with `C-g' is not considered an error, and `debug-on-error' has no effect on the handling of `C-g'. Likewise, `debug-on-quit' has no effect on errors. Once you have the debugger running in the middle of the infinite loop, you can proceed from the debugger using the stepping commands. If you step through the entire loop, you will probably get enough information to solve the problem. -- User Option: debug-on-quit This variable determines whether the debugger is called when `quit' is signaled and not handled. If `debug-on-quit' is non-`nil', then the debugger is called whenever you quit (that is, type `C-g'). If `debug-on-quit' is `nil', then the debugger is not called when you quit. *Note Quitting::.  File: elisp, Node: Function Debugging, Next: Explicit Debug, Prev: Infinite Loops, Up: Debugger 18.1.3 Entering the Debugger on a Function Call ----------------------------------------------- To investigate a problem that happens in the middle of a program, one useful technique is to enter the debugger whenever a certain function is called. You can do this to the function in which the problem occurs, and then step through the function, or you can do this to a function called shortly before the problem, step quickly over the call to that function, and then step through its caller. -- Command: debug-on-entry function-name This function requests FUNCTION-NAME to invoke the debugger each time it is called. It works by inserting the form `(implement-debug-on-entry)' into the function definition as the first form. Any function or macro defined as Lisp code may be set to break on entry, regardless of whether it is interpreted code or compiled code. If the function is a command, it will enter the debugger when called from Lisp and when called interactively (after the reading of the arguments). You can also set debug-on-entry for primitive functions (i.e., those written in C) this way, but it only takes effect when the primitive is called from Lisp code. Debug-on-entry is not allowed for special forms. When `debug-on-entry' is called interactively, it prompts for FUNCTION-NAME in the minibuffer. If the function is already set up to invoke the debugger on entry, `debug-on-entry' does nothing. `debug-on-entry' always returns FUNCTION-NAME. *Warning:* if you redefine a function after using `debug-on-entry' on it, the code to enter the debugger is discarded by the redefinition. In effect, redefining the function cancels the break-on-entry feature for that function. Here's an example to illustrate use of this function: (defun fact (n) (if (zerop n) 1 (* n (fact (1- n))))) => fact (debug-on-entry 'fact) => fact (fact 3) ------ Buffer: *Backtrace* ------ Debugger entered--entering a function: * fact(3) eval((fact 3)) eval-last-sexp-1(nil) eval-last-sexp(nil) call-interactively(eval-last-sexp) ------ Buffer: *Backtrace* ------ (symbol-function 'fact) => (lambda (n) (debug (quote debug)) (if (zerop n) 1 (* n (fact (1- n))))) -- Command: cancel-debug-on-entry &optional function-name This function undoes the effect of `debug-on-entry' on FUNCTION-NAME. When called interactively, it prompts for FUNCTION-NAME in the minibuffer. If FUNCTION-NAME is omitted or `nil', it cancels break-on-entry for all functions. Calling `cancel-debug-on-entry' does nothing to a function which is not currently set up to break on entry.  File: elisp, Node: Explicit Debug, Next: Using Debugger, Prev: Function Debugging, Up: Debugger 18.1.4 Explicit Entry to the Debugger ------------------------------------- You can cause the debugger to be called at a certain point in your program by writing the expression `(debug)' at that point. To do this, visit the source file, insert the text `(debug)' at the proper place, and type `C-M-x' (`eval-defun', a Lisp mode key binding). *Warning:* if you do this for temporary debugging purposes, be sure to undo this insertion before you save the file! The place where you insert `(debug)' must be a place where an additional form can be evaluated and its value ignored. (If the value of `(debug)' isn't ignored, it will alter the execution of the program!) The most common suitable places are inside a `progn' or an implicit `progn' (*note Sequencing::).  File: elisp, Node: Using Debugger, Next: Debugger Commands, Prev: Explicit Debug, Up: Debugger 18.1.5 Using the Debugger ------------------------- When the debugger is entered, it displays the previously selected buffer in one window and a buffer named `*Backtrace*' in another window. The backtrace buffer contains one line for each level of Lisp function execution currently going on. At the beginning of this buffer is a message describing the reason that the debugger was invoked (such as the error message and associated data, if it was invoked due to an error). The backtrace buffer is read-only and uses a special major mode, Debugger mode, in which letters are defined as debugger commands. The usual Emacs editing commands are available; thus, you can switch windows to examine the buffer that was being edited at the time of the error, switch buffers, visit files, or do any other sort of editing. However, the debugger is a recursive editing level (*note Recursive Editing::) and it is wise to go back to the backtrace buffer and exit the debugger (with the `q' command) when you are finished with it. Exiting the debugger gets out of the recursive edit and kills the backtrace buffer. The backtrace buffer shows you the functions that are executing and their argument values. It also allows you to specify a stack frame by moving point to the line describing that frame. (A stack frame is the place where the Lisp interpreter records information about a particular invocation of a function.) The frame whose line point is on is considered the "current frame". Some of the debugger commands operate on the current frame. If a line starts with a star, that means that exiting that frame will call the debugger again. This is useful for examining the return value of a function. If a function name is underlined, that means the debugger knows where its source code is located. You can click `Mouse-2' on that name, or move to it and type , to visit the source code. The debugger itself must be run byte-compiled, since it makes assumptions about how many stack frames are used for the debugger itself. These assumptions are false if the debugger is running interpreted.  File: elisp, Node: Debugger Commands, Next: Invoking the Debugger, Prev: Using Debugger, Up: Debugger 18.1.6 Debugger Commands ------------------------ The debugger buffer (in Debugger mode) provides special commands in addition to the usual Emacs commands. The most important use of debugger commands is for stepping through code, so that you can see how control flows. The debugger can step through the control structures of an interpreted function, but cannot do so in a byte-compiled function. If you would like to step through a byte-compiled function, replace it with an interpreted definition of the same function. (To do this, visit the source for the function and type `C-M-x' on its definition.) You cannot use the Lisp debugger to step through a primitive function. Here is a list of Debugger mode commands: `c' Exit the debugger and continue execution. When continuing is possible, it resumes execution of the program as if the debugger had never been entered (aside from any side-effects that you caused by changing variable values or data structures while inside the debugger). Continuing is possible after entry to the debugger due to function entry or exit, explicit invocation, or quitting. You cannot continue if the debugger was entered because of an error. `d' Continue execution, but enter the debugger the next time any Lisp function is called. This allows you to step through the subexpressions of an expression, seeing what values the subexpressions compute, and what else they do. The stack frame made for the function call which enters the debugger in this way will be flagged automatically so that the debugger will be called again when the frame is exited. You can use the `u' command to cancel this flag. `b' Flag the current frame so that the debugger will be entered when the frame is exited. Frames flagged in this way are marked with stars in the backtrace buffer. `u' Don't enter the debugger when the current frame is exited. This cancels a `b' command on that frame. The visible effect is to remove the star from the line in the backtrace buffer. `j' Flag the current frame like `b'. Then continue execution like `c', but temporarily disable break-on-entry for all functions that are set up to do so by `debug-on-entry'. `e' Read a Lisp expression in the minibuffer, evaluate it, and print the value in the echo area. The debugger alters certain important variables, and the current buffer, as part of its operation; `e' temporarily restores their values from outside the debugger, so you can examine and change them. This makes the debugger more transparent. By contrast, `M-:' does nothing special in the debugger; it shows you the variable values within the debugger. `R' Like `e', but also save the result of evaluation in the buffer `*Debugger-record*'. `q' Terminate the program being debugged; return to top-level Emacs command execution. If the debugger was entered due to a `C-g' but you really want to quit, and not debug, use the `q' command. `r' Return a value from the debugger. The value is computed by reading an expression with the minibuffer and evaluating it. The `r' command is useful when the debugger was invoked due to exit from a Lisp call frame (as requested with `b' or by entering the frame with `d'); then the value specified in the `r' command is used as the value of that frame. It is also useful if you call `debug' and use its return value. Otherwise, `r' has the same effect as `c', and the specified return value does not matter. You can't use `r' when the debugger was entered due to an error. `l' Display a list of functions that will invoke the debugger when called. This is a list of functions that are set to break on entry by means of `debug-on-entry'. *Warning:* if you redefine such a function and thus cancel the effect of `debug-on-entry', it may erroneously show up in this list.  File: elisp, Node: Invoking the Debugger, Next: Internals of Debugger, Prev: Debugger Commands, Up: Debugger 18.1.7 Invoking the Debugger ---------------------------- Here we describe in full detail the function `debug' that is used to invoke the debugger. -- Function: debug &rest debugger-args This function enters the debugger. It switches buffers to a buffer named `*Backtrace*' (or `*Backtrace*<2>' if it is the second recursive entry to the debugger, etc.), and fills it with information about the stack of Lisp function calls. It then enters a recursive edit, showing the backtrace buffer in Debugger mode. The Debugger mode `c', `d', `j', and `r' commands exit the recursive edit; then `debug' switches back to the previous buffer and returns to whatever called `debug'. This is the only way the function `debug' can return to its caller. The use of the DEBUGGER-ARGS is that `debug' displays the rest of its arguments at the top of the `*Backtrace*' buffer, so that the user can see them. Except as described below, this is the _only_ way these arguments are used. However, certain values for first argument to `debug' have a special significance. (Normally, these values are used only by the internals of Emacs, and not by programmers calling `debug'.) Here is a table of these special values: `lambda' A first argument of `lambda' means `debug' was called because of entry to a function when `debug-on-next-call' was non-`nil'. The debugger displays `Debugger entered--entering a function:' as a line of text at the top of the buffer. `debug' `debug' as first argument means `debug' was called because of entry to a function that was set to debug on entry. The debugger displays the string `Debugger entered--entering a function:', just as in the `lambda' case. It also marks the stack frame for that function so that it will invoke the debugger when exited. `t' When the first argument is `t', this indicates a call to `debug' due to evaluation of a function call form when `debug-on-next-call' is non-`nil'. The debugger displays `Debugger entered--beginning evaluation of function call form:' as the top line in the buffer. `exit' When the first argument is `exit', it indicates the exit of a stack frame previously marked to invoke the debugger on exit. The second argument given to `debug' in this case is the value being returned from the frame. The debugger displays `Debugger entered--returning value:' in the top line of the buffer, followed by the value being returned. `error' When the first argument is `error', the debugger indicates that it is being entered because an error or `quit' was signaled and not handled, by displaying `Debugger entered--Lisp error:' followed by the error signaled and any arguments to `signal'. For example, (let ((debug-on-error t)) (/ 1 0)) ------ Buffer: *Backtrace* ------ Debugger entered--Lisp error: (arith-error) /(1 0) ... ------ Buffer: *Backtrace* ------ If an error was signaled, presumably the variable `debug-on-error' is non-`nil'. If `quit' was signaled, then presumably the variable `debug-on-quit' is non-`nil'. `nil' Use `nil' as the first of the DEBUGGER-ARGS when you want to enter the debugger explicitly. The rest of the DEBUGGER-ARGS are printed on the top line of the buffer. You can use this feature to display messages--for example, to remind yourself of the conditions under which `debug' is called.  File: elisp, Node: Internals of Debugger, Prev: Invoking the Debugger, Up: Debugger 18.1.8 Internals of the Debugger -------------------------------- This section describes functions and variables used internally by the debugger. -- Variable: debugger The value of this variable is the function to call to invoke the debugger. Its value must be a function of any number of arguments, or, more typically, the name of a function. This function should invoke some kind of debugger. The default value of the variable is `debug'. The first argument that Lisp hands to the function indicates why it was called. The convention for arguments is detailed in the description of `debug' (*note Invoking the Debugger::). -- Command: backtrace This function prints a trace of Lisp function calls currently active. This is the function used by `debug' to fill up the `*Backtrace*' buffer. It is written in C, since it must have access to the stack to determine which function calls are active. The return value is always `nil'. In the following example, a Lisp expression calls `backtrace' explicitly. This prints the backtrace to the stream `standard-output', which, in this case, is the buffer `backtrace-output'. Each line of the backtrace represents one function call. The line shows the values of the function's arguments if they are all known; if they are still being computed, the line says so. The arguments of special forms are elided. (with-output-to-temp-buffer "backtrace-output" (let ((var 1)) (save-excursion (setq var (eval '(progn (1+ var) (list 'testing (backtrace)))))))) => (testing nil) ----------- Buffer: backtrace-output ------------ backtrace() (list ...computing arguments...) (progn ...) eval((progn (1+ var) (list (quote testing) (backtrace)))) (setq ...) (save-excursion ...) (let ...) (with-output-to-temp-buffer ...) eval((with-output-to-temp-buffer ...)) eval-last-sexp-1(nil) eval-last-sexp(nil) call-interactively(eval-last-sexp) ----------- Buffer: backtrace-output ------------ -- Variable: debug-on-next-call If this variable is non-`nil', it says to call the debugger before the next `eval', `apply' or `funcall'. Entering the debugger sets `debug-on-next-call' to `nil'. The `d' command in the debugger works by setting this variable. -- Function: backtrace-debug level flag This function sets the debug-on-exit flag of the stack frame LEVEL levels down the stack, giving it the value FLAG. If FLAG is non-`nil', this will cause the debugger to be entered when that frame later exits. Even a nonlocal exit through that frame will enter the debugger. This function is used only by the debugger. -- Variable: command-debug-status This variable records the debugging status of the current interactive command. Each time a command is called interactively, this variable is bound to `nil'. The debugger can set this variable to leave information for future debugger invocations during the same command invocation. The advantage of using this variable rather than an ordinary global variable is that the data will never carry over to a subsequent command invocation. -- Function: backtrace-frame frame-number The function `backtrace-frame' is intended for use in Lisp debuggers. It returns information about what computation is happening in the stack frame FRAME-NUMBER levels down. If that frame has not evaluated the arguments yet, or is a special form, the value is `(nil FUNCTION ARG-FORMS...)'. If that frame has evaluated its arguments and called its function already, the return value is `(t FUNCTION ARG-VALUES...)'. In the return value, FUNCTION is whatever was supplied as the CAR of the evaluated list, or a `lambda' expression in the case of a macro call. If the function has a `&rest' argument, that is represented as the tail of the list ARG-VALUES. If FRAME-NUMBER is out of range, `backtrace-frame' returns `nil'.  File: elisp, Node: Edebug, Next: Syntax Errors, Prev: Debugger, Up: Debugging 18.2 Edebug =========== Edebug is a source-level debugger for Emacs Lisp programs, with which you can: * Step through evaluation, stopping before and after each expression. * Set conditional or unconditional breakpoints. * Stop when a specified condition is true (the global break event). * Trace slow or fast, stopping briefly at each stop point, or at each breakpoint. * Display expression results and evaluate expressions as if outside of Edebug. * Automatically re-evaluate a list of expressions and display their results each time Edebug updates the display. * Output trace information on function calls and returns. * Stop when an error occurs. * Display a backtrace, omitting Edebug's own frames. * Specify argument evaluation for macros and defining forms. * Obtain rudimentary coverage testing and frequency counts. The first three sections below should tell you enough about Edebug to start using it. * Menu: * Using Edebug:: Introduction to use of Edebug. * Instrumenting:: You must instrument your code in order to debug it with Edebug. * Modes: Edebug Execution Modes. Execution modes, stopping more or less often. * Jumping:: Commands to jump to a specified place. * Misc: Edebug Misc. Miscellaneous commands. * Breaks:: Setting breakpoints to make the program stop. * Trapping Errors:: Trapping errors with Edebug. * Views: Edebug Views. Views inside and outside of Edebug. * Eval: Edebug Eval. Evaluating expressions within Edebug. * Eval List:: Expressions whose values are displayed each time you enter Edebug. * Printing in Edebug:: Customization of printing. * Trace Buffer:: How to produce trace output in a buffer. * Coverage Testing:: How to test evaluation coverage. * The Outside Context:: Data that Edebug saves and restores. * Edebug and Macros:: Specifying how to handle macro calls. * Options: Edebug Options. Option variables for customizing Edebug.  File: elisp, Node: Using Edebug, Next: Instrumenting, Up: Edebug 18.2.1 Using Edebug ------------------- To debug a Lisp program with Edebug, you must first "instrument" the Lisp code that you want to debug. A simple way to do this is to first move point into the definition of a function or macro and then do `C-u C-M-x' (`eval-defun' with a prefix argument). See *note Instrumenting::, for alternative ways to instrument code. Once a function is instrumented, any call to the function activates Edebug. Depending on which Edebug execution mode you have selected, activating Edebug may stop execution and let you step through the function, or it may update the display and continue execution while checking for debugging commands. The default execution mode is step, which stops execution. *Note Edebug Execution Modes::. Within Edebug, you normally view an Emacs buffer showing the source of the Lisp code you are debugging. This is referred to as the "source code buffer", and it is temporarily read-only. An arrow in the left fringe indicates the line where the function is executing. Point initially shows where within the line the function is executing, but this ceases to be true if you move point yourself. If you instrument the definition of `fac' (shown below) and then execute `(fac 3)', here is what you would normally see. Point is at the open-parenthesis before `if'. (defun fac (n) =>-!-(if (< 0 n) (* n (fac (1- n))) 1)) The places within a function where Edebug can stop execution are called "stop points". These occur both before and after each subexpression that is a list, and also after each variable reference. Here we use periods to show the stop points in the function `fac': (defun fac (n) .(if .(< 0 n.). .(* n. .(fac .(1- n.).).). 1).) The special commands of Edebug are available in the source code buffer in addition to the commands of Emacs Lisp mode. For example, you can type the Edebug command to execute until the next stop point. If you type once after entry to `fac', here is the display you will see: (defun fac (n) =>(if -!-(< 0 n) (* n (fac (1- n))) 1)) When Edebug stops execution after an expression, it displays the expression's value in the echo area. Other frequently used commands are `b' to set a breakpoint at a stop point, `g' to execute until a breakpoint is reached, and `q' to exit Edebug and return to the top-level command loop. Type `?' to display a list of all Edebug commands.  File: elisp, Node: Instrumenting, Next: Edebug Execution Modes, Prev: Using Edebug, Up: Edebug 18.2.2 Instrumenting for Edebug ------------------------------- In order to use Edebug to debug Lisp code, you must first "instrument" the code. Instrumenting code inserts additional code into it, to invoke Edebug at the proper places. When you invoke command `C-M-x' (`eval-defun') with a prefix argument on a function definition, it instruments the definition before evaluating it. (This does not modify the source code itself.) If the variable `edebug-all-defs' is non-`nil', that inverts the meaning of the prefix argument: in this case, `C-M-x' instruments the definition _unless_ it has a prefix argument. The default value of `edebug-all-defs' is `nil'. The command `M-x edebug-all-defs' toggles the value of the variable `edebug-all-defs'. If `edebug-all-defs' is non-`nil', then the commands `eval-region', `eval-current-buffer', and `eval-buffer' also instrument any definitions they evaluate. Similarly, `edebug-all-forms' controls whether `eval-region' should instrument _any_ form, even non-defining forms. This doesn't apply to loading or evaluations in the minibuffer. The command `M-x edebug-all-forms' toggles this option. Another command, `M-x edebug-eval-top-level-form', is available to instrument any top-level form regardless of the values of `edebug-all-defs' and `edebug-all-forms'. While Edebug is active, the command `I' (`edebug-instrument-callee') instruments the definition of the function or macro called by the list form after point, if it is not already instrumented. This is possible only if Edebug knows where to find the source for that function; for this reason, after loading Edebug, `eval-region' records the position of every definition it evaluates, even if not instrumenting it. See also the `i' command (*note Jumping::), which steps into the call after instrumenting the function. Edebug knows how to instrument all the standard special forms, `interactive' forms with an expression argument, anonymous lambda expressions, and other defining forms. However, Edebug cannot determine on its own what a user-defined macro will do with the arguments of a macro call, so you must provide that information using Edebug specifications; for details, *note Edebug and Macros::. When Edebug is about to instrument code for the first time in a session, it runs the hook `edebug-setup-hook', then sets it to `nil'. You can use this to load Edebug specifications associated with a package you are using, but only when you use Edebug. To remove instrumentation from a definition, simply re-evaluate its definition in a way that does not instrument. There are two ways of evaluating forms that never instrument them: from a file with `load', and from the minibuffer with `eval-expression' (`M-:'). If Edebug detects a syntax error while instrumenting, it leaves point at the erroneous code and signals an `invalid-read-syntax' error. *Note Edebug Eval::, for other evaluation functions available inside of Edebug.  File: elisp, Node: Edebug Execution Modes, Next: Jumping, Prev: Instrumenting, Up: Edebug 18.2.3 Edebug Execution Modes ----------------------------- Edebug supports several execution modes for running the program you are debugging. We call these alternatives "Edebug execution modes"; do not confuse them with major or minor modes. The current Edebug execution mode determines how far Edebug continues execution before stopping--whether it stops at each stop point, or continues to the next breakpoint, for example--and how much Edebug displays the progress of the evaluation before it stops. Normally, you specify the Edebug execution mode by typing a command to continue the program in a certain mode. Here is a table of these commands; all except for `S' resume execution of the program, at least for a certain distance. `S' Stop: don't execute any more of the program, but wait for more Edebug commands (`edebug-stop'). `' Step: stop at the next stop point encountered (`edebug-step-mode'). `n' Next: stop at the next stop point encountered after an expression (`edebug-next-mode'). Also see `edebug-forward-sexp' in *note Jumping::. `t' Trace: pause (normally one second) at each Edebug stop point (`edebug-trace-mode'). `T' Rapid trace: update the display at each stop point, but don't actually pause (`edebug-Trace-fast-mode'). `g' Go: run until the next breakpoint (`edebug-go-mode'). *Note Breakpoints::. `c' Continue: pause one second at each breakpoint, and then continue (`edebug-continue-mode'). `C' Rapid continue: move point to each breakpoint, but don't pause (`edebug-Continue-fast-mode'). `G' Go non-stop: ignore breakpoints (`edebug-Go-nonstop-mode'). You can still stop the program by typing `S', or any editing command. In general, the execution modes earlier in the above list run the program more slowly or stop sooner than the modes later in the list. While executing or tracing, you can interrupt the execution by typing any Edebug command. Edebug stops the program at the next stop point and then executes the command you typed. For example, typing `t' during execution switches to trace mode at the next stop point. You can use `S' to stop execution without doing anything else. If your function happens to read input, a character you type intending to interrupt execution may be read by the function instead. You can avoid such unintended results by paying attention to when your program wants input. Keyboard macros containing the commands in this section do not completely work: exiting from Edebug, to resume the program, loses track of the keyboard macro. This is not easy to fix. Also, defining or executing a keyboard macro outside of Edebug does not affect commands inside Edebug. This is usually an advantage. See also the `edebug-continue-kbd-macro' option in *note Edebug Options::. When you enter a new Edebug level, the initial execution mode comes from the value of the variable `edebug-initial-mode' (*note Edebug Options::). By default, this specifies step mode. Note that you may reenter the same Edebug level several times if, for example, an instrumented function is called several times from one command. -- User Option: edebug-sit-for-seconds This option specifies how many seconds to wait between execution steps in trace mode or continue mode. The default is 1 second.  File: elisp, Node: Jumping, Next: Edebug Misc, Prev: Edebug Execution Modes, Up: Edebug 18.2.4 Jumping -------------- The commands described in this section execute until they reach a specified location. All except `i' make a temporary breakpoint to establish the place to stop, then switch to go mode. Any other breakpoint reached before the intended stop point will also stop execution. *Note Breakpoints::, for the details on breakpoints. These commands may fail to work as expected in case of nonlocal exit, as that can bypass the temporary breakpoint where you expected the program to stop. `h' Proceed to the stop point near where point is (`edebug-goto-here'). `f' Run the program for one expression (`edebug-forward-sexp'). `o' Run the program until the end of the containing sexp (`edebug-step-out'). `i' Step into the function or macro called by the form after point. The `h' command proceeds to the stop point at or after the current location of point, using a temporary breakpoint. The `f' command runs the program forward over one expression. More precisely, it sets a temporary breakpoint at the position that `forward-sexp' would reach, then executes in go mode so that the program will stop at breakpoints. With a prefix argument N, the temporary breakpoint is placed N sexps beyond point. If the containing list ends before N more elements, then the place to stop is after the containing expression. You must check that the position `forward-sexp' finds is a place that the program will really get to. In `cond', for example, this may not be true. For flexibility, the `f' command does `forward-sexp' starting at point, rather than at the stop point. If you want to execute one expression _from the current stop point_, first type `w' (`edebug-where') to move point there, and then type `f'. The `o' command continues "out of" an expression. It places a temporary breakpoint at the end of the sexp containing point. If the containing sexp is a function definition itself, `o' continues until just before the last sexp in the definition. If that is where you are now, it returns from the function and then stops. In other words, this command does not exit the currently executing function unless you are positioned after the last sexp. The `i' command steps into the function or macro called by the list form after point, and stops at its first stop point. Note that the form need not be the one about to be evaluated. But if the form is a function call about to be evaluated, remember to use this command before any of the arguments are evaluated, since otherwise it will be too late. The `i' command instruments the function or macro it's supposed to step into, if it isn't instrumented already. This is convenient, but keep in mind that the function or macro remains instrumented unless you explicitly arrange to deinstrument it.  File: elisp, Node: Edebug Misc, Next: Breaks, Prev: Jumping, Up: Edebug 18.2.5 Miscellaneous Edebug Commands ------------------------------------ Some miscellaneous Edebug commands are described here. `?' Display the help message for Edebug (`edebug-help'). `C-]' Abort one level back to the previous command level (`abort-recursive-edit'). `q' Return to the top level editor command loop (`top-level'). This exits all recursive editing levels, including all levels of Edebug activity. However, instrumented code protected with `unwind-protect' or `condition-case' forms may resume debugging. `Q' Like `q', but don't stop even for protected code (`edebug-top-level-nonstop'). `r' Redisplay the most recently known expression result in the echo area (`edebug-previous-result'). `d' Display a backtrace, excluding Edebug's own functions for clarity (`edebug-backtrace'). You cannot use debugger commands in the backtrace buffer in Edebug as you would in the standard debugger. The backtrace buffer is killed automatically when you continue execution. You can invoke commands from Edebug that activate Edebug again recursively. Whenever Edebug is active, you can quit to the top level with `q' or abort one recursive edit level with `C-]'. You can display a backtrace of all the pending evaluations with `d'.  File: elisp, Node: Breaks, Next: Trapping Errors, Prev: Edebug Misc, Up: Edebug 18.2.6 Breaks ------------- Edebug's step mode stops execution when the next stop point is reached. There are three other ways to stop Edebug execution once it has started: breakpoints, the global break condition, and source breakpoints. * Menu: * Breakpoints:: Breakpoints at stop points. * Global Break Condition:: Breaking on an event. * Source Breakpoints:: Embedding breakpoints in source code.  File: elisp, Node: Breakpoints, Next: Global Break Condition, Up: Breaks 18.2.6.1 Edebug Breakpoints ........................... While using Edebug, you can specify "breakpoints" in the program you are testing: these are places where execution should stop. You can set a breakpoint at any stop point, as defined in *note Using Edebug::. For setting and unsetting breakpoints, the stop point that is affected is the first one at or after point in the source code buffer. Here are the Edebug commands for breakpoints: `b' Set a breakpoint at the stop point at or after point (`edebug-set-breakpoint'). If you use a prefix argument, the breakpoint is temporary--it turns off the first time it stops the program. `u' Unset the breakpoint (if any) at the stop point at or after point (`edebug-unset-breakpoint'). `x CONDITION ' Set a conditional breakpoint which stops the program only if evaluating CONDITION produces a non-`nil' value (`edebug-set-conditional-breakpoint'). With a prefix argument, the breakpoint is temporary. `B' Move point to the next breakpoint in the current definition (`edebug-next-breakpoint'). While in Edebug, you can set a breakpoint with `b' and unset one with `u'. First move point to the Edebug stop point of your choice, then type `b' or `u' to set or unset a breakpoint there. Unsetting a breakpoint where none has been set has no effect. Re-evaluating or reinstrumenting a definition removes all of its previous breakpoints. A "conditional breakpoint" tests a condition each time the program gets there. Any errors that occur as a result of evaluating the condition are ignored, as if the result were `nil'. To set a conditional breakpoint, use `x', and specify the condition expression in the minibuffer. Setting a conditional breakpoint at a stop point that has a previously established conditional breakpoint puts the previous condition expression in the minibuffer so you can edit it. You can make a conditional or unconditional breakpoint "temporary" by using a prefix argument with the command to set the breakpoint. When a temporary breakpoint stops the program, it is automatically unset. Edebug always stops or pauses at a breakpoint, except when the Edebug mode is Go-nonstop. In that mode, it ignores breakpoints entirely. To find out where your breakpoints are, use the `B' command, which moves point to the next breakpoint following point, within the same function, or to the first breakpoint if there are no following breakpoints. This command does not continue execution--it just moves point in the buffer.  File: elisp, Node: Global Break Condition, Next: Source Breakpoints, Prev: Breakpoints, Up: Breaks 18.2.6.2 Global Break Condition ............................... A "global break condition" stops execution when a specified condition is satisfied, no matter where that may occur. Edebug evaluates the global break condition at every stop point; if it evaluates to a non-`nil' value, then execution stops or pauses depending on the execution mode, as if a breakpoint had been hit. If evaluating the condition gets an error, execution does not stop. The condition expression is stored in `edebug-global-break-condition'. You can specify a new expression using the `X' command from the source code buffer while Edebug is active, or using `C-x X X' from any buffer at any time, as long as Edebug is loaded (`edebug-set-global-break-condition'). The global break condition is the simplest way to find where in your code some event occurs, but it makes code run much more slowly. So you should reset the condition to `nil' when not using it.  File: elisp, Node: Source Breakpoints, Prev: Global Break Condition, Up: Breaks 18.2.6.3 Source Breakpoints ........................... All breakpoints in a definition are forgotten each time you reinstrument it. If you wish to make a breakpoint that won't be forgotten, you can write a "source breakpoint", which is simply a call to the function `edebug' in your source code. You can, of course, make such a call conditional. For example, in the `fac' function, you can insert the first line as shown below, to stop when the argument reaches zero: (defun fac (n) (if (= n 0) (edebug)) (if (< 0 n) (* n (fac (1- n))) 1)) When the `fac' definition is instrumented and the function is called, the call to `edebug' acts as a breakpoint. Depending on the execution mode, Edebug stops or pauses there. If no instrumented code is being executed when `edebug' is called, that function calls `debug'.  File: elisp, Node: Trapping Errors, Next: Edebug Views, Prev: Breaks, Up: Edebug 18.2.7 Trapping Errors ---------------------- Emacs normally displays an error message when an error is signaled and not handled with `condition-case'. While Edebug is active and executing instrumented code, it normally responds to all unhandled errors. You can customize this with the options `edebug-on-error' and `edebug-on-quit'; see *note Edebug Options::. When Edebug responds to an error, it shows the last stop point encountered before the error. This may be the location of a call to a function which was not instrumented, and within which the error actually occurred. For an unbound variable error, the last known stop point might be quite distant from the offending variable reference. In that case, you might want to display a full backtrace (*note Edebug Misc::). If you change `debug-on-error' or `debug-on-quit' while Edebug is active, these changes will be forgotten when Edebug becomes inactive. Furthermore, during Edebug's recursive edit, these variables are bound to the values they had outside of Edebug.  File: elisp, Node: Edebug Views, Next: Edebug Eval, Prev: Trapping Errors, Up: Edebug 18.2.8 Edebug Views ------------------- These Edebug commands let you view aspects of the buffer and window status as they were before entry to Edebug. The outside window configuration is the collection of windows and contents that were in effect outside of Edebug. `v' Switch to viewing the outside window configuration (`edebug-view-outside'). Type `C-x X w' to return to Edebug. `p' Temporarily display the outside current buffer with point at its outside position (`edebug-bounce-point'), pausing for one second before returning to Edebug. With a prefix argument N, pause for N seconds instead. `w' Move point back to the current stop point in the source code buffer (`edebug-where'). If you use this command in a different window displaying the same buffer, that window will be used instead to display the current definition in the future. `W' Toggle whether Edebug saves and restores the outside window configuration (`edebug-toggle-save-windows'). With a prefix argument, `W' only toggles saving and restoring of the selected window. To specify a window that is not displaying the source code buffer, you must use `C-x X W' from the global keymap. You can view the outside window configuration with `v' or just bounce to the point in the current buffer with `p', even if it is not normally displayed. After moving point, you may wish to jump back to the stop point. You can do that with `w' from a source code buffer. You can jump back to the stop point in the source code buffer from any buffer using `C-x X w'. Each time you use `W' to turn saving _off_, Edebug forgets the saved outside window configuration--so that even if you turn saving back _on_, the current window configuration remains unchanged when you next exit Edebug (by continuing the program). However, the automatic redisplay of `*edebug*' and `*edebug-trace*' may conflict with the buffers you wish to see unless you have enough windows open.  File: elisp, Node: Edebug Eval, Next: Eval List, Prev: Edebug Views, Up: Edebug 18.2.9 Evaluation ----------------- While within Edebug, you can evaluate expressions "as if" Edebug were not running. Edebug tries to be invisible to the expression's evaluation and printing. Evaluation of expressions that cause side effects will work as expected, except for changes to data that Edebug explicitly saves and restores. *Note The Outside Context::, for details on this process. `e EXP ' Evaluate expression EXP in the context outside of Edebug (`edebug-eval-expression'). That is, Edebug tries to minimize its interference with the evaluation. `M-: EXP ' Evaluate expression EXP in the context of Edebug itself (`eval-expression'). `C-x C-e' Evaluate the expression before point, in the context outside of Edebug (`edebug-eval-last-sexp'). Edebug supports evaluation of expressions containing references to lexically bound symbols created by the following constructs in `cl.el': `lexical-let', `macrolet', and `symbol-macrolet'.  File: elisp, Node: Eval List, Next: Printing in Edebug, Prev: Edebug Eval, Up: Edebug 18.2.10 Evaluation List Buffer ------------------------------ You can use the "evaluation list buffer", called `*edebug*', to evaluate expressions interactively. You can also set up the "evaluation list" of expressions to be evaluated automatically each time Edebug updates the display. `E' Switch to the evaluation list buffer `*edebug*' (`edebug-visit-eval-list'). In the `*edebug*' buffer you can use the commands of Lisp Interaction mode (*note Lisp Interaction: (emacs)Lisp Interaction.) as well as these special commands: `C-j' Evaluate the expression before point, in the outside context, and insert the value in the buffer (`edebug-eval-print-last-sexp'). `C-x C-e' Evaluate the expression before point, in the context outside of Edebug (`edebug-eval-last-sexp'). `C-c C-u' Build a new evaluation list from the contents of the buffer (`edebug-update-eval-list'). `C-c C-d' Delete the evaluation list group that point is in (`edebug-delete-eval-item'). `C-c C-w' Switch back to the source code buffer at the current stop point (`edebug-where'). You can evaluate expressions in the evaluation list window with `C-j' or `C-x C-e', just as you would in `*scratch*'; but they are evaluated in the context outside of Edebug. The expressions you enter interactively (and their results) are lost when you continue execution; but you can set up an "evaluation list" consisting of expressions to be evaluated each time execution stops. To do this, write one or more "evaluation list groups" in the evaluation list buffer. An evaluation list group consists of one or more Lisp expressions. Groups are separated by comment lines. The command `C-c C-u' (`edebug-update-eval-list') rebuilds the evaluation list, scanning the buffer and using the first expression of each group. (The idea is that the second expression of the group is the value previously computed and displayed.) Each entry to Edebug redisplays the evaluation list by inserting each expression in the buffer, followed by its current value. It also inserts comment lines so that each expression becomes its own group. Thus, if you type `C-c C-u' again without changing the buffer text, the evaluation list is effectively unchanged. If an error occurs during an evaluation from the evaluation list, the error message is displayed in a string as if it were the result. Therefore, expressions using variables that are not currently valid do not interrupt your debugging. Here is an example of what the evaluation list window looks like after several expressions have been added to it: (current-buffer) # ;--------------------------------------------------------------- (selected-window) # ;--------------------------------------------------------------- (point) 196 ;--------------------------------------------------------------- bad-var "Symbol's value as variable is void: bad-var" ;--------------------------------------------------------------- (recursion-depth) 0 ;--------------------------------------------------------------- this-command eval-last-sexp ;--------------------------------------------------------------- To delete a group, move point into it and type `C-c C-d', or simply delete the text for the group and update the evaluation list with `C-c C-u'. To add a new expression to the evaluation list, insert the expression at a suitable place, insert a new comment line, then type `C-c C-u'. You need not insert dashes in the comment line--its contents don't matter. After selecting `*edebug*', you can return to the source code buffer with `C-c C-w'. The `*edebug*' buffer is killed when you continue execution, and recreated next time it is needed.  File: elisp, Node: Printing in Edebug, Next: Trace Buffer, Prev: Eval List, Up: Edebug 18.2.11 Printing in Edebug -------------------------- If an expression in your program produces a value containing circular list structure, you may get an error when Edebug attempts to print it. One way to cope with circular structure is to set `print-length' or `print-level' to truncate the printing. Edebug does this for you; it binds `print-length' and `print-level' to the values of the variables `edebug-print-length' and `edebug-print-level' (so long as they have non-`nil' values). *Note Output Variables::. -- User Option: edebug-print-length If non-`nil', Edebug binds `print-length' to this value while printing results. The default value is `50'. -- User Option: edebug-print-level If non-`nil', Edebug binds `print-level' to this value while printing results. The default value is `50'. You can also print circular structures and structures that share elements more informatively by binding `print-circle' to a non-`nil' value. Here is an example of code that creates a circular structure: (setq a '(x y)) (setcar a a) Custom printing prints this as `Result: #1=(#1# y)'. The `#1=' notation labels the structure that follows it with the label `1', and the `#1#' notation references the previously labeled structure. This notation is used for any shared elements of lists or vectors. -- User Option: edebug-print-circle If non-`nil', Edebug binds `print-circle' to this value while printing results. The default value is `t'. Other programs can also use custom printing; see `cust-print.el' for details.  File: elisp, Node: Trace Buffer, Next: Coverage Testing, Prev: Printing in Edebug, Up: Edebug 18.2.12 Trace Buffer -------------------- Edebug can record an execution trace, storing it in a buffer named `*edebug-trace*'. This is a log of function calls and returns, showing the function names and their arguments and values. To enable trace recording, set `edebug-trace' to a non-`nil' value. Making a trace buffer is not the same thing as using trace execution mode (*note Edebug Execution Modes::). When trace recording is enabled, each function entry and exit adds lines to the trace buffer. A function entry record consists of `::::{', followed by the function name and argument values. A function exit record consists of `::::}', followed by the function name and result of the function. The number of `:'s in an entry shows its recursion depth. You can use the braces in the trace buffer to find the matching beginning or end of function calls. You can customize trace recording for function entry and exit by redefining the functions `edebug-print-trace-before' and `edebug-print-trace-after'. -- Macro: edebug-tracing string body... This macro requests additional trace information around the execution of the BODY forms. The argument STRING specifies text to put in the trace buffer, after the `{' or `}'. All the arguments are evaluated, and `edebug-tracing' returns the value of the last form in BODY. -- Function: edebug-trace format-string &rest format-args This function inserts text in the trace buffer. It computes the text with `(apply 'format FORMAT-STRING FORMAT-ARGS)'. It also appends a newline to separate entries. `edebug-tracing' and `edebug-trace' insert lines in the trace buffer whenever they are called, even if Edebug is not active. Adding text to the trace buffer also scrolls its window to show the last lines inserted.  File: elisp, Node: Coverage Testing, Next: The Outside Context, Prev: Trace Buffer, Up: Edebug 18.2.13 Coverage Testing ------------------------ Edebug provides rudimentary coverage testing and display of execution frequency. Coverage testing works by comparing the result of each expression with the previous result; each form in the program is considered "covered" if it has returned two different values since you began testing coverage in the current Emacs session. Thus, to do coverage testing on your program, execute it under various conditions and note whether it behaves correctly; Edebug will tell you when you have tried enough different conditions that each form has returned two different values. Coverage testing makes execution slower, so it is only done if `edebug-test-coverage' is non-`nil'. Frequency counting is performed for all executions of an instrumented function, even if the execution mode is Go-nonstop, and regardless of whether coverage testing is enabled. Use `C-x X =' (`edebug-display-freq-count') to display both the coverage information and the frequency counts for a definition. Just `=' (`edebug-temp-display-freq-count') displays the same information temporarily, only until you type another key. -- Command: edebug-display-freq-count This command displays the frequency count data for each line of the current definition. It inserts frequency counts as comment lines after each line of code. You can undo all insertions with one `undo' command. The counts appear under the `(' before an expression or the `)' after an expression, or on the last character of a variable. To simplify the display, a count is not shown if it is equal to the count of an earlier expression on the same line. The character `=' following the count for an expression says that the expression has returned the same value each time it was evaluated. In other words, it is not yet "covered" for coverage testing purposes. To clear the frequency count and coverage data for a definition, simply reinstrument it with `eval-defun'. For example, after evaluating `(fac 5)' with a source breakpoint, and setting `edebug-test-coverage' to `t', when the breakpoint is reached, the frequency data looks like this: (defun fac (n) (if (= n 0) (edebug)) ;#6 1 = =5 (if (< 0 n) ;#5 = (* n (fac (1- n))) ;# 5 0 1)) ;# 0 The comment lines show that `fac' was called 6 times. The first `if' statement returned 5 times with the same result each time; the same is true of the condition on the second `if'. The recursive call of `fac' did not return at all.  File: elisp, Node: The Outside Context, Next: Edebug and Macros, Prev: Coverage Testing, Up: Edebug 18.2.14 The Outside Context --------------------------- Edebug tries to be transparent to the program you are debugging, but it does not succeed completely. Edebug also tries to be transparent when you evaluate expressions with `e' or with the evaluation list buffer, by temporarily restoring the outside context. This section explains precisely what context Edebug restores, and how Edebug fails to be completely transparent. * Menu: * Checking Whether to Stop:: When Edebug decides what to do. * Edebug Display Update:: When Edebug updates the display. * Edebug Recursive Edit:: When Edebug stops execution.  File: elisp, Node: Checking Whether to Stop, Next: Edebug Display Update, Up: The Outside Context 18.2.14.1 Checking Whether to Stop .................................. Whenever Edebug is entered, it needs to save and restore certain data before even deciding whether to make trace information or stop the program. * `max-lisp-eval-depth' and `max-specpdl-size' are both increased to reduce Edebug's impact on the stack. You could, however, still run out of stack space when using Edebug. * The state of keyboard macro execution is saved and restored. While Edebug is active, `executing-kbd-macro' is bound to `nil' unless `edebug-continue-kbd-macro' is non-`nil'.  File: elisp, Node: Edebug Display Update, Next: Edebug Recursive Edit, Prev: Checking Whether to Stop, Up: The Outside Context 18.2.14.2 Edebug Display Update ............................... When Edebug needs to display something (e.g., in trace mode), it saves the current window configuration from "outside" Edebug (*note Window Configurations::). When you exit Edebug (by continuing the program), it restores the previous window configuration. Emacs redisplays only when it pauses. Usually, when you continue execution, the program re-enters Edebug at a breakpoint or after stepping, without pausing or reading input in between. In such cases, Emacs never gets a chance to redisplay the "outside" configuration. Consequently, what you see is the same window configuration as the last time Edebug was active, with no interruption. Entry to Edebug for displaying something also saves and restores the following data (though some of them are deliberately not restored if an error or quit signal occurs). * Which buffer is current, and the positions of point and the mark in the current buffer, are saved and restored. * The outside window configuration is saved and restored if `edebug-save-windows' is non-`nil' (*note Edebug Options::). The window configuration is not restored on error or quit, but the outside selected window _is_ reselected even on error or quit in case a `save-excursion' is active. If the value of `edebug-save-windows' is a list, only the listed windows are saved and restored. The window start and horizontal scrolling of the source code buffer are not restored, however, so that the display remains coherent within Edebug. * The value of point in each displayed buffer is saved and restored if `edebug-save-displayed-buffer-points' is non-`nil'. * The variables `overlay-arrow-position' and `overlay-arrow-string' are saved and restored, so you can safely invoke Edebug from the recursive edit elsewhere in the same buffer. * `cursor-in-echo-area' is locally bound to `nil' so that the cursor shows up in the window.  File: elisp, Node: Edebug Recursive Edit, Prev: Edebug Display Update, Up: The Outside Context 18.2.14.3 Edebug Recursive Edit ............................... When Edebug is entered and actually reads commands from the user, it saves (and later restores) these additional data: * The current match data. *Note Match Data::. * The variables `last-command', `this-command', `last-input-event', `last-command-event', `last-event-frame', `last-nonmenu-event', and `track-mouse'. Commands used within Edebug do not affect these variables outside of Edebug. Executing commands within Edebug can change the key sequence that would be returned by `this-command-keys', and there is no way to reset the key sequence from Lisp. Edebug cannot save and restore the value of `unread-command-events'. Entering Edebug while this variable has a nontrivial value can interfere with execution of the program you are debugging. * Complex commands executed while in Edebug are added to the variable `command-history'. In rare cases this can alter execution. * Within Edebug, the recursion depth appears one deeper than the recursion depth outside Edebug. This is not true of the automatically updated evaluation list window. * `standard-output' and `standard-input' are bound to `nil' by the `recursive-edit', but Edebug temporarily restores them during evaluations. * The state of keyboard macro definition is saved and restored. While Edebug is active, `defining-kbd-macro' is bound to `edebug-continue-kbd-macro'.  File: elisp, Node: Edebug and Macros, Next: Edebug Options, Prev: The Outside Context, Up: Edebug 18.2.15 Edebug and Macros ------------------------- To make Edebug properly instrument expressions that call macros, some extra care is needed. This subsection explains the details. * Menu: * Instrumenting Macro Calls:: The basic problem. * Specification List:: How to specify complex patterns of evaluation. * Backtracking:: What Edebug does when matching fails. * Specification Examples:: To help understand specifications.  File: elisp, Node: Instrumenting Macro Calls, Next: Specification List, Up: Edebug and Macros 18.2.15.1 Instrumenting Macro Calls ................................... When Edebug instruments an expression that calls a Lisp macro, it needs additional information about the macro to do the job properly. This is because there is no a-priori way to tell which subexpressions of the macro call are forms to be evaluated. (Evaluation may occur explicitly in the macro body, or when the resulting expansion is evaluated, or any time later.) Therefore, you must define an Edebug specification for each macro that Edebug will encounter, to explain the format of calls to that macro. To do this, add a `debug' declaration to the macro definition. Here is a simple example that shows the specification for the `for' example macro (*note Argument Evaluation::). (defmacro for (var from init to final do &rest body) "Execute a simple \"for\" loop. For example, (for i from 1 to 10 do (print i))." (declare (debug (symbolp "from" form "to" form "do" &rest form))) ...) The Edebug specification says which parts of a call to the macro are forms to be evaluated. For simple macros, the specification often looks very similar to the formal argument list of the macro definition, but specifications are much more general than macro arguments. *Note Defining Macros::, for more explanation of the `declare' form. You can also define an edebug specification for a macro separately from the macro definition with `def-edebug-spec'. Adding `debug' declarations is preferred, and more convenient, for macro definitions in Lisp, but `def-edebug-spec' makes it possible to define Edebug specifications for special forms implemented in C. -- Macro: def-edebug-spec macro specification Specify which expressions of a call to macro MACRO are forms to be evaluated. SPECIFICATION should be the edebug specification. Neither argument is evaluated. The MACRO argument can actually be any symbol, not just a macro name. Here is a table of the possibilities for SPECIFICATION and how each directs processing of arguments. `t' All arguments are instrumented for evaluation. `0' None of the arguments is instrumented. a symbol The symbol must have an Edebug specification, which is used instead. This indirection is repeated until another kind of specification is found. This allows you to inherit the specification from another macro. a list The elements of the list describe the types of the arguments of a calling form. The possible elements of a specification list are described in the following sections. If a macro has no Edebug specification, neither through a `debug' declaration nor through a `def-edebug-spec' call, the variable `edebug-eval-macro-args' comes into play. -- User Option: edebug-eval-macro-args This controls the way Edebug treats macro arguments with no explicit Edebug specification. If it is `nil' (the default), none of the arguments is instrumented for evaluation. Otherwise, all arguments are instrumented.  File: elisp, Node: Specification List, Next: Backtracking, Prev: Instrumenting Macro Calls, Up: Edebug and Macros 18.2.15.2 Specification List ............................ A "specification list" is required for an Edebug specification if some arguments of a macro call are evaluated while others are not. Some elements in a specification list match one or more arguments, but others modify the processing of all following elements. The latter, called "specification keywords", are symbols beginning with `&' (such as `&optional'). A specification list may contain sublists which match arguments that are themselves lists, or it may contain vectors used for grouping. Sublists and groups thus subdivide the specification list into a hierarchy of levels. Specification keywords apply only to the remainder of the sublist or group they are contained in. When a specification list involves alternatives or repetition, matching it against an actual macro call may require backtracking. For more details, *note Backtracking::. Edebug specifications provide the power of regular expression matching, plus some context-free grammar constructs: the matching of sublists with balanced parentheses, recursive processing of forms, and recursion via indirect specifications. Here's a table of the possible elements of a specification list, with their meanings (see *note Specification Examples::, for the referenced examples): `sexp' A single unevaluated Lisp object, which is not instrumented. `form' A single evaluated expression, which is instrumented. `place' A place to store a value, as in the Common Lisp `setf' construct. `body' Short for `&rest form'. See `&rest' below. `function-form' A function form: either a quoted function symbol, a quoted lambda expression, or a form (that should evaluate to a function symbol or lambda expression). This is useful when an argument that's a lambda expression might be quoted with `quote' rather than `function', since it instruments the body of the lambda expression either way. `lambda-expr' A lambda expression with no quoting. `&optional' All following elements in the specification list are optional; as soon as one does not match, Edebug stops matching at this level. To make just a few elements optional followed by non-optional elements, use `[&optional SPECS...]'. To specify that several elements must all match or none, use `&optional [SPECS...]'. See the `defun' example. `&rest' All following elements in the specification list are repeated zero or more times. In the last repetition, however, it is not a problem if the expression runs out before matching all of the elements of the specification list. To repeat only a few elements, use `[&rest SPECS...]'. To specify several elements that must all match on every repetition, use `&rest [SPECS...]'. `&or' Each of the following elements in the specification list is an alternative. One of the alternatives must match, or the `&or' specification fails. Each list element following `&or' is a single alternative. To group two or more list elements as a single alternative, enclose them in `[...]'. `¬' Each of the following elements is matched as alternatives as if by using `&or', but if any of them match, the specification fails. If none of them match, nothing is matched, but the `¬' specification succeeds. `&define' Indicates that the specification is for a defining form. The defining form itself is not instrumented (that is, Edebug does not stop before and after the defining form), but forms inside it typically will be instrumented. The `&define' keyword should be the first element in a list specification. `nil' This is successful when there are no more arguments to match at the current argument list level; otherwise it fails. See sublist specifications and the backquote example. `gate' No argument is matched but backtracking through the gate is disabled while matching the remainder of the specifications at this level. This is primarily used to generate more specific syntax error messages. See *note Backtracking::, for more details. Also see the `let' example. `OTHER-SYMBOL' Any other symbol in a specification list may be a predicate or an indirect specification. If the symbol has an Edebug specification, this "indirect specification" should be either a list specification that is used in place of the symbol, or a function that is called to process the arguments. The specification may be defined with `def-edebug-spec' just as for macros. See the `defun' example. Otherwise, the symbol should be a predicate. The predicate is called with the argument and the specification fails if the predicate returns `nil', and the argument is not instrumented. Some suitable predicates include `symbolp', `integerp', `stringp', `vectorp', and `atom'. `[ELEMENTS...]' A vector of elements groups the elements into a single "group specification". Its meaning has nothing to do with vectors. `"STRING"' The argument should be a symbol named STRING. This specification is equivalent to the quoted symbol, `'SYMBOL', where the name of SYMBOL is the STRING, but the string form is preferred. `(vector ELEMENTS...)' The argument should be a vector whose elements must match the ELEMENTS in the specification. See the backquote example. `(ELEMENTS...)' Any other list is a "sublist specification" and the argument must be a list whose elements match the specification ELEMENTS. A sublist specification may be a dotted list and the corresponding list argument may then be a dotted list. Alternatively, the last CDR of a dotted list specification may be another sublist specification (via a grouping or an indirect specification, e.g., `(spec . [(more specs...)])') whose elements match the non-dotted list arguments. This is useful in recursive specifications such as in the backquote example. Also see the description of a `nil' specification above for terminating such recursion. Note that a sublist specification written as `(specs . nil)' is equivalent to `(specs)', and `(specs . (sublist-elements...))' is equivalent to `(specs sublist-elements...)'. Here is a list of additional specifications that may appear only after `&define'. See the `defun' example. `name' The argument, a symbol, is the name of the defining form. A defining form is not required to have a name field; and it may have multiple name fields. `:name' This construct does not actually match an argument. The element following `:name' should be a symbol; it is used as an additional name component for the definition. You can use this to add a unique, static component to the name of the definition. It may be used more than once. `arg' The argument, a symbol, is the name of an argument of the defining form. However, lambda-list keywords (symbols starting with `&') are not allowed. `lambda-list' This matches a lambda list--the argument list of a lambda expression. `def-body' The argument is the body of code in a definition. This is like `body', described above, but a definition body must be instrumented with a different Edebug call that looks up information associated with the definition. Use `def-body' for the highest level list of forms within the definition. `def-form' The argument is a single, highest-level form in a definition. This is like `def-body', except it is used to match a single form rather than a list of forms. As a special case, `def-form' also means that tracing information is not output when the form is executed. See the `interactive' example.  File: elisp, Node: Backtracking, Next: Specification Examples, Prev: Specification List, Up: Edebug and Macros 18.2.15.3 Backtracking in Specifications ........................................ If a specification fails to match at some point, this does not necessarily mean a syntax error will be signaled; instead, "backtracking" will take place until all alternatives have been exhausted. Eventually every element of the argument list must be matched by some element in the specification, and every required element in the specification must match some argument. When a syntax error is detected, it might not be reported until much later, after higher-level alternatives have been exhausted, and with the point positioned further from the real error. But if backtracking is disabled when an error occurs, it can be reported immediately. Note that backtracking is also reenabled automatically in several situations; when a new alternative is established by `&optional', `&rest', or `&or', or at the start of processing a sublist, group, or indirect specification. The effect of enabling or disabling backtracking is limited to the remainder of the level currently being processed and lower levels. Backtracking is disabled while matching any of the form specifications (that is, `form', `body', `def-form', and `def-body'). These specifications will match any form so any error must be in the form itself rather than at a higher level. Backtracking is also disabled after successfully matching a quoted symbol or string specification, since this usually indicates a recognized construct. But if you have a set of alternative constructs that all begin with the same symbol, you can usually work around this constraint by factoring the symbol out of the alternatives, e.g., `["foo" &or [first case] [second case] ...]'. Most needs are satisfied by these two ways that backtracking is automatically disabled, but occasionally it is useful to explicitly disable backtracking by using the `gate' specification. This is useful when you know that no higher alternatives could apply. See the example of the `let' specification.  File: elisp, Node: Specification Examples, Prev: Backtracking, Up: Edebug and Macros 18.2.15.4 Specification Examples ................................ It may be easier to understand Edebug specifications by studying the examples provided here. A `let' special form has a sequence of bindings and a body. Each of the bindings is either a symbol or a sublist with a symbol and optional expression. In the specification below, notice the `gate' inside of the sublist to prevent backtracking once a sublist is found. (def-edebug-spec let ((&rest &or symbolp (gate symbolp &optional form)) body)) Edebug uses the following specifications for `defun' and the associated argument list and `interactive' specifications. It is necessary to handle interactive forms specially since an expression argument is actually evaluated outside of the function body. (The specification for `defmacro' is very similar to that for `defun', but allows for the `declare' statement.) (def-edebug-spec defun (&define name lambda-list [&optional stringp] ; Match the doc string, if present. [&optional ("interactive" interactive)] def-body)) (def-edebug-spec lambda-list (([&rest arg] [&optional ["&optional" arg &rest arg]] &optional ["&rest" arg] ))) (def-edebug-spec interactive (&optional &or stringp def-form)) ; Notice: `def-form' The specification for backquote below illustrates how to match dotted lists and use `nil' to terminate recursion. It also illustrates how components of a vector may be matched. (The actual specification defined by Edebug is a little different, and does not support dotted lists because doing so causes very deep recursion that could fail.) (def-edebug-spec \` (backquote-form)) ; Alias just for clarity. (def-edebug-spec backquote-form (&or ([&or "," ",@"] &or ("quote" backquote-form) form) (backquote-form . [&or nil backquote-form]) (vector &rest backquote-form) sexp))  File: elisp, Node: Edebug Options, Prev: Edebug and Macros, Up: Edebug 18.2.16 Edebug Options ---------------------- These options affect the behavior of Edebug: -- User Option: edebug-setup-hook Functions to call before Edebug is used. Each time it is set to a new value, Edebug will call those functions once and then `edebug-setup-hook' is reset to `nil'. You could use this to load up Edebug specifications associated with a package you are using but only when you also use Edebug. *Note Instrumenting::. -- User Option: edebug-all-defs If this is non-`nil', normal evaluation of defining forms such as `defun' and `defmacro' instruments them for Edebug. This applies to `eval-defun', `eval-region', `eval-buffer', and `eval-current-buffer'. Use the command `M-x edebug-all-defs' to toggle the value of this option. *Note Instrumenting::. -- User Option: edebug-all-forms If this is non-`nil', the commands `eval-defun', `eval-region', `eval-buffer', and `eval-current-buffer' instrument all forms, even those that don't define anything. This doesn't apply to loading or evaluations in the minibuffer. Use the command `M-x edebug-all-forms' to toggle the value of this option. *Note Instrumenting::. -- User Option: edebug-save-windows If this is non-`nil', Edebug saves and restores the window configuration. That takes some time, so if your program does not care what happens to the window configurations, it is better to set this variable to `nil'. If the value is a list, only the listed windows are saved and restored. You can use the `W' command in Edebug to change this variable interactively. *Note Edebug Display Update::. -- User Option: edebug-save-displayed-buffer-points If this is non-`nil', Edebug saves and restores point in all displayed buffers. Saving and restoring point in other buffers is necessary if you are debugging code that changes the point of a buffer that is displayed in a non-selected window. If Edebug or the user then selects the window, point in that buffer will move to the window's value of point. Saving and restoring point in all buffers is expensive, since it requires selecting each window twice, so enable this only if you need it. *Note Edebug Display Update::. -- User Option: edebug-initial-mode If this variable is non-`nil', it specifies the initial execution mode for Edebug when it is first activated. Possible values are `step', `next', `go', `Go-nonstop', `trace', `Trace-fast', `continue', and `Continue-fast'. The default value is `step'. *Note Edebug Execution Modes::. -- User Option: edebug-trace If this is non-`nil', trace each function entry and exit. Tracing output is displayed in a buffer named `*edebug-trace*', one function entry or exit per line, indented by the recursion level. Also see `edebug-tracing', in *note Trace Buffer::. -- User Option: edebug-test-coverage If non-`nil', Edebug tests coverage of all expressions debugged. *Note Coverage Testing::. -- User Option: edebug-continue-kbd-macro If non-`nil', continue defining or executing any keyboard macro that is executing outside of Edebug. Use this with caution since it is not debugged. *Note Edebug Execution Modes::. -- User Option: edebug-on-error Edebug binds `debug-on-error' to this value, if `debug-on-error' was previously `nil'. *Note Trapping Errors::. -- User Option: edebug-on-quit Edebug binds `debug-on-quit' to this value, if `debug-on-quit' was previously `nil'. *Note Trapping Errors::. If you change the values of `edebug-on-error' or `edebug-on-quit' while Edebug is active, their values won't be used until the _next_ time Edebug is invoked via a new command. -- User Option: edebug-global-break-condition If non-`nil', an expression to test for at every stop point. If the result is non-`nil', then break. Errors are ignored. *Note Global Break Condition::.  File: elisp, Node: Syntax Errors, Next: Test Coverage, Prev: Edebug, Up: Debugging 18.3 Debugging Invalid Lisp Syntax ================================== The Lisp reader reports invalid syntax, but cannot say where the real problem is. For example, the error "End of file during parsing" in evaluating an expression indicates an excess of open parentheses (or square brackets). The reader detects this imbalance at the end of the file, but it cannot figure out where the close parenthesis should have been. Likewise, "Invalid read syntax: ")"" indicates an excess close parenthesis or missing open parenthesis, but does not say where the missing parenthesis belongs. How, then, to find what to change? If the problem is not simply an imbalance of parentheses, a useful technique is to try `C-M-e' at the beginning of each defun, and see if it goes to the place where that defun appears to end. If it does not, there is a problem in that defun. However, unmatched parentheses are the most common syntax errors in Lisp, and we can give further advice for those cases. (In addition, just moving point through the code with Show Paren mode enabled might find the mismatch.) * Menu: * Excess Open:: How to find a spurious open paren or missing close. * Excess Close:: How to find a spurious close paren or missing open.  File: elisp, Node: Excess Open, Next: Excess Close, Up: Syntax Errors 18.3.1 Excess Open Parentheses ------------------------------ The first step is to find the defun that is unbalanced. If there is an excess open parenthesis, the way to do this is to go to the end of the file and type `C-u C-M-u'. This will move you to the beginning of the first defun that is unbalanced. The next step is to determine precisely what is wrong. There is no way to be sure of this except by studying the program, but often the existing indentation is a clue to where the parentheses should have been. The easiest way to use this clue is to reindent with `C-M-q' and see what moves. *But don't do this yet!* Keep reading, first. Before you do this, make sure the defun has enough close parentheses. Otherwise, `C-M-q' will get an error, or will reindent all the rest of the file until the end. So move to the end of the defun and insert a close parenthesis there. Don't use `C-M-e' to move there, since that too will fail to work until the defun is balanced. Now you can go to the beginning of the defun and type `C-M-q'. Usually all the lines from a certain point to the end of the function will shift to the right. There is probably a missing close parenthesis, or a superfluous open parenthesis, near that point. (However, don't assume this is true; study the code to make sure.) Once you have found the discrepancy, undo the `C-M-q' with `C-_', since the old indentation is probably appropriate to the intended parentheses. After you think you have fixed the problem, use `C-M-q' again. If the old indentation actually fit the intended nesting of parentheses, and you have put back those parentheses, `C-M-q' should not change anything.  File: elisp, Node: Excess Close, Prev: Excess Open, Up: Syntax Errors 18.3.2 Excess Close Parentheses ------------------------------- To deal with an excess close parenthesis, first go to the beginning of the file, then type `C-u -1 C-M-u' to find the end of the first unbalanced defun. Then find the actual matching close parenthesis by typing `C-M-f' at the beginning of that defun. This will leave you somewhere short of the place where the defun ought to end. It is possible that you will find a spurious close parenthesis in that vicinity. If you don't see a problem at that point, the next thing to do is to type `C-M-q' at the beginning of the defun. A range of lines will probably shift left; if so, the missing open parenthesis or spurious close parenthesis is probably near the first of those lines. (However, don't assume this is true; study the code to make sure.) Once you have found the discrepancy, undo the `C-M-q' with `C-_', since the old indentation is probably appropriate to the intended parentheses. After you think you have fixed the problem, use `C-M-q' again. If the old indentation actually fits the intended nesting of parentheses, and you have put back those parentheses, `C-M-q' should not change anything.  File: elisp, Node: Test Coverage, Next: Compilation Errors, Prev: Syntax Errors, Up: Debugging 18.4 Test Coverage ================== You can do coverage testing for a file of Lisp code by loading the `testcover' library and using the command `M-x testcover-start FILE ' to instrument the code. Then test your code by calling it one or more times. Then use the command `M-x testcover-mark-all' to display colored highlights on the code to show where coverage is insufficient. The command `M-x testcover-next-mark' will move point forward to the next highlighted spot. Normally, a red highlight indicates the form was never completely evaluated; a brown highlight means it always evaluated to the same value (meaning there has been little testing of what is done with the result). However, the red highlight is skipped for forms that can't possibly complete their evaluation, such as `error'. The brown highlight is skipped for forms that are expected to always evaluate to the same value, such as `(setq x 14)'. For difficult cases, you can add do-nothing macros to your code to give advice to the test coverage tool. -- Macro: 1value form Evaluate FORM and return its value, but inform coverage testing that FORM's value should always be the same. -- Macro: noreturn form Evaluate FORM, informing coverage testing that FORM should never return. If it ever does return, you get a run-time error. Edebug also has a coverage testing feature (*note Coverage Testing::). These features partly duplicate each other, and it would be cleaner to combine them.  File: elisp, Node: Compilation Errors, Prev: Test Coverage, Up: Debugging 18.5 Debugging Problems in Compilation ====================================== When an error happens during byte compilation, it is normally due to invalid syntax in the program you are compiling. The compiler prints a suitable error message in the `*Compile-Log*' buffer, and then stops. The message may state a function name in which the error was found, or it may not. Either way, here is how to find out where in the file the error occurred. What you should do is switch to the buffer ` *Compiler Input*'. (Note that the buffer name starts with a space, so it does not show up in `M-x list-buffers'.) This buffer contains the program being compiled, and point shows how far the byte compiler was able to read. If the error was due to invalid Lisp syntax, point shows exactly where the invalid syntax was _detected_. The cause of the error is not necessarily near by! Use the techniques in the previous section to find the error. If the error was detected while compiling a form that had been read successfully, then point is located at the end of the form. In this case, this technique can't localize the error precisely, but can still show you which function to check.  File: elisp, Node: Read and Print, Next: Minibuffers, Prev: Debugging, Up: Top 19 Reading and Printing Lisp Objects ************************************ "Printing" and "reading" are the operations of converting Lisp objects to textual form and vice versa. They use the printed representations and read syntax described in *note Lisp Data Types::. This chapter describes the Lisp functions for reading and printing. It also describes "streams", which specify where to get the text (if reading) or where to put it (if printing). * Menu: * Streams Intro:: Overview of streams, reading and printing. * Input Streams:: Various data types that can be used as input streams. * Input Functions:: Functions to read Lisp objects from text. * Output Streams:: Various data types that can be used as output streams. * Output Functions:: Functions to print Lisp objects as text. * Output Variables:: Variables that control what the printing functions do.  File: elisp, Node: Streams Intro, Next: Input Streams, Up: Read and Print 19.1 Introduction to Reading and Printing ========================================= "Reading" a Lisp object means parsing a Lisp expression in textual form and producing a corresponding Lisp object. This is how Lisp programs get into Lisp from files of Lisp code. We call the text the "read syntax" of the object. For example, the text `(a . 5)' is the read syntax for a cons cell whose CAR is `a' and whose CDR is the number 5. "Printing" a Lisp object means producing text that represents that object--converting the object to its "printed representation" (*note Printed Representation::). Printing the cons cell described above produces the text `(a . 5)'. Reading and printing are more or less inverse operations: printing the object that results from reading a given piece of text often produces the same text, and reading the text that results from printing an object usually produces a similar-looking object. For example, printing the symbol `foo' produces the text `foo', and reading that text returns the symbol `foo'. Printing a list whose elements are `a' and `b' produces the text `(a b)', and reading that text produces a list (but not the same list) with elements `a' and `b'. However, these two operations are not precisely inverse to each other. There are three kinds of exceptions: * Printing can produce text that cannot be read. For example, buffers, windows, frames, subprocesses and markers print as text that starts with `#'; if you try to read this text, you get an error. There is no way to read those data types. * One object can have multiple textual representations. For example, `1' and `01' represent the same integer, and `(a b)' and `(a . (b))' represent the same list. Reading will accept any of the alternatives, but printing must choose one of them. * Comments can appear at certain points in the middle of an object's read sequence without affecting the result of reading it.  File: elisp, Node: Input Streams, Next: Input Functions, Prev: Streams Intro, Up: Read and Print 19.2 Input Streams ================== Most of the Lisp functions for reading text take an "input stream" as an argument. The input stream specifies where or how to get the characters of the text to be read. Here are the possible types of input stream: BUFFER The input characters are read from BUFFER, starting with the character directly after point. Point advances as characters are read. MARKER The input characters are read from the buffer that MARKER is in, starting with the character directly after the marker. The marker position advances as characters are read. The value of point in the buffer has no effect when the stream is a marker. STRING The input characters are taken from STRING, starting at the first character in the string and using as many characters as required. FUNCTION The input characters are generated by FUNCTION, which must support two kinds of calls: * When it is called with no arguments, it should return the next character. * When it is called with one argument (always a character), FUNCTION should save the argument and arrange to return it on the next call. This is called "unreading" the character; it happens when the Lisp reader reads one character too many and wants to "put it back where it came from." In this case, it makes no difference what value FUNCTION returns. `t' `t' used as a stream means that the input is read from the minibuffer. In fact, the minibuffer is invoked once and the text given by the user is made into a string that is then used as the input stream. If Emacs is running in batch mode, standard input is used instead of the minibuffer. For example, (message "%s" (read t)) will read a Lisp expression from standard input and print the result to standard output. `nil' `nil' supplied as an input stream means to use the value of `standard-input' instead; that value is the "default input stream", and must be a non-`nil' input stream. SYMBOL A symbol as input stream is equivalent to the symbol's function definition (if any). Here is an example of reading from a stream that is a buffer, showing where point is located before and after: ---------- Buffer: foo ---------- This-!- is the contents of foo. ---------- Buffer: foo ---------- (read (get-buffer "foo")) => is (read (get-buffer "foo")) => the ---------- Buffer: foo ---------- This is the-!- contents of foo. ---------- Buffer: foo ---------- Note that the first read skips a space. Reading skips any amount of whitespace preceding the significant text. Here is an example of reading from a stream that is a marker, initially positioned at the beginning of the buffer shown. The value read is the symbol `This'. ---------- Buffer: foo ---------- This is the contents of foo. ---------- Buffer: foo ---------- (setq m (set-marker (make-marker) 1 (get-buffer "foo"))) => # (read m) => This m => # ;; Before the first space. Here we read from the contents of a string: (read "(When in) the course") => (When in) The following example reads from the minibuffer. The prompt is: `Lisp expression: '. (That is always the prompt used when you read from the stream `t'.) The user's input is shown following the prompt. (read t) => 23 ---------- Buffer: Minibuffer ---------- Lisp expression: 23 ---------- Buffer: Minibuffer ---------- Finally, here is an example of a stream that is a function, named `useless-stream'. Before we use the stream, we initialize the variable `useless-list' to a list of characters. Then each call to the function `useless-stream' obtains the next character in the list or unreads a character by adding it to the front of the list. (setq useless-list (append "XY()" nil)) => (88 89 40 41) (defun useless-stream (&optional unread) (if unread (setq useless-list (cons unread useless-list)) (prog1 (car useless-list) (setq useless-list (cdr useless-list))))) => useless-stream Now we read using the stream thus constructed: (read 'useless-stream) => XY useless-list => (40 41) Note that the open and close parentheses remain in the list. The Lisp reader encountered the open parenthesis, decided that it ended the input, and unread it. Another attempt to read from the stream at this point would read `()' and return `nil'. -- Function: get-file-char This function is used internally as an input stream to read from the input file opened by the function `load'. Don't use this function yourself.  File: elisp, Node: Input Functions, Next: Output Streams, Prev: Input Streams, Up: Read and Print 19.3 Input Functions ==================== This section describes the Lisp functions and variables that pertain to reading. In the functions below, STREAM stands for an input stream (see the previous section). If STREAM is `nil' or omitted, it defaults to the value of `standard-input'. An `end-of-file' error is signaled if reading encounters an unterminated list, vector, or string. -- Function: read &optional stream This function reads one textual Lisp expression from STREAM, returning it as a Lisp object. This is the basic Lisp input function. -- Function: read-from-string string &optional start end This function reads the first textual Lisp expression from the text in STRING. It returns a cons cell whose CAR is that expression, and whose CDR is an integer giving the position of the next remaining character in the string (i.e., the first one not read). If START is supplied, then reading begins at index START in the string (where the first character is at index 0). If you specify END, then reading is forced to stop just before that index, as if the rest of the string were not there. For example: (read-from-string "(setq x 55) (setq y 5)") => ((setq x 55) . 11) (read-from-string "\"A short string\"") => ("A short string" . 16) ;; Read starting at the first character. (read-from-string "(list 112)" 0) => ((list 112) . 10) ;; Read starting at the second character. (read-from-string "(list 112)" 1) => (list . 5) ;; Read starting at the seventh character, ;; and stopping at the ninth. (read-from-string "(list 112)" 6 8) => (11 . 8) -- Variable: standard-input This variable holds the default input stream--the stream that `read' uses when the STREAM argument is `nil'. The default is `t', meaning use the minibuffer. -- Variable: read-circle If non-`nil', this variable enables the reading of circular and shared structures. *Note Circular Objects::. Its default value is `t'.  File: elisp, Node: Output Streams, Next: Output Functions, Prev: Input Functions, Up: Read and Print 19.4 Output Streams =================== An output stream specifies what to do with the characters produced by printing. Most print functions accept an output stream as an optional argument. Here are the possible types of output stream: BUFFER The output characters are inserted into BUFFER at point. Point advances as characters are inserted. MARKER The output characters are inserted into the buffer that MARKER points into, at the marker position. The marker position advances as characters are inserted. The value of point in the buffer has no effect on printing when the stream is a marker, and this kind of printing does not move point (except that if the marker points at or before the position of point, point advances with the surrounding text, as usual). FUNCTION The output characters are passed to FUNCTION, which is responsible for storing them away. It is called with a single character as argument, as many times as there are characters to be output, and is responsible for storing the characters wherever you want to put them. `t' The output characters are displayed in the echo area. `nil' `nil' specified as an output stream means to use the value of `standard-output' instead; that value is the "default output stream", and must not be `nil'. SYMBOL A symbol as output stream is equivalent to the symbol's function definition (if any). Many of the valid output streams are also valid as input streams. The difference between input and output streams is therefore more a matter of how you use a Lisp object, than of different types of object. Here is an example of a buffer used as an output stream. Point is initially located as shown immediately before the `h' in `the'. At the end, point is located directly before that same `h'. ---------- Buffer: foo ---------- This is t-!-he contents of foo. ---------- Buffer: foo ---------- (print "This is the output" (get-buffer "foo")) => "This is the output" ---------- Buffer: foo ---------- This is t "This is the output" -!-he contents of foo. ---------- Buffer: foo ---------- Now we show a use of a marker as an output stream. Initially, the marker is in buffer `foo', between the `t' and the `h' in the word `the'. At the end, the marker has advanced over the inserted text so that it remains positioned before the same `h'. Note that the location of point, shown in the usual fashion, has no effect. ---------- Buffer: foo ---------- This is the -!-output ---------- Buffer: foo ---------- (setq m (copy-marker 10)) => # (print "More output for foo." m) => "More output for foo." ---------- Buffer: foo ---------- This is t "More output for foo." he -!-output ---------- Buffer: foo ---------- m => # The following example shows output to the echo area: (print "Echo Area output" t) => "Echo Area output" ---------- Echo Area ---------- "Echo Area output" ---------- Echo Area ---------- Finally, we show the use of a function as an output stream. The function `eat-output' takes each character that it is given and conses it onto the front of the list `last-output' (*note Building Lists::). At the end, the list contains all the characters output, but in reverse order. (setq last-output nil) => nil (defun eat-output (c) (setq last-output (cons c last-output))) => eat-output (print "This is the output" 'eat-output) => "This is the output" last-output => (10 34 116 117 112 116 117 111 32 101 104 116 32 115 105 32 115 105 104 84 34 10) Now we can put the output in the proper order by reversing the list: (concat (nreverse last-output)) => " \"This is the output\" " Calling `concat' converts the list to a string so you can see its contents more clearly.  File: elisp, Node: Output Functions, Next: Output Variables, Prev: Output Streams, Up: Read and Print 19.5 Output Functions ===================== This section describes the Lisp functions for printing Lisp objects--converting objects into their printed representation. Some of the Emacs printing functions add quoting characters to the output when necessary so that it can be read properly. The quoting characters used are `"' and `\'; they distinguish strings from symbols, and prevent punctuation characters in strings and symbols from being taken as delimiters when reading. *Note Printed Representation::, for full details. You specify quoting or no quoting by the choice of printing function. If the text is to be read back into Lisp, then you should print with quoting characters to avoid ambiguity. Likewise, if the purpose is to describe a Lisp object clearly for a Lisp programmer. However, if the purpose of the output is to look nice for humans, then it is usually better to print without quoting. Lisp objects can refer to themselves. Printing a self-referential object in the normal way would require an infinite amount of text, and the attempt could cause infinite recursion. Emacs detects such recursion and prints `#LEVEL' instead of recursively printing an object already being printed. For example, here `#0' indicates a recursive reference to the object at level 0 of the current print operation: (setq foo (list nil)) => (nil) (setcar foo foo) => (#0) In the functions below, STREAM stands for an output stream. (See the previous section for a description of output streams.) If STREAM is `nil' or omitted, it defaults to the value of `standard-output'. -- Function: print object &optional stream The `print' function is a convenient way of printing. It outputs the printed representation of OBJECT to STREAM, printing in addition one newline before OBJECT and another after it. Quoting characters are used. `print' returns OBJECT. For example: (progn (print 'The\ cat\ in) (print "the hat") (print " came back")) -| -| The\ cat\ in -| -| "the hat" -| -| " came back" => " came back" -- Function: prin1 object &optional stream This function outputs the printed representation of OBJECT to STREAM. It does not print newlines to separate output as `print' does, but it does use quoting characters just like `print'. It returns OBJECT. (progn (prin1 'The\ cat\ in) (prin1 "the hat") (prin1 " came back")) -| The\ cat\ in"the hat"" came back" => " came back" -- Function: princ object &optional stream This function outputs the printed representation of OBJECT to STREAM. It returns OBJECT. This function is intended to produce output that is readable by people, not by `read', so it doesn't insert quoting characters and doesn't put double-quotes around the contents of strings. It does not add any spacing between calls. (progn (princ 'The\ cat) (princ " in the \"hat\"")) -| The cat in the "hat" => " in the \"hat\"" -- Function: terpri &optional stream This function outputs a newline to STREAM. The name stands for "terminate print." -- Function: write-char character &optional stream This function outputs CHARACTER to STREAM. It returns CHARACTER. -- Function: prin1-to-string object &optional noescape This function returns a string containing the text that `prin1' would have printed for the same argument. (prin1-to-string 'foo) => "foo" (prin1-to-string (mark-marker)) => "#" If NOESCAPE is non-`nil', that inhibits use of quoting characters in the output. (This argument is supported in Emacs versions 19 and later.) (prin1-to-string "foo") => "\"foo\"" (prin1-to-string "foo" t) => "foo" See `format', in *note Formatting Strings::, for other ways to obtain the printed representation of a Lisp object as a string. -- Macro: with-output-to-string body... This macro executes the BODY forms with `standard-output' set up to feed output into a string. Then it returns that string. For example, if the current buffer name is `foo', (with-output-to-string (princ "The buffer is ") (princ (buffer-name))) returns `"The buffer is foo"'.  File: elisp, Node: Output Variables, Prev: Output Functions, Up: Read and Print 19.6 Variables Affecting Output =============================== -- Variable: standard-output The value of this variable is the default output stream--the stream that print functions use when the STREAM argument is `nil'. The default is `t', meaning display in the echo area. -- Variable: print-quoted If this is non-`nil', that means to print quoted forms using abbreviated reader syntax. `(quote foo)' prints as `'foo', `(function foo)' as `#'foo', and backquoted forms print using modern backquote syntax. -- Variable: print-escape-newlines If this variable is non-`nil', then newline characters in strings are printed as `\n' and formfeeds are printed as `\f'. Normally these characters are printed as actual newlines and formfeeds. This variable affects the print functions `prin1' and `print' that print with quoting. It does not affect `princ'. Here is an example using `prin1': (prin1 "a\nb") -| "a -| b" => "a b" (let ((print-escape-newlines t)) (prin1 "a\nb")) -| "a\nb" => "a b" In the second expression, the local binding of `print-escape-newlines' is in effect during the call to `prin1', but not during the printing of the result. -- Variable: print-escape-nonascii If this variable is non-`nil', then unibyte non-ASCII characters in strings are unconditionally printed as backslash sequences by the print functions `prin1' and `print' that print with quoting. Those functions also use backslash sequences for unibyte non-ASCII characters, regardless of the value of this variable, when the output stream is a multibyte buffer or a marker pointing into one. -- Variable: print-escape-multibyte If this variable is non-`nil', then multibyte non-ASCII characters in strings are unconditionally printed as backslash sequences by the print functions `prin1' and `print' that print with quoting. Those functions also use backslash sequences for multibyte non-ASCII characters, regardless of the value of this variable, when the output stream is a unibyte buffer or a marker pointing into one. -- Variable: print-length The value of this variable is the maximum number of elements to print in any list, vector or bool-vector. If an object being printed has more than this many elements, it is abbreviated with an ellipsis. If the value is `nil' (the default), then there is no limit. (setq print-length 2) => 2 (print '(1 2 3 4 5)) -| (1 2 ...) => (1 2 ...) -- Variable: print-level The value of this variable is the maximum depth of nesting of parentheses and brackets when printed. Any list or vector at a depth exceeding this limit is abbreviated with an ellipsis. A value of `nil' (which is the default) means no limit. -- User Option: eval-expression-print-length -- User Option: eval-expression-print-level These are the values for `print-length' and `print-level' used by `eval-expression', and thus, indirectly, by many interactive evaluation commands (*note Evaluating Emacs-Lisp Expressions: (emacs)Lisp Eval.). These variables are used for detecting and reporting circular and shared structure: -- Variable: print-circle If non-`nil', this variable enables detection of circular and shared structure in printing. *Note Circular Objects::. -- Variable: print-gensym If non-`nil', this variable enables detection of uninterned symbols (*note Creating Symbols::) in printing. When this is enabled, uninterned symbols print with the prefix `#:', which tells the Lisp reader to produce an uninterned symbol. -- Variable: print-continuous-numbering If non-`nil', that means number continuously across print calls. This affects the numbers printed for `#N=' labels and `#M#' references. Don't set this variable with `setq'; you should only bind it temporarily to `t' with `let'. When you do that, you should also bind `print-number-table' to `nil'. -- Variable: print-number-table This variable holds a vector used internally by printing to implement the `print-circle' feature. You should not use it except to bind it to `nil' when you bind `print-continuous-numbering'. -- Variable: float-output-format This variable specifies how to print floating point numbers. Its default value is `nil', meaning use the shortest output that represents the number without losing information. To control output format more precisely, you can put a string in this variable. The string should hold a `%'-specification to be used in the C function `sprintf'. For further restrictions on what you can use, see the variable's documentation string.  File: elisp, Node: Minibuffers, Next: Command Loop, Prev: Read and Print, Up: Top 20 Minibuffers ************** A "minibuffer" is a special buffer that Emacs commands use to read arguments more complicated than the single numeric prefix argument. These arguments include file names, buffer names, and command names (as in `M-x'). The minibuffer is displayed on the bottom line of the frame, in the same place as the echo area (*note The Echo Area::), but only while it is in use for reading an argument. * Menu: * Intro to Minibuffers:: Basic information about minibuffers. * Text from Minibuffer:: How to read a straight text string. * Object from Minibuffer:: How to read a Lisp object or expression. * Minibuffer History:: Recording previous minibuffer inputs so the user can reuse them. * Initial Input:: Specifying initial contents for the minibuffer. * Completion:: How to invoke and customize completion. * Yes-or-No Queries:: Asking a question with a simple answer. * Multiple Queries:: Asking a series of similar questions. * Reading a Password:: Reading a password from the terminal. * Minibuffer Commands:: Commands used as key bindings in minibuffers. * Minibuffer Contents:: How such commands access the minibuffer text. * Minibuffer Windows:: Operating on the special minibuffer windows. * Recursive Mini:: Whether recursive entry to minibuffer is allowed. * Minibuffer Misc:: Various customization hooks and variables.  File: elisp, Node: Intro to Minibuffers, Next: Text from Minibuffer, Up: Minibuffers 20.1 Introduction to Minibuffers ================================ In most ways, a minibuffer is a normal Emacs buffer. Most operations _within_ a buffer, such as editing commands, work normally in a minibuffer. However, many operations for managing buffers do not apply to minibuffers. The name of a minibuffer always has the form ` *Minibuf-NUMBER*', and it cannot be changed. Minibuffers are displayed only in special windows used only for minibuffers; these windows always appear at the bottom of a frame. (Sometimes frames have no minibuffer window, and sometimes a special kind of frame contains nothing but a minibuffer window; see *note Minibuffers and Frames::.) The text in the minibuffer always starts with the "prompt string", the text that was specified by the program that is using the minibuffer to tell the user what sort of input to type. This text is marked read-only so you won't accidentally delete or change it. It is also marked as a field (*note Fields::), so that certain motion functions, including `beginning-of-line', `forward-word', `forward-sentence', and `forward-paragraph', stop at the boundary between the prompt and the actual text. The minibuffer's window is normally a single line; it grows automatically if the contents require more space. You can explicitly resize it temporarily with the window sizing commands; it reverts to its normal size when the minibuffer is exited. You can resize it permanently by using the window sizing commands in the frame's other window, when the minibuffer is not active. If the frame contains just a minibuffer, you can change the minibuffer's size by changing the frame's size. Use of the minibuffer reads input events, and that alters the values of variables such as `this-command' and `last-command' (*note Command Loop Info::). Your program should bind them around the code that uses the minibuffer, if you do not want that to change them. Under some circumstances, a command can use a minibuffer even if there is an active minibuffer; such minibuffers are called a "recursive minibuffer". The first minibuffer is named ` *Minibuf-0*'. Recursive minibuffers are named by incrementing the number at the end of the name. (The names begin with a space so that they won't show up in normal buffer lists.) Of several recursive minibuffers, the innermost (or most recently entered) is the active minibuffer. We usually call this "the" minibuffer. You can permit or forbid recursive minibuffers by setting the variable `enable-recursive-minibuffers', or by putting properties of that name on command symbols (*Note Recursive Mini::.) Like other buffers, a minibuffer uses a local keymap (*note Keymaps::) to specify special key bindings. The function that invokes the minibuffer also sets up its local map according to the job to be done. *Note Text from Minibuffer::, for the non-completion minibuffer local maps. *Note Completion Commands::, for the minibuffer local maps for completion. When Emacs is running in batch mode, any request to read from the minibuffer actually reads a line from the standard input descriptor that was supplied when Emacs was started.  File: elisp, Node: Text from Minibuffer, Next: Object from Minibuffer, Prev: Intro to Minibuffers, Up: Minibuffers 20.2 Reading Text Strings with the Minibuffer ============================================= The most basic primitive for minibuffer input is `read-from-minibuffer', which can be used to read either a string or a Lisp object in textual form. The function `read-regexp' is used for reading regular expressions (*note Regular Expressions::), which are a special kind of string. There are also specialized functions for reading commands, variables, file names, etc. (*note Completion::). In most cases, you should not call minibuffer input functions in the middle of a Lisp function. Instead, do all minibuffer input as part of reading the arguments for a command, in the `interactive' specification. *Note Defining Commands::. -- Function: read-from-minibuffer prompt-string &optional initial-contents keymap read hist default inherit-input-method This function is the most general way to get input from the minibuffer. By default, it accepts arbitrary text and returns it as a string; however, if READ is non-`nil', then it uses `read' to convert the text into a Lisp object (*note Input Functions::). The first thing this function does is to activate a minibuffer and display it with PROMPT-STRING as the prompt. This value must be a string. Then the user can edit text in the minibuffer. When the user types a command to exit the minibuffer, `read-from-minibuffer' constructs the return value from the text in the minibuffer. Normally it returns a string containing that text. However, if READ is non-`nil', `read-from-minibuffer' reads the text and returns the resulting Lisp object, unevaluated. (*Note Input Functions::, for information about reading.) The argument DEFAULT specifies default values to make available through the history commands. It should be a string, a list of strings, or `nil'. The string or strings become the minibuffer's "future history," available to the user with `M-n'. If READ is non-`nil', then DEFAULT is also used as the input to `read', if the user enters empty input. If DEFAULT is a list of strings, the first string is used as the input. If DEFAULT is `nil', empty input results in an `end-of-file' error. However, in the usual case (where READ is `nil'), `read-from-minibuffer' ignores DEFAULT when the user enters empty input and returns an empty string, `""'. In this respect, it differs from all the other minibuffer input functions in this chapter. If KEYMAP is non-`nil', that keymap is the local keymap to use in the minibuffer. If KEYMAP is omitted or `nil', the value of `minibuffer-local-map' is used as the keymap. Specifying a keymap is the most important way to customize the minibuffer for various applications such as completion. The argument HIST specifies which history list variable to use for saving the input and for history commands used in the minibuffer. It defaults to `minibuffer-history'. *Note Minibuffer History::. If the variable `minibuffer-allow-text-properties' is non-`nil', then the string which is returned includes whatever text properties were present in the minibuffer. Otherwise all the text properties are stripped when the value is returned. If the argument INHERIT-INPUT-METHOD is non-`nil', then the minibuffer inherits the current input method (*note Input Methods::) and the setting of `enable-multibyte-characters' (*note Text Representations::) from whichever buffer was current before entering the minibuffer. Use of INITIAL-CONTENTS is mostly deprecated; we recommend using a non-`nil' value only in conjunction with specifying a cons cell for HIST. *Note Initial Input::. -- Function: read-string prompt &optional initial history default inherit-input-method This function reads a string from the minibuffer and returns it. The arguments PROMPT, INITIAL, HISTORY and INHERIT-INPUT-METHOD are used as in `read-from-minibuffer'. The keymap used is `minibuffer-local-map'. The optional argument DEFAULT is used as in `read-from-minibuffer', except that, if non-`nil', it also specifies a default value to return if the user enters null input. As in `read-from-minibuffer' it should be a string, a list of strings, or `nil' which is equivalent to an empty string. When DEFAULT is a string, that string is the default value. When it is a list of strings, the first string is the default value. (All these strings are available to the user in the "future minibuffer history.") This function works by calling the `read-from-minibuffer' function: (read-string PROMPT INITIAL HISTORY DEFAULT INHERIT) == (let ((value (read-from-minibuffer PROMPT INITIAL nil nil HISTORY DEFAULT INHERIT))) (if (and (equal value "") DEFAULT) (if (consp DEFAULT) (car DEFAULT) DEFAULT) value)) -- Function: read-regexp prompt &optional default-value This function reads a regular expression as a string from the minibuffer and returns it. The argument PROMPT is used as in `read-from-minibuffer'. The keymap used is `minibuffer-local-map', and `regexp-history' is used as the history list (*note regexp-history: Minibuffer History.). The optional argument DEFAULT-VALUE specifies a default value to return if the user enters null input; it should be a string, or `nil' which is equivalent to an empty string. In addition, `read-regexp' collects a few useful candidates for input and passes them to `read-from-minibuffer', to make them available to the user as the "future minibuffer history list" (*note future list: (emacs)Minibuffer History.). These candidates are: - The word or symbol at point. - The last regexp used in an incremental search. - The last string used in an incremental search. - The last string or pattern used in query-replace commands. This function works by calling the `read-from-minibuffer' function, after computing the list of defaults as described above. -- Variable: minibuffer-allow-text-properties If this variable is `nil', then `read-from-minibuffer' strips all text properties from the minibuffer input before returning it. This variable also affects `read-string'. However, `read-no-blanks-input' (see below), as well as `read-minibuffer' and related functions (*note Reading Lisp Objects With the Minibuffer: Object from Minibuffer.), and all functions that do minibuffer input with completion, discard text properties unconditionally, regardless of the value of this variable. -- Variable: minibuffer-local-map This is the default local keymap for reading from the minibuffer. By default, it makes the following bindings: `C-j' `exit-minibuffer' `exit-minibuffer' `C-g' `abort-recursive-edit' `M-n' `next-history-element' `M-p' `previous-history-element' `M-s' `next-matching-history-element' `M-r' `previous-matching-history-element' -- Function: read-no-blanks-input prompt &optional initial inherit-input-method This function reads a string from the minibuffer, but does not allow whitespace characters as part of the input: instead, those characters terminate the input. The arguments PROMPT, INITIAL, and INHERIT-INPUT-METHOD are used as in `read-from-minibuffer'. This is a simplified interface to the `read-from-minibuffer' function, and passes the value of the `minibuffer-local-ns-map' keymap as the KEYMAP argument for that function. Since the keymap `minibuffer-local-ns-map' does not rebind `C-q', it _is_ possible to put a space into the string, by quoting it. This function discards text properties, regardless of the value of `minibuffer-allow-text-properties'. (read-no-blanks-input PROMPT INITIAL) == (let (minibuffer-allow-text-properties) (read-from-minibuffer PROMPT INITIAL minibuffer-local-ns-map)) -- Variable: minibuffer-local-ns-map This built-in variable is the keymap used as the minibuffer local keymap in the function `read-no-blanks-input'. By default, it makes the following bindings, in addition to those of `minibuffer-local-map': `exit-minibuffer' `exit-minibuffer' `?' `self-insert-and-exit'  File: elisp, Node: Object from Minibuffer, Next: Minibuffer History, Prev: Text from Minibuffer, Up: Minibuffers 20.3 Reading Lisp Objects with the Minibuffer ============================================= This section describes functions for reading Lisp objects with the minibuffer. -- Function: read-minibuffer prompt &optional initial This function reads a Lisp object using the minibuffer, and returns it without evaluating it. The arguments PROMPT and INITIAL are used as in `read-from-minibuffer'. This is a simplified interface to the `read-from-minibuffer' function: (read-minibuffer PROMPT INITIAL) == (let (minibuffer-allow-text-properties) (read-from-minibuffer PROMPT INITIAL nil t)) Here is an example in which we supply the string `"(testing)"' as initial input: (read-minibuffer "Enter an expression: " (format "%s" '(testing))) ;; Here is how the minibuffer is displayed: ---------- Buffer: Minibuffer ---------- Enter an expression: (testing)-!- ---------- Buffer: Minibuffer ---------- The user can type immediately to use the initial input as a default, or can edit the input. -- Function: eval-minibuffer prompt &optional initial This function reads a Lisp expression using the minibuffer, evaluates it, then returns the result. The arguments PROMPT and INITIAL are used as in `read-from-minibuffer'. This function simply evaluates the result of a call to `read-minibuffer': (eval-minibuffer PROMPT INITIAL) == (eval (read-minibuffer PROMPT INITIAL)) -- Function: edit-and-eval-command prompt form This function reads a Lisp expression in the minibuffer, and then evaluates it. The difference between this command and `eval-minibuffer' is that here the initial FORM is not optional and it is treated as a Lisp object to be converted to printed representation rather than as a string of text. It is printed with `prin1', so if it is a string, double-quote characters (`"') appear in the initial text. *Note Output Functions::. The first thing `edit-and-eval-command' does is to activate the minibuffer with PROMPT as the prompt. Then it inserts the printed representation of FORM in the minibuffer, and lets the user edit it. When the user exits the minibuffer, the edited text is read with `read' and then evaluated. The resulting value becomes the value of `edit-and-eval-command'. In the following example, we offer the user an expression with initial text which is a valid form already: (edit-and-eval-command "Please edit: " '(forward-word 1)) ;; After evaluation of the preceding expression, ;; the following appears in the minibuffer: ---------- Buffer: Minibuffer ---------- Please edit: (forward-word 1)-!- ---------- Buffer: Minibuffer ---------- Typing right away would exit the minibuffer and evaluate the expression, thus moving point forward one word. `edit-and-eval-command' returns `nil' in this example.  File: elisp, Node: Minibuffer History, Next: Initial Input, Prev: Object from Minibuffer, Up: Minibuffers 20.4 Minibuffer History ======================= A "minibuffer history list" records previous minibuffer inputs so the user can reuse them conveniently. A history list is actually a symbol, not a list; it is a variable whose value is a list of strings (previous inputs), most recent first. There are many separate history lists, used for different kinds of inputs. It's the Lisp programmer's job to specify the right history list for each use of the minibuffer. You specify the history list with the optional HIST argument to either `read-from-minibuffer' or `completing-read'. Here are the possible values for it: VARIABLE Use VARIABLE (a symbol) as the history list. (VARIABLE . STARTPOS) Use VARIABLE (a symbol) as the history list, and assume that the initial history position is STARTPOS (a nonnegative integer). Specifying 0 for STARTPOS is equivalent to just specifying the symbol VARIABLE. `previous-history-element' will display the most recent element of the history list in the minibuffer. If you specify a positive STARTPOS, the minibuffer history functions behave as if `(elt VARIABLE (1- STARTPOS))' were the history element currently shown in the minibuffer. For consistency, you should also specify that element of the history as the initial minibuffer contents, using the INITIAL argument to the minibuffer input function (*note Initial Input::). If you don't specify HIST, then the default history list `minibuffer-history' is used. For other standard history lists, see below. You can also create your own history list variable; just initialize it to `nil' before the first use. Both `read-from-minibuffer' and `completing-read' add new elements to the history list automatically, and provide commands to allow the user to reuse items on the list. The only thing your program needs to do to use a history list is to initialize it and to pass its name to the input functions when you wish. But it is safe to modify the list by hand when the minibuffer input functions are not using it. Emacs functions that add a new element to a history list can also delete old elements if the list gets too long. The variable `history-length' specifies the maximum length for most history lists. To specify a different maximum length for a particular history list, put the length in the `history-length' property of the history list symbol. The variable `history-delete-duplicates' specifies whether to delete duplicates in history. -- Function: add-to-history history-var newelt &optional maxelt keep-all This function adds a new element NEWELT, if it isn't the empty string, to the history list stored in the variable HISTORY-VAR, and returns the updated history list. It limits the list length to the value of MAXELT (if non-`nil') or `history-length' (described below). The possible values of MAXELT have the same meaning as the values of `history-length'. Normally, `add-to-history' removes duplicate members from the history list if `history-delete-duplicates' is non-`nil'. However, if KEEP-ALL is non-`nil', that says not to remove duplicates, and to add NEWELT to the list even if it is empty. -- Variable: history-add-new-input If the value of this variable is `nil', standard functions that read from the minibuffer don't add new elements to the history list. This lets Lisp programs explicitly manage input history by using `add-to-history'. By default, `history-add-new-input' is set to a non-`nil' value. -- User Option: history-length The value of this variable specifies the maximum length for all history lists that don't specify their own maximum lengths. If the value is `t', that means there is no maximum (don't delete old elements). The value of `history-length' property of the history list variable's symbol, if set, overrides this variable for that particular history list. -- User Option: history-delete-duplicates If the value of this variable is `t', that means when adding a new history element, all previous identical elements are deleted. Here are some of the standard minibuffer history list variables: -- Variable: minibuffer-history The default history list for minibuffer history input. -- Variable: query-replace-history A history list for arguments to `query-replace' (and similar arguments to other commands). -- Variable: file-name-history A history list for file-name arguments. -- Variable: buffer-name-history A history list for buffer-name arguments. -- Variable: regexp-history A history list for regular expression arguments. -- Variable: extended-command-history A history list for arguments that are names of extended commands. -- Variable: shell-command-history A history list for arguments that are shell commands. -- Variable: read-expression-history A history list for arguments that are Lisp expressions to evaluate.  File: elisp, Node: Initial Input, Next: Completion, Prev: Minibuffer History, Up: Minibuffers 20.5 Initial Input ================== Several of the functions for minibuffer input have an argument called INITIAL or INITIAL-CONTENTS. This is a mostly-deprecated feature for specifying that the minibuffer should start out with certain text, instead of empty as usual. If INITIAL is a string, the minibuffer starts out containing the text of the string, with point at the end, when the user starts to edit the text. If the user simply types to exit the minibuffer, it will use the initial input string to determine the value to return. *We discourage use of a non-`nil' value for INITIAL*, because initial input is an intrusive interface. History lists and default values provide a much more convenient method to offer useful default inputs to the user. There is just one situation where you should specify a string for an INITIAL argument. This is when you specify a cons cell for the HIST or HISTORY argument. *Note Minibuffer History::. INITIAL can also be a cons cell of the form `(STRING . POSITION)'. This means to insert STRING in the minibuffer but put point at POSITION within the string's text. As a historical accident, POSITION was implemented inconsistently in different functions. In `completing-read', POSITION's value is interpreted as origin-zero; that is, a value of 0 means the beginning of the string, 1 means after the first character, etc. In `read-minibuffer', and the other non-completion minibuffer input functions that support this argument, 1 means the beginning of the string 2 means after the first character, etc. Use of a cons cell as the value for INITIAL arguments is deprecated in user code.  File: elisp, Node: Completion, Next: Yes-or-No Queries, Prev: Initial Input, Up: Minibuffers 20.6 Completion =============== "Completion" is a feature that fills in the rest of a name starting from an abbreviation for it. Completion works by comparing the user's input against a list of valid names and determining how much of the name is determined uniquely by what the user has typed. For example, when you type `C-x b' (`switch-to-buffer') and then type the first few letters of the name of the buffer to which you wish to switch, and then type (`minibuffer-complete'), Emacs extends the name as far as it can. Standard Emacs commands offer completion for names of symbols, files, buffers, and processes; with the functions in this section, you can implement completion for other kinds of names. The `try-completion' function is the basic primitive for completion: it returns the longest determined completion of a given initial string, with a given set of strings to match against. The function `completing-read' provides a higher-level interface for completion. A call to `completing-read' specifies how to determine the list of valid names. The function then activates the minibuffer with a local keymap that binds a few keys to commands useful for completion. Other functions provide convenient simple interfaces for reading certain kinds of names with completion. * Menu: * Basic Completion:: Low-level functions for completing strings. * Minibuffer Completion:: Invoking the minibuffer with completion. * Completion Commands:: Minibuffer commands that do completion. * High-Level Completion:: Convenient special cases of completion (reading buffer name, file name, etc.). * Reading File Names:: Using completion to read file names and shell commands. * Completion Styles:: Specifying rules for performing completion. * Programmed Completion:: Writing your own completion-function.  File: elisp, Node: Basic Completion, Next: Minibuffer Completion, Up: Completion 20.6.1 Basic Completion Functions --------------------------------- The following completion functions have nothing in themselves to do with minibuffers. We describe them here to keep them near the higher-level completion features that do use the minibuffer. -- Function: try-completion string collection &optional predicate This function returns the longest common substring of all possible completions of STRING in COLLECTION. The value of COLLECTION must be a list of strings or symbols, an alist, an obarray, a hash table, or a completion function (*note Programmed Completion::). Completion compares STRING against each of the permissible completions specified by COLLECTION. If no permissible completions match, `try-completion' returns `nil'. If there is just one matching completion, and the match is exact, it returns `t'. Otherwise, it returns the longest initial sequence common to all possible matching completions. If COLLECTION is an alist (*note Association Lists::), the permissible completions are the elements of the alist that are either strings, symbols, or conses whose CAR is a string or symbol. Symbols are converted to strings using `symbol-name'. Other elements of the alist are ignored. (Remember that in Emacs Lisp, the elements of alists do not _have_ to be conses.) In particular, a list of strings or symbols is allowed, even though we usually do not think of such lists as alists. If COLLECTION is an obarray (*note Creating Symbols::), the names of all symbols in the obarray form the set of permissible completions. The global variable `obarray' holds an obarray containing the names of all interned Lisp symbols. Note that the only valid way to make a new obarray is to create it empty and then add symbols to it one by one using `intern'. Also, you cannot intern a given symbol in more than one obarray. If COLLECTION is a hash table, then the keys that are strings are the possible completions. Other keys are ignored. You can also use a symbol that is a function as COLLECTION. Then the function is solely responsible for performing completion; `try-completion' returns whatever this function returns. The function is called with three arguments: STRING, PREDICATE and `nil' (the reason for the third argument is so that the same function can be used in `all-completions' and do the appropriate thing in either case). *Note Programmed Completion::. If the argument PREDICATE is non-`nil', then it must be a function of one argument, unless COLLECTION is a hash table, in which case it should be a function of two arguments. It is used to test each possible match, and the match is accepted only if PREDICATE returns non-`nil'. The argument given to PREDICATE is either a string or a cons cell (the CAR of which is a string) from the alist, or a symbol (_not_ a symbol name) from the obarray. If COLLECTION is a hash table, PREDICATE is called with two arguments, the string key and the associated value. In addition, to be acceptable, a completion must also match all the regular expressions in `completion-regexp-list'. (Unless COLLECTION is a function, in which case that function has to handle `completion-regexp-list' itself.) In the first of the following examples, the string `foo' is matched by three of the alist CARs. All of the matches begin with the characters `fooba', so that is the result. In the second example, there is only one possible match, and it is exact, so the value is `t'. (try-completion "foo" '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4))) => "fooba" (try-completion "foo" '(("barfoo" 2) ("foo" 3))) => t In the following example, numerous symbols begin with the characters `forw', and all of them begin with the word `forward'. In most of the symbols, this is followed with a `-', but not in all, so no more than `forward' can be completed. (try-completion "forw" obarray) => "forward" Finally, in the following example, only two of the three possible matches pass the predicate `test' (the string `foobaz' is too short). Both of those begin with the string `foobar'. (defun test (s) (> (length (car s)) 6)) => test (try-completion "foo" '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4)) 'test) => "foobar" -- Function: all-completions string collection &optional predicate nospace This function returns a list of all possible completions of STRING. The arguments to this function (aside from NOSPACE) are the same as those of `try-completion'. Also, this function uses `completion-regexp-list' in the same way that `try-completion' does. The optional argument NOSPACE is obsolete. If it is non-`nil', completions that start with a space are ignored unless STRING starts with a space. If COLLECTION is a function, it is called with three arguments: STRING, PREDICATE and `t'; then `all-completions' returns whatever the function returns. *Note Programmed Completion::. Here is an example, using the function `test' shown in the example for `try-completion': (defun test (s) (> (length (car s)) 6)) => test (all-completions "foo" '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4)) 'test) => ("foobar1" "foobar2") -- Function: test-completion string collection &optional predicate This function returns non-`nil' if STRING is a valid completion possibility specified by COLLECTION and PREDICATE. The arguments are the same as in `try-completion'. For instance, if COLLECTION is a list of strings, this is true if STRING appears in the list and PREDICATE is satisfied. This function uses `completion-regexp-list' in the same way that `try-completion' does. If PREDICATE is non-`nil' and if COLLECTION contains several strings that are equal to each other, as determined by `compare-strings' according to `completion-ignore-case', then PREDICATE should accept either all or none of them. Otherwise, the return value of `test-completion' is essentially unpredictable. If COLLECTION is a function, it is called with three arguments, the values STRING, PREDICATE and `lambda'; whatever it returns, `test-completion' returns in turn. If you store a completion alist in a variable, you should mark the variable as "risky" with a non-`nil' `risky-local-variable' property. *Note File Local Variables::. -- Variable: completion-ignore-case If the value of this variable is non-`nil', Emacs does not consider case significant in completion. Note, however, that this variable is overridden by `read-file-name-completion-ignore-case' within `read-file-name' (*note Reading File Names::), and by `read-buffer-completion-ignore-case' within `read-buffer' (*note High-Level Completion::). -- Variable: completion-regexp-list This is a list of regular expressions. The completion functions only consider a completion acceptable if it matches all regular expressions in this list, with `case-fold-search' (*note Searching and Case::) bound to the value of `completion-ignore-case'. -- Macro: lazy-completion-table var fun This macro provides a way to initialize the variable VAR as a collection for completion in a lazy way, not computing its actual contents until they are first needed. You use this macro to produce a value that you store in VAR. The actual computation of the proper value is done the first time you do completion using VAR. It is done by calling FUN with no arguments. The value FUN returns becomes the permanent value of VAR. Here is an example of use: (defvar foo (lazy-completion-table foo make-my-alist)) The function `completion-in-region' provides a convenient way to perform completion on an arbitrary stretch of text in an Emacs buffer: -- Function: completion-in-region start end collection &optional predicate This function completes the text in the current buffer between the positions START and END, using COLLECTION. The argument COLLECTION has the same meaning as in `try-completion' (*note Basic Completion::). This function inserts the completion text directly into the current buffer. Unlike `completing-read' (*note Minibuffer Completion::), it does not activate the minibuffer. For this function to work, point must be somewhere between START and END.  File: elisp, Node: Minibuffer Completion, Next: Completion Commands, Prev: Basic Completion, Up: Completion 20.6.2 Completion and the Minibuffer ------------------------------------ This section describes the basic interface for reading from the minibuffer with completion. -- Function: completing-read prompt collection &optional predicate require-match initial hist default inherit-input-method This function reads a string in the minibuffer, assisting the user by providing completion. It activates the minibuffer with prompt PROMPT, which must be a string. The actual completion is done by passing COLLECTION and PREDICATE to the function `try-completion' (*note Basic Completion::). This happens in certain commands bound in the local keymaps used for completion. Some of these commands also call `test-completion'. Thus, if PREDICATE is non-`nil', it should be compatible with COLLECTION and `completion-ignore-case'. *Note Definition of test-completion::. The value of the optional argument REQUIRE-MATCH determines how the user may exit the minibuffer: * If `nil', the usual minibuffer exit commands work regardless of the input in the minibuffer. * If `t', the usual minibuffer exit commands won't exit unless the input completes to an element of COLLECTION. * If `confirm', the user can exit with any input, but is asked for confirmation if the input is not an element of COLLECTION. * If `confirm-after-completion', the user can exit with any input, but is asked for confirmation if the preceding command was a completion command (i.e., one of the commands in `minibuffer-confirm-exit-commands') and the resulting input is not an element of COLLECTION. *Note Completion Commands::. * Any other value of REQUIRE-MATCH behaves like `t', except that the exit commands won't exit if it performs completion. However, empty input is always permitted, regardless of the value of REQUIRE-MATCH; in that case, `completing-read' returns the first element of DEFAULT, if it is a list; `""', if DEFAULT is `nil'; or DEFAULT. The string or strings in DEFAULT are also available to the user through the history commands. The function `completing-read' uses `minibuffer-local-completion-map' as the keymap if REQUIRE-MATCH is `nil', and uses `minibuffer-local-must-match-map' if REQUIRE-MATCH is non-`nil'. *Note Completion Commands::. The argument HIST specifies which history list variable to use for saving the input and for minibuffer history commands. It defaults to `minibuffer-history'. *Note Minibuffer History::. The argument INITIAL is mostly deprecated; we recommend using a non-`nil' value only in conjunction with specifying a cons cell for HIST. *Note Initial Input::. For default input, use DEFAULT instead. If the argument INHERIT-INPUT-METHOD is non-`nil', then the minibuffer inherits the current input method (*note Input Methods::) and the setting of `enable-multibyte-characters' (*note Text Representations::) from whichever buffer was current before entering the minibuffer. If the built-in variable `completion-ignore-case' is non-`nil', completion ignores case when comparing the input against the possible matches. *Note Basic Completion::. In this mode of operation, PREDICATE must also ignore case, or you will get surprising results. Here's an example of using `completing-read': (completing-read "Complete a foo: " '(("foobar1" 1) ("barfoo" 2) ("foobaz" 3) ("foobar2" 4)) nil t "fo") ;; After evaluation of the preceding expression, ;; the following appears in the minibuffer: ---------- Buffer: Minibuffer ---------- Complete a foo: fo-!- ---------- Buffer: Minibuffer ---------- If the user then types ` b ', `completing-read' returns `barfoo'. The `completing-read' function binds variables to pass information to the commands that actually do completion. They are described in the following section.  File: elisp, Node: Completion Commands, Next: High-Level Completion, Prev: Minibuffer Completion, Up: Completion 20.6.3 Minibuffer Commands that Do Completion --------------------------------------------- This section describes the keymaps, commands and user options used in the minibuffer to do completion. -- Variable: minibuffer-completion-table The value of this variable is the collection used for completion in the minibuffer. This is the global variable that contains what `completing-read' passes to `try-completion'. It is used by minibuffer completion commands such as `minibuffer-complete-word'. -- Variable: minibuffer-completion-predicate This variable's value is the predicate that `completing-read' passes to `try-completion'. The variable is also used by the other minibuffer completion functions. -- Variable: minibuffer-completion-confirm This variable determines whether Emacs asks for confirmation before exiting the minibuffer; `completing-read' binds this variable, and the function `minibuffer-complete-and-exit' checks the value before exiting. If the value is `nil', confirmation is not required. If the value is `confirm', the user may exit with an input that is not a valid completion alternative, but Emacs asks for confirmation. If the value is `confirm-after-completion', the user may exit with an input that is not a valid completion alternative, but Emacs asks for confirmation if the user submitted the input right after any of the completion commands in `minibuffer-confirm-exit-commands'. -- Variable: minibuffer-confirm-exit-commands This variable holds a list of commands that cause Emacs to ask for confirmation before exiting the minibuffer, if the REQUIRE-MATCH argument to `completing-read' is `confirm-after-completion'. The confirmation is requested if the user attempts to exit the minibuffer immediately after calling any command in this list. -- Command: minibuffer-complete-word This function completes the minibuffer contents by at most a single word. Even if the minibuffer contents have only one completion, `minibuffer-complete-word' does not add any characters beyond the first character that is not a word constituent. *Note Syntax Tables::. -- Command: minibuffer-complete This function completes the minibuffer contents as far as possible. -- Command: minibuffer-complete-and-exit This function completes the minibuffer contents, and exits if confirmation is not required, i.e., if `minibuffer-completion-confirm' is `nil'. If confirmation _is_ required, it is given by repeating this command immediately--the command is programmed to work without confirmation when run twice in succession. -- Command: minibuffer-completion-help This function creates a list of the possible completions of the current minibuffer contents. It works by calling `all-completions' using the value of the variable `minibuffer-completion-table' as the COLLECTION argument, and the value of `minibuffer-completion-predicate' as the PREDICATE argument. The list of completions is displayed as text in a buffer named `*Completions*'. -- Function: display-completion-list completions &optional common-substring This function displays COMPLETIONS to the stream in `standard-output', usually a buffer. (*Note Read and Print::, for more information about streams.) The argument COMPLETIONS is normally a list of completions just returned by `all-completions', but it does not have to be. Each element may be a symbol or a string, either of which is simply printed. It can also be a list of two strings, which is printed as if the strings were concatenated. The first of the two strings is the actual completion, the second string serves as annotation. The argument COMMON-SUBSTRING is the prefix that is common to all the completions. With normal Emacs completion, it is usually the same as the string that was completed. `display-completion-list' uses this to highlight text in the completion list for better visual feedback. This is not needed in the minibuffer; for minibuffer completion, you can pass `nil'. This function is called by `minibuffer-completion-help'. The most common way to use it is together with `with-output-to-temp-buffer', like this: (with-output-to-temp-buffer "*Completions*" (display-completion-list (all-completions (buffer-string) my-alist) (buffer-string))) -- User Option: completion-auto-help If this variable is non-`nil', the completion commands automatically display a list of possible completions whenever nothing can be completed because the next character is not uniquely determined. -- Variable: minibuffer-local-completion-map `completing-read' uses this value as the local keymap when an exact match of one of the completions is not required. By default, this keymap makes the following bindings: `?' `minibuffer-completion-help' `minibuffer-complete-word' `minibuffer-complete' with other characters bound as in `minibuffer-local-map' (*note Definition of minibuffer-local-map::). -- Variable: minibuffer-local-must-match-map `completing-read' uses this value as the local keymap when an exact match of one of the completions is required. Therefore, no keys are bound to `exit-minibuffer', the command that exits the minibuffer unconditionally. By default, this keymap makes the following bindings: `?' `minibuffer-completion-help' `minibuffer-complete-word' `minibuffer-complete' `C-j' `minibuffer-complete-and-exit' `minibuffer-complete-and-exit' with other characters bound as in `minibuffer-local-map'. -- Variable: minibuffer-local-filename-completion-map This is like `minibuffer-local-completion-map' except that it does not bind . This keymap is used by the function `read-file-name'. -- Variable: minibuffer-local-filename-must-match-map This is like `minibuffer-local-must-match-map' except that it does not bind . This keymap is used by the function `read-file-name'.  File: elisp, Node: High-Level Completion, Next: Reading File Names, Prev: Completion Commands, Up: Completion 20.6.4 High-Level Completion Functions -------------------------------------- This section describes the higher-level convenient functions for reading certain sorts of names with completion. In most cases, you should not call these functions in the middle of a Lisp function. When possible, do all minibuffer input as part of reading the arguments for a command, in the `interactive' specification. *Note Defining Commands::. -- Function: read-buffer prompt &optional default require-match This function reads the name of a buffer and returns it as a string. The argument DEFAULT is the default name to use, the value to return if the user exits with an empty minibuffer. If non-`nil', it should be a string, a list of strings, or a buffer. If it is a list, the default value is the first element of this list. It is mentioned in the prompt, but is not inserted in the minibuffer as initial input. The argument PROMPT should be a string ending with a colon and a space. If DEFAULT is non-`nil', the function inserts it in PROMPT before the colon to follow the convention for reading from the minibuffer with a default value (*note Programming Tips::). The optional argument REQUIRE-MATCH has the same meaning as in `completing-read'. *Note Minibuffer Completion::. In the following example, the user enters `minibuffer.t', and then types . The argument REQUIRE-MATCH is `t', and the only buffer name starting with the given input is `minibuffer.texi', so that name is the value. (read-buffer "Buffer name: " "foo" t) ;; After evaluation of the preceding expression, ;; the following prompt appears, ;; with an empty minibuffer: ---------- Buffer: Minibuffer ---------- Buffer name (default foo): -!- ---------- Buffer: Minibuffer ---------- ;; The user types `minibuffer.t '. => "minibuffer.texi" -- User Option: read-buffer-function This variable specifies how to read buffer names. For example, if you set this variable to `iswitchb-read-buffer', all Emacs commands that call `read-buffer' to read a buffer name will actually use the `iswitchb' package to read it. -- User Option: read-buffer-completion-ignore-case If this variable is non-`nil', `read-buffer' ignores case when performing completion. -- Function: read-command prompt &optional default This function reads the name of a command and returns it as a Lisp symbol. The argument PROMPT is used as in `read-from-minibuffer'. Recall that a command is anything for which `commandp' returns `t', and a command name is a symbol for which `commandp' returns `t'. *Note Interactive Call::. The argument DEFAULT specifies what to return if the user enters null input. It can be a symbol, a string or a list of strings. If it is a string, `read-command' interns it before returning it. If it is a list, `read-command' returns the first element of this list. If DEFAULT is `nil', that means no default has been specified; then if the user enters null input, the return value is `(intern "")', that is, a symbol whose name is an empty string. (read-command "Command name? ") ;; After evaluation of the preceding expression, ;; the following prompt appears with an empty minibuffer: ---------- Buffer: Minibuffer ---------- Command name? ---------- Buffer: Minibuffer ---------- If the user types `forward-c ', then this function returns `forward-char'. The `read-command' function is a simplified interface to `completing-read'. It uses the variable `obarray' so as to complete in the set of extant Lisp symbols, and it uses the `commandp' predicate so as to accept only command names: (read-command PROMPT) == (intern (completing-read PROMPT obarray 'commandp t nil)) -- Function: read-variable prompt &optional default This function reads the name of a user variable and returns it as a symbol. The argument DEFAULT specifies the default value to return if the user enters null input. It can be a symbol, a string, or a list of strings. If it is a string, `read-variable' interns it to make the default value. If it is a list, `read-variable' interns the first element. If DEFAULT is `nil', that means no default has been specified; then if the user enters null input, the return value is `(intern "")'. (read-variable "Variable name? ") ;; After evaluation of the preceding expression, ;; the following prompt appears, ;; with an empty minibuffer: ---------- Buffer: Minibuffer ---------- Variable name? -!- ---------- Buffer: Minibuffer ---------- If the user then types `fill-p ', `read-variable' returns `fill-prefix'. In general, `read-variable' is similar to `read-command', but uses the predicate `user-variable-p' instead of `commandp': (read-variable PROMPT) == (intern (completing-read PROMPT obarray 'user-variable-p t nil)) -- Command: read-color &optional prompt convert allow-empty display This function reads a string that is a color specification, either the color's name or an RGB hex value such as `#RRRGGGBBB'. It prompts with PROMPT (default: `"Color (name or #R+G+B+):"') and provides completion for color names, but not for hex RGB values. In addition to names of standard colors, completion candidates include the foreground and background colors at point. Valid RGB values are described in *note Color Names::. The function's return value is the color name typed by the user in the minibuffer. However, when called interactively or if the optional argument CONVERT is non-`nil', it converts the name into the color's RGB value and returns that value as a string. If an invalid color name was specified, this function signals an error, except that empty color names are allowed when `allow-empty' is non-`nil' and the user enters null input. Interactively, or when DISPLAY is non-`nil', the return value is also displayed in the echo area. See also the functions `read-coding-system' and `read-non-nil-coding-system', in *note User-Chosen Coding Systems::, and `read-input-method-name', in *note Input Methods::.