This is ../info/lispref.info, produced by makeinfo version 4.8 from
lispref/lispref.texi.

INFO-DIR-SECTION XEmacs Editor
START-INFO-DIR-ENTRY
* Lispref: (lispref).		XEmacs Lisp Reference Manual.
END-INFO-DIR-ENTRY

   Edition History:

   GNU Emacs Lisp Reference Manual Second Edition (v2.01), May 1993 GNU
Emacs Lisp Reference Manual Further Revised (v2.02), August 1993 Lucid
Emacs Lisp Reference Manual (for 19.10) First Edition, March 1994
XEmacs Lisp Programmer's Manual (for 19.12) Second Edition, April 1995
GNU Emacs Lisp Reference Manual v2.4, June 1995 XEmacs Lisp
Programmer's Manual (for 19.13) Third Edition, July 1995 XEmacs Lisp
Reference Manual (for 19.14 and 20.0) v3.1, March 1996 XEmacs Lisp
Reference Manual (for 19.15 and 20.1, 20.2, 20.3) v3.2, April, May,
November 1997 XEmacs Lisp Reference Manual (for 21.0) v3.3, April 1998

   Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995 Free Software
Foundation, Inc.  Copyright (C) 1994, 1995 Sun Microsystems, Inc.
Copyright (C) 1995, 1996 Ben Wing.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Foundation.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU General Public License" is included
exactly as in the original, and provided that the entire resulting
derived work is distributed under the terms of a permission notice
identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the section entitled "GNU General Public License"
may be included in a translation approved by the Free Software
Foundation instead of in the original English.


File: lispref.info,  Node: Problems with Macros,  Prev: Backquote,  Up: Macros

18.6 Common Problems Using Macros
=================================

The basic facts of macro expansion have counterintuitive consequences.
This section describes some important consequences that can lead to
trouble, and rules to follow to avoid trouble.

* Menu:

* Argument Evaluation::    The expansion should evaluate each macro arg once.
* Surprising Local Vars::  Local variable bindings in the expansion
                              require special care.
* Eval During Expansion::  Don't evaluate them; put them in the expansion.
* Repeated Expansion::     Avoid depending on how many times expansion is done.


File: lispref.info,  Node: Argument Evaluation,  Next: Surprising Local Vars,  Prev: Problems with Macros,  Up: Problems with Macros

18.6.1 Evaluating Macro Arguments Repeatedly
--------------------------------------------

When defining a macro you must pay attention to the number of times the
arguments will be evaluated when the expansion is executed.  The
following macro (used to facilitate iteration) illustrates the problem.
This macro allows us to write a simple "for" loop such as one might
find in Pascal.

     (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))."
       (list 'let (list (list var init))
             (cons 'while (cons (list '<= var final)
                                (append body (list (list 'inc var)))))))
     => for

     (for i from 1 to 3 do
        (setq square (* i i))
        (princ (format "\n%d %d" i square)))
     ==>
     (let ((i 1))
       (while (<= i 3)
         (setq square (* i i))
         (princ (format "%d      %d" i square))
         (inc i)))

          -|1       1
          -|2       4
          -|3       9
     => nil

(The arguments `from', `to', and `do' in this macro are "syntactic
sugar"; they are entirely ignored.  The idea is that you will write
noise words (such as `from', `to', and `do') in those positions in the
macro call.)

   Here's an equivalent definition simplified through use of backquote:

     (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))."
       `(let ((,var ,init))
          (while (<= ,var ,final)
            ,@body
            (inc ,var))))

   Both forms of this definition (with backquote and without) suffer
from the defect that FINAL is evaluated on every iteration.  If FINAL
is a constant, this is not a problem.  If it is a more complex form,
say `(long-complex-calculation x)', this can slow down the execution
significantly.  If FINAL has side effects, executing it more than once
is probably incorrect.

   A well-designed macro definition takes steps to avoid this problem by
producing an expansion that evaluates the argument expressions exactly
once unless repeated evaluation is part of the intended purpose of the
macro.  Here is a correct expansion for the `for' macro:

     (let ((i 1)
           (max 3))
       (while (<= i max)
         (setq square (* i i))
         (princ (format "%d      %d" i square))
         (inc i)))

   Here is a macro definition that creates this expansion:

     (defmacro for (var from init to final do &rest body)
       "Execute a simple for loop: (for i from 1 to 10 do (print i))."
       `(let ((,var ,init)
              (max ,final))
          (while (<= ,var max)
            ,@body
            (inc ,var))))

   Unfortunately, this introduces another problem.  Proceed to the
following node.


File: lispref.info,  Node: Surprising Local Vars,  Next: Eval During Expansion,  Prev: Argument Evaluation,  Up: Problems with Macros

18.6.2 Local Variables in Macro Expansions
------------------------------------------

In the previous section, the definition of `for' was fixed as follows
to make the expansion evaluate the macro arguments the proper number of
times:

     (defmacro for (var from init to final do &rest body)
       "Execute a simple for loop: (for i from 1 to 10 do (print i))."
       `(let ((,var ,init)
              (max ,final))
          (while (<= ,var max)
            ,@body
            (inc ,var))))

The new definition of `for' has a new problem: it introduces a local
variable named `max' which the user does not expect.  This causes
trouble in examples such as the following:

     (let ((max 0))
       (for x from 0 to 10 do
         (let ((this (frob x)))
           (if (< max this)
               (setq max this)))))

The references to `max' inside the body of the `for', which are
supposed to refer to the user's binding of `max', really access the
binding made by `for'.

   The way to correct this is to use an uninterned symbol instead of
`max' (*note Creating Symbols::).  The uninterned symbol can be bound
and referred to just like any other symbol, but since it is created by
`for', we know that it cannot already appear in the user's program.
Since it is not interned, there is no way the user can put it into the
program later.  It will never appear anywhere except where put by
`for'.  Here is a definition of `for' that works this way:

     (defmacro for (var from init to final do &rest body)
       "Execute a simple for loop: (for i from 1 to 10 do (print i))."
       (let ((tempvar (make-symbol "max")))
         `(let ((,var ,init)
                (,tempvar ,final))
            (while (<= ,var ,tempvar)
              ,@body
              (inc ,var)))))

This creates an uninterned symbol named `max' and puts it in the
expansion instead of the usual interned symbol `max' that appears in
expressions ordinarily.


File: lispref.info,  Node: Eval During Expansion,  Next: Repeated Expansion,  Prev: Surprising Local Vars,  Up: Problems with Macros

18.6.3 Evaluating Macro Arguments in Expansion
----------------------------------------------

Another problem can happen if you evaluate any of the macro argument
expressions during the computation of the expansion, such as by calling
`eval' (*note Eval::).  If the argument is supposed to refer to the
user's variables, you may have trouble if the user happens to use a
variable with the same name as one of the macro arguments.  Inside the
macro body, the macro argument binding is the most local binding of this
variable, so any references inside the form being evaluated do refer to
it.  Here is an example:

     (defmacro foo (a)
       (list 'setq (eval a) t))
          => foo
     (setq x 'b)
     (foo x) ==> (setq b t)
          => t                  ; and `b' has been set.
     ;; but
     (setq a 'c)
     (foo a) ==> (setq a t)
          => t                  ; but this set `a', not `c'.

   It makes a difference whether the user's variable is named `a' or
`x', because `a' conflicts with the macro argument variable `a'.

   Another reason not to call `eval' in a macro definition is that it
probably won't do what you intend in a compiled program.  The
byte-compiler runs macro definitions while compiling the program, when
the program's own computations (which you might have wished to access
with `eval') don't occur and its local variable bindings don't exist.

   The safe way to work with the run-time value of an expression is to
put the expression into the macro expansion, so that its value is
computed as part of executing the expansion.


File: lispref.info,  Node: Repeated Expansion,  Prev: Eval During Expansion,  Up: Problems with Macros

18.6.4 How Many Times is the Macro Expanded?
--------------------------------------------

Occasionally problems result from the fact that a macro call is
expanded each time it is evaluated in an interpreted function, but is
expanded only once (during compilation) for a compiled function.  If the
macro definition has side effects, they will work differently depending
on how many times the macro is expanded.

   In particular, constructing objects is a kind of side effect.  If the
macro is called once, then the objects are constructed only once.  In
other words, the same structure of objects is used each time the macro
call is executed.  In interpreted operation, the macro is reexpanded
each time, producing a fresh collection of objects each time.  Usually
this does not matter--the objects have the same contents whether they
are shared or not.  But if the surrounding program does side effects on
the objects, it makes a difference whether they are shared.  Here is an
example:

     (defmacro empty-object ()
       (list 'quote (cons nil nil)))

     (defun initialize (condition)
       (let ((object (empty-object)))
         (if condition
             (setcar object condition))
         object))

If `initialize' is interpreted, a new list `(nil)' is constructed each
time `initialize' is called.  Thus, no side effect survives between
calls.  If `initialize' is compiled, then the macro `empty-object' is
expanded during compilation, producing a single "constant" `(nil)' that
is reused and altered each time `initialize' is called.

   One way to avoid pathological cases like this is to think of
`empty-object' as a funny kind of constant, not as a memory allocation
construct.  You wouldn't use `setcar' on a constant such as `'(nil)',
so naturally you won't use it on `(empty-object)' either.


File: lispref.info,  Node: Customization,  Next: Loading,  Prev: Macros,  Up: Top

19 Writing Customization Definitions
************************************

This chapter describes how to declare user options for customization,
and also customization groups for classifying them.  We use the term
"customization item" to include both kinds of customization
definitions--as well as face definitions.

* Menu:

* Common Keywords::
* Group Definitions::
* Variable Definitions::
* Face Definitions::
* Customization Types::
* Enabling Behavior::


File: lispref.info,  Node: Common Keywords,  Next: Group Definitions,  Prev: Customization,  Up: Customization

19.1 Common Keywords for All Kinds of Items
===========================================

All kinds of customization declarations (for variables and groups, and
for faces) accept keyword arguments for specifying various information.
This section describes some keywords that apply to all kinds.

   All of these keywords, except `:tag', can be used more than once in
a given item.  Each use of the keyword has an independent effect.  The
keyword `:tag' is an exception because any given item can only display
one name.

`:tag NAME'
     Use NAME, a string, instead of the item's name, to label the item
     in customization menus and buffers.

`:group GROUP'
     Put this customization item in group GROUP.  When you use `:group'
     in a `defgroup', it makes the new group a subgroup of GROUP.

     If you use this keyword more than once, you can put a single item
     into more than one group.  Displaying any of those groups will
     show this item.  Be careful not to overdo this!

`:link LINK-DATA'
     Include an external link after the documentation string for this
     item.  This is a sentence containing an active field which
     references some other documentation.

     There are three alternatives you can use for LINK-DATA:

    `(custom-manual INFO-NODE)'
          Link to an Info node; INFO-NODE is a string which specifies
          the node name, as in `"(emacs)Top"'.  The link appears as
          `[manual]' in the customization buffer.

    `(info-link INFO-NODE)'
          Like `custom-manual' except that the link appears in the
          customization buffer with the Info node name.

    `(url-link URL)'
          Link to a web page; URL is a string which specifies the URL.
          The link appears in the customization buffer as URL.

     You can specify the text to use in the customization buffer by
     adding `:tag NAME' after the first element of the LINK-DATA; for
     example, `(info-link :tag "foo" "(emacs)Top")' makes a link to the
     Emacs manual which appears in the buffer as `foo'.

     An item can have more than one external link; however, most items
     have none at all.

`:load FILE'
     Load file FILE (a string) before displaying this customization
     item.  Loading is done with `load-library', and only if the file is
     not already loaded.

`:require FEATURE'
     Require feature FEATURE (a symbol) when installing a value for
     this item (an option or a face) that was saved using the
     customization feature.  This is done by calling `require'.

     The most common reason to use `:require' is when a variable enables
     a feature such as a minor mode, and just setting the variable
     won't have any effect unless the code which implements the mode is
     loaded.


File: lispref.info,  Node: Group Definitions,  Next: Variable Definitions,  Prev: Common Keywords,  Up: Customization

19.2 Defining Custom Groups
===========================

Each Emacs Lisp package should have one main customization group which
contains all the options, faces and other groups in the package.  If the
package has a small number of options and faces, use just one group and
put everything in it.  When there are more than twelve or so options and
faces, then you should structure them into subgroups, and put the
subgroups under the package's main customization group.  It is OK to
put some of the options and faces in the package's main group alongside
the subgroups.

   The package's main or only group should be a member of one or more of
the standard customization groups.  (To display the full list of them,
use `M-x customize'.)  Choose one or more of them (but not too many),
and add your group to each of them using the `:group' keyword.

   The way to declare new customization groups is with `defgroup'.

 -- Macro: defgroup group members doc [keyword value]...
     Declare GROUP as a customization group containing MEMBERS.  Do not
     quote the symbol GROUP.  The argument DOC specifies the
     documentation string for the group.

     The argument MEMBERS is a list specifying an initial set of
     customization items to be members of the group.  However, most
     often MEMBERS is `nil', and you specify the group's members by
     using the `:group' keyword when defining those members.

     If you want to specify group members through MEMBERS, each element
     should have the form `(NAME WIDGET)'.  Here NAME is a symbol, and
     WIDGET is a widget type for editing that symbol.  Useful widgets
     are `custom-variable' for a variable, `custom-face' for a face,
     and `custom-group' for a group.

     In addition to the common keywords (*note Common Keywords::), you
     can use this keyword in `defgroup':

    `:prefix PREFIX'
          If the name of an item in the group starts with PREFIX, then
          the tag for that item is constructed (by default) by omitting
          PREFIX.

          One group can have any number of prefixes.


File: lispref.info,  Node: Variable Definitions,  Next: Face Definitions,  Prev: Group Definitions,  Up: Customization

19.3 Defining Customization Variables
=====================================

Use `defcustom' to declare user-editable variables.  For face
declarations, use `defface' instead.  *Note Face Definitions::.

 -- Macro: defcustom option default doc [keyword value]...
     Declare OPTION as a customizable user option variable.  Do not
     quote OPTION.  The argument DOC specifies the documentation string
     for the variable.

     If OPTION is void, `defcustom' initializes it to DEFAULT.  DEFAULT
     should be an expression to compute the value; be careful in
     writing it, because it can be evaluated on more than one occasion.

     The following additional keywords are defined:

    `:type TYPE'
          Use TYPE as the data type for this option.  It specifies which
          values are legitimate, and how to display the value.  *Note
          Customization Types::, for more information.

    `:options LIST'
          Specify LIST as the list of reasonable values for use in this
          option.

          Currently this is meaningful only when the type is `hook'.
          In that case, the elements of LIST should be functions that
          are useful as elements of the hook value.  The user is not
          restricted to using only these functions, but they are
          offered as convenient alternatives.

    `:version VERSION'
          This option specifies that the variable was first introduced,
          or its default value was changed, in Emacs version VERSION.
          The value VERSION must be a string.  For example,

               (defcustom foo-max 34
                 "*Maximum number of foo's allowed."
                 :type 'integer
                 :group 'foo
                 :version "20.3")

    `:set SETFUNCTION'
          Specify SETFUNCTION as the way to change the value of this
          option.  The function SETFUNCTION should take two arguments,
          a symbol and the new value, and should do whatever is
          necessary to update the value properly for this option (which
          may not mean simply setting the option as a Lisp variable).
          The default for SETFUNCTION is `set-default'.

    `:get GETFUNCTION'
          Specify GETFUNCTION as the way to extract the value of this
          option.  The function GETFUNCTION should take one argument, a
          symbol, and should return the "current value" for that symbol
          (which need not be the symbol's Lisp value).  The default is
          `default-value'.

    `:initialize FUNCTION'
          FUNCTION should be a function used to initialize the variable
          when the `defcustom' is evaluated.  It should take two
          arguments, the symbol and value.  Here are some predefined
          functions meant for use in this way:

         `custom-initialize-set'
               Use the variable's `:set' function to initialize the
               variable, but do not reinitialize it if it is already
               non-void.  This is the default `:initialize' function.

         `custom-initialize-default'
               Like `custom-initialize-set', but use the function
               `set-default' to set the variable, instead of the
               variable's `:set' function.  This is the usual choice
               for a variable whose `:set' function enables or disables
               a minor mode; with this choice, defining the variable
               will not call the minor mode function, but customizing
               the variable will do so.

         `custom-initialize-reset'
               Always use the `:set' function to initialize the
               variable.  If the variable is already non-void, reset it
               by calling the `:set' function using the current value
               (returned by the `:get' method).

         `custom-initialize-changed'
               Use the `:set' function to initialize the variable, if
               it is already set or has been customized; otherwise,
               just use `set-default'.

   The `:require' option is useful for an option that turns on the
operation of a certain feature.  Assuming that the package is coded to
check the value of the option, you still need to arrange for the package
to be loaded.  You can do that with `:require'.  *Note Common
Keywords::.  Here is an example, from the library `paren.el':

     (defcustom show-paren-mode nil
       "Toggle Show Paren mode...."
       :set (lambda (symbol value)
              (show-paren-mode (or value 0)))
       :initialize 'custom-initialize-default
       :type 'boolean
       :group 'paren-showing
       :require 'paren)

   Internally, `defcustom' uses the symbol property `standard-value' to
record the expression for the default value, and `saved-value' to
record the value saved by the user with the customization buffer.  The
`saved-value' property is actually a list whose car is an expression
which evaluates to the value.


File: lispref.info,  Node: Face Definitions,  Next: Customization Types,  Prev: Variable Definitions,  Up: Customization

19.4 Face Definitions
=====================

Use `defface' to declare a new face.  Conventions used in specifying
properties are similar to those for general customizable variables.
*Note Variable Definitions::.

 -- Function: defface face spec doc &rest args
     Declare FACE as a customizable face that defaults to SPEC.  FACE
     does not need to be quoted.

     Third argument DOC is the face documentation.

     If FACE has been set with `custom-set-face', set the face
     attributes as specified by that function, otherwise set the face
     attributes according to SPEC.

     The remaining arguments ARGS are a property list, which has the
     form

     KEYWORD VALUE...

     The following KEYWORDs are defined:

    `:group'
          VALUE is a customization group.  Add FACE to that group.

     SPEC is an alist of the form ((DISPLAY ATTS)...).

     ATTS is a list of face attributes and their values.  The possible
     attributes are defined in the variable `custom-face-attributes'.

     The ATTS of the first entry in SPEC where the DISPLAY matches the
     frame take effect in that frame.  DISPLAY can either be the symbol
     t, which will match all frames, or an alist of the form \((REQ
     ITEM...)...)

     For DISPLAY to match a frame, the REQ property of the frame must
     match one of the ITEM.  The following REQ are defined:

    ``type' (the value of `window-system')'
          Should be one of `x', `mswindows', or `tty'.

          `class' (the frame's color support)   Should be one of
          `color', `grayscale', or `mono'.

          `min-colors' (the minimum number of colors the frame supports)
           Should be in integer which is compared to
          `display-color-cells'

          `background' (what color is used for the background text)
          Should be one of `light' or `dark'.


File: lispref.info,  Node: Customization Types,  Next: Enabling Behavior,  Prev: Face Definitions,  Up: Customization

19.5 Customization Types
========================

When you define a user option with `defcustom', you must specify its
"customization type".  That is a Lisp object which describes (1) which
values are legitimate and (2) how to display the value in the
customization buffer for editing.

   You specify the customization type in `defcustom' with the `:type'
keyword.  The argument of `:type' is evaluated; since types that vary
at run time are rarely useful, normally you use a quoted constant.  For
example:

     (defcustom diff-command "diff"
       "*The command to use to run diff."
       :type '(string)
       :group 'diff)

   In general, a customization type is a list whose first element is a
symbol, one of the customization type names defined in the following
sections.  After this symbol come a number of arguments, depending on
the symbol.  Between the type symbol and its arguments, you can
optionally write keyword-value pairs (*note Type Keywords::).

   Some of the type symbols do not use any arguments; those are called
"simple types".  For a simple type, if you do not use any keyword-value
pairs, you can omit the parentheses around the type symbol.  For
example just `string' as a customization type is equivalent to
`(string)'.

* Menu:

* Simple Types::
* Composite Types::
* Splicing into Lists::
* Type Keywords::
* Defining New Types::


File: lispref.info,  Node: Simple Types,  Next: Composite Types,  Prev: Customization Types,  Up: Customization Types

19.5.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, 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-<TAB>'.

`(file :must-match t)'
     The value must be a file name for an existing file, and you can do
     completion with `M-<TAB>'.

`directory'
     The value must be a directory name, and you can do completion with
     `M-<TAB>'.

`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-<TAB>'.

`variable'
     The value must be a variable name, and you can do completion with
     `M-<TAB>'.

`face'
     The value must be a symbol which is a face name.

`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.


File: lispref.info,  Node: Composite Types,  Next: Splicing into Lists,  Prev: Simple Types,  Up: Customization Types

19.5.2 Composite Types
----------------------

When none of the simple types is appropriate, you can use composite
types, which build new types from other types.  Here are several ways of
doing that:

`(restricted-sexp :match-alternatives CRITERIA)'
     The value may be any Lisp object that satisfies one of CRITERIA.
     CRITERIA should be a list, and each elements should be one of
     these possibilities:

        * A predicate--that is, a function of one argument that returns
          non-`nil' if the argument fits a certain type.  This means
          that objects of that type are acceptable.

        * A quoted constant--that is, `'OBJECT'.  This means 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.

`(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 you have specified; 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, the each element is displayed and
     edited separately, according to the type specified for it.

`(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 one of the
     alternatives 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::.

`(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))

`(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 ELEMENTS...)'
     The value must be a list and each element of the list must be one
     of the ELEMENTS specified.  This appears in the customization
     buffer as a checklist.

`(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.


File: lispref.info,  Node: Splicing into Lists,  Next: Type Keywords,  Prev: Composite Types,  Up: Customization Types

19.5.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 `t' and
whose remaining arguments should be zero or more of `foo' and `bar',
use this customization type:

     (list (const t) (set :inline t foo bar))

This matches values such as `(t)', `(t foo)', `(t bar)' and `(t 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: lispref.info,  Node: Type Keywords,  Next: Defining New Types,  Prev: Splicing into Lists,  Up: Customization Types

19.5.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.

`: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.



File: lispref.info,  Node: Defining New Types,  Prev: Type Keywords,  Up: Customization Types

19.5.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 once, and use that name each `defcustom'.  The other case is when
a user option accept a recursive datastructure.  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 name `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 accept 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 <ret> binary-tree-of-string <ret>' command.

   After these mandatory arguments follows the keyword arguments.  The
most important is `:type', which describes the datatype 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
are there to ensure that child nodes are indented four spaces
relatively 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.


File: lispref.info,  Node: Enabling Behavior,  Prev: Customization Types,  Up: Customization

19.6 Enabling Behavior
======================

Some functionality requires a fair amount of effort to enable globally
in a session.  For example, someone who discovers filladapt and really
likes it must toggle it separately in each buffer.  On the other hand,
after trying it for a while she might like to disable it everywhere,
having decided it doesn't work very well for her.  Such a functionality
is called a "behavior".

   `define-behavior' allows the programmer to register functions to
enable or disable a package globally in a session.  The user sees a
consistent interface through the `enable-behavior' and
`disable-behavior' functions.  These functions were introduced in
XEmacs 21.5.6.

 -- Variable: behavior-hash-table
     Internal table of registered behaviors.

 -- Variable: behavior-history
     History of entered behaviors.

 -- Function: define-behavior name doc-string [cl-keys ...]
     Define a behavior named NAME.

     DOC-STRING must be specified.  It is a description of what the
     behavior does when it's enabled and how to further control it
     (typically through custom variables).  Accepted keywords are

    `:title'
          A "pretty" version of the name, for use in menus.  If omitted
          a prettified name will be generated.

    `:require'
          A single symbol or a list of such symbols, which need to be
          present at enable time, or will be loaded using `require'.

    `:enable'
          A function of no variables, which turns the behavior on.

    `:disable'
          A function of no variables, which turns the behavior off.

     Behaviors are assumed to be global, and to take effect
     immediately; if the underlying package is per-buffer, the enabler
     may have to scan all existing buffers and frob them.  When a
     behavior is disabled, it should completely go away *everywhere*,
     as if it were never invoked at all.

     The `:disable' keyword can be missing.  This is bad practice.  In
     such a case, attempting to disable the behavior will signal an
     error unless you use the `force' option.

 -- Function: read-behavior prompt [require-match [initial-contents
          [history [default]]]]
     Return a behavior symbol from the minibuffer, prompting with string
     PROMPT.

     The optional arguments REQUIRE-MATCH, INITIAL-CONTENTS, HISTORY,
     and DEFAULT are passed to `completing-read', and have semantics
     derived from that function.  *Note Minibuffer Completion::.  The
     default value of HISTORY is `behavior-history'.

 -- Function: behavior-enabled-p name
     Return non-nil if the behavior registered under NAME is enabled.

     Unimplemented in 21.5.6.

 -- Function: enable-behavior behavior [force]
     Enable the behavior registered under the symbol BEHAVIOR.

     The optional argument FORCE is unimplemented in 21.5.6.

     Called interactively, prompt the user for BEHAVIOR, and take FORCE
     from the prefix argument.

 -- Function: disable-behavior (behavior &optional force)
     Disable the behavior registered under the symbol BEHAVIOR.

     The optional argument FORCE is unimplemented in 21.5.6.

     Called interactively, prompt the user for BEHAVIOR, and take FORCE
     from the prefix argument.


File: lispref.info,  Node: Loading,  Next: Byte Compilation,  Prev: Customization,  Up: Top

20 Loading
**********

Loading a file of Lisp code means bringing its contents into the Lisp
environment in the form of Lisp objects.  XEmacs 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-current-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.
* 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.
* Unloading::			How to ``unload'' a library that was loaded.
* Hooks for Loading::		Providing code to be run when
				  particular libraries are loaded.


File: lispref.info,  Node: How Programs Do Loading,  Next: Autoload,  Prev: Loading,  Up: Loading

20.1 How Programs Do Loading
============================

XEmacs Lisp has several interfaces for loading.  For example,
`autoload' creates a placeholder object for a function 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
     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
     `.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 the optional argument NOSUFFIX is non-`nil', then the suffixes
     `.elc' and `.el' are not tried.  In this case, you must specify
     the precise file name you want.

     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.

     If you get a warning that `foo.elc' is older than `foo.el', it
     means you should consider recompiling `foo.el'.  *Note Byte
     Compilation::.

     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.

 -- 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/paths.h' when XEmacs is
     built.

     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/lib/emacs/lisp

     Here is how to set it using `sh':

          export EMACSLOADPATH
          EMACSLOADPATH=.:/user/bil/emacs:/usr/local/lib/emacs/lisp

     Here is an example of code you can place in a `.emacs' 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.

     The command line options `-l' or `-load' specify a Lisp library to
     load as part of Emacs startup.  Since this file might be in the
     current directory, Emacs 18 temporarily adds the current directory
     to the front of `load-path' so the file can be found there.  Newer
     Emacs versions also find such files in the current directory, but
     without altering `load-path'.

     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'.

 -- Function: locate-file filename path-list &optional suffixes mode
     This function searches for a file in the same way that `load' does,
     and returns the file found (if any). (In fact, `load' uses this
     function to search through `load-path'.) It searches for FILENAME
     through PATH-LIST, expanded by one of the optional SUFFIXES
     (string of suffixes separated by `:'s), checking for access MODE
     (0|1|2|4 = exists|executable|writable|readable), default readable.

     `locate-file' keeps hash tables of the directories it searches
     through, in order to speed things up.  It tries valiantly to not
     get confused in the face of a changing and unpredictable
     environment, but can occasionally get tripped up.  In this case,
     you will have to call `locate-file-clear-hashing' to get it back
     on track.  See that function for details.

 -- Function: locate-file-clear-hashing path
     This function clears the hash records for the specified list of
     directories.  `locate-file' uses a hashing scheme to speed lookup,
     and will correctly track the following environmental changes:

        * changes of any sort to the list of directories to be searched.

        * addition and deletion of non-shadowing files (see below) from
          the directories in the list.

        * byte-compilation of a .el file into a .elc file.

     `locate-file' will primarily get confused if you add a file that
     shadows (i.e. has the same name as) another file further down in
     the directory list.  In this case, you must call
     `locate-file-clear-hashing'.

 -- 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'.

 -- User Option: load-warn-when-source-newer
     This variable specifies whether `load' should check whether the
     source is newer than the binary.  If this variable is true, then
     when a `.elc' file is being loaded and the corresponding `.el' is
     newer, a warning message will be printed.  The default is `nil',
     but it is bound to `t' during the initial loadup.

 -- User Option: load-warn-when-source-only
     This variable specifies whether `load' should warn when loading a
     `.el' file instead of an `.elc'.  If this variable is true, then
     when `load' is called with a filename without an extension, and
     the `.elc' version doesn't exist but the `.el' version does, then
     a message will be printed.  If an explicit extension is passed to
     `load', no warning will be printed.  The default is `nil', but it
     is bound to `t' during the initial loadup.

 -- User Option: load-ignore-elc-files
     This variable specifies whether `load' should ignore `.elc' files
     when a suffix is not given.  This is normally used only to
     bootstrap the `.elc' files when building XEmacs, when you use the
     command `make all-elc'. (This forces the `.el' versions to be
     loaded in the process of compiling those same files, so that
     existing out-of-date `.elc' files do not make it mess things up.)

   To learn how `load' is used to build XEmacs, see *Note Building
XEmacs::.


File: lispref.info,  Node: Autoload,  Next: Repeated Loading,  Prev: How Programs Do Loading,  Up: Loading

20.2 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 do nothing on their own; 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.  Magic comments are the
most convenient way to make a function autoload, but only for packages
installed along with Emacs.

 -- 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.

     The argument DOCSTRING is the documentation string for the
     function.  Normally, this is identical to the documentation string
     in the function definition itself.  Specifying the documentation
     string in the call to `autoload' makes it possible to look at the
     documentation without loading the function's real definition.

     If INTERACTIVE is non-`nil', then the function can be called
     interactively.  This lets completion in `M-x' work without loading
     the function's real definition.  The complete interactive
     specification need not be 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 `DOC' 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 appear defined, but
they might fail to work properly for the lack of certain subroutines
defined later in the file and not loaded successfully.

   XEmacs as distributed comes with many autoloaded functions.  The
calls to `autoload' are in the file `loaddefs.el'.  There is a
convenient way of updating them automatically.

   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 looks like `;;;###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'.  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 definition,
it is copied verbatim.  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 `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 'doctor "doctor"
       "\
     Switch to *doctor* buffer and start giving psychotherapy."
       t)

The backslash and newline immediately following the double-quote are a
convention used only in the preloaded Lisp files such as `loaddefs.el';
they tell `make-docfile' to put the documentation string in the `DOC'
file.  *Note Building XEmacs::.


File: lispref.info,  Node: Repeated Loading,  Next: Named Features,  Prev: Autoload,  Up: Loading

20.3 Repeated Loading
=====================

You may load one 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, remember to byte-compile it if
necessary; otherwise you may find yourself inadvertently reloading the
older, byte-compiled file instead of your newer, non-compiled file!

   When writing the forms in a Lisp library file, keep in mind that the
file might be loaded more than once.  For example, the choice of
`defvar' vs. `defconst' for defining a variable depends on whether it
is desirable to reinitialize the variable if the library is reloaded:
`defconst' does so, and `defvar' does not.  (*Note Defining
Variables::.)

   The simplest way to add an element to an alist is like this:

     (setq minor-mode-alist
           (cons '(leif-mode " Leif") minor-mode-alist))

But this would add multiple elements if the library is reloaded.  To
avoid the problem, write this:

     (or (assq 'leif-mode minor-mode-alist)
         (setq minor-mode-alist
               (cons '(leif-mode " Leif") minor-mode-alist)))

   To add an element to a list just once, use `add-to-list' (*note
Setting Variables::).

   Occasionally you will want to test explicitly whether a library has
already been loaded.  Here's one way to test, in a library, whether it
has been loaded before:

     (defvar foo-was-loaded)

     (if (not (boundp 'foo-was-loaded))
         EXECUTE-FIRST-TIME-ONLY)

     (setq foo-was-loaded t)

If the library uses `provide' to provide a named feature, you can use
`featurep' to test whether the library has been loaded.  *Note Named
Features::.


File: lispref.info,  Node: Named Features,  Next: Unloading,  Prev: Repeated Loading,  Up: Loading

20.4 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.  

   Features are normally named after the files that provide them, so
that `require' need not be given the file name.

   For example, in `emacs/lisp/prolog.el', the definition for
`run-prolog' includes the following code:

     (defun run-prolog ()
       "Run an inferior Prolog process, input and output 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.

   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.

   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 while
loading.

 -- Function: provide feature
     This function announces that FEATURE is now loaded, or being
     loaded, into the current XEmacs 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 to add FEATURE to the
     front of the list `features' if it is not already in the list.
     The argument FEATURE must be a symbol.  `provide' returns FEATURE.

          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 evaluating its contents, any function definitions
     or `provide' calls that occurred during the load are undone.
     *Note Autoload::.

 -- Function: require feature &optional filename
     This function checks whether FEATURE is present in the current
     XEmacs session (using `(featurep FEATURE)'; see below).  If it is
     not, then `require' loads FILENAME with `load'.  If FILENAME is
     not supplied, then the name of the symbol FEATURE is used as the
     file name to load.

     If loading the file fails to provide FEATURE, `require' signals an
     error, `Required feature FEATURE was not provided'.

     Top level calls to `require' are handled specially by the compiler;
     they are evaluated at compile time and also compiled in the normal
     way, see above.  This allows compile-time expansion of any macros
     and correct compile-time inlining of any inline functions (*note
     Inline Functions::).

     Should this create a problem (for example, with a feature
     available as a module that is not necessarily available at compile
     time, with no macros and no inline functions), a portable
     work-around is to call `require' in a way that avoids the top
     level form handling:

          (funcall 'require 'FEATURE)

     This will compile to the normal code and will avoid compile-time
     evaluation. A more clear equivalent that works in GNU Emacs and
     XEmacs (with the exception of beta XEmacs builds from 2018 to
     early 2021) is the following:

          (eval-when-compile (require 'cl))

          (eval-when (:load-toplevel :execute)
            (require 'FEATURE))

 -- Function: featurep fexp
     This function returns `t' if feature FEXP is present in this
     Emacs.  Use this to conditionalize execution of lisp code based on
     the presence or absence of emacs or environment extensions.

     FEXP can be a symbol, a number, or a list.

     If FEXP is a symbol, it is looked up in the `features' variable,
     and `t' is returned if it is found, `nil' otherwise.

     If FEXP is a number, the function returns `t' if this Emacs has an
     equal or greater number than FEXP, `nil' otherwise.  Note that
     minor Emacs version is expected to be 2 decimal places wide, so
     `(featurep 20.4)' will return `nil' on XEmacs 20.4--you must write
     `(featurep 20.04)', unless you wish to match for XEmacs 20.40.

     If FEXP is a list whose car is the symbol `and', the function
     returns `t' if all the features in its cdr are present, `nil'
     otherwise.

     If FEXP is a list whose car is the symbol `or', the function
     returns `t' if any the features in its cdr are present, `nil'
     otherwise.

     If FEXP is a list whose car is the symbol `not', the function
     returns `t' if the feature is not present, `nil' otherwise.

     Examples:

          (featurep 'xemacs)
               => ; t on XEmacs.

          (featurep '(and xemacs gnus))
               => ; t on XEmacs with Gnus loaded.

          (featurep '(or tty-frames (and emacs 19.30)))
               => ; t if this Emacs supports TTY frames.

          (featurep '(or (and xemacs 19.15) (and emacs 19.34)))
               => ; t on XEmacs 19.15 and later, or on
                         ; FSF Emacs 19.34 and later.

     *Please note:* The advanced arguments of this function (anything
     other than a symbol) are not yet supported by FSF Emacs.  If you
     feel they are useful for supporting multiple Emacs variants, lobby
     Richard Stallman at `<bug-gnu-emacs@prep.ai.mit.edu>'.

 -- Variable: features
     The value of this variable is a list of symbols that are the
     features loaded in the current XEmacs 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: lispref.info,  Node: Unloading,  Next: Hooks for Loading,  Prev: Named Features,  Up: Loading

20.5 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 `defconst', `defvar', `defun', `defmacro',
     `defsubst', `define-function' and `defalias'.  It then restores
     any autoloads formerly associated with those symbols.  (Loading
     saves these in the `autoload' property of the symbol.)

     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: load-history
     This variable's value is an alist connecting library names with the
     names of functions and variables they define, the features they
     provide, and the features they require.

     Each element is a list and describes one library.  The CAR of the
     list is the name of the library, as a string.  The rest of the
     list is composed of these kinds of objects:

        * Symbols that were defined by this library.

        * Lists of the form `(require . FEATURE)' indicating features
          that were required.

        * Lists of the form `(provide . FEATURE)' indicating features
          that were 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.


File: lispref.info,  Node: Hooks for Loading,  Prev: Unloading,  Up: Loading

20.6 Hooks for Loading
======================

 -- Variable: after-load-alist
     An alist of expressions to evaluate if and when particular
     libraries are loaded.  Each element looks like this:

          (FILENAME FORMS...)

     When `load' is run and the file-name argument is FILENAME, the
     FORMS in the corresponding element are executed at the end of
     loading.

     FILENAME must match exactly!  Normally FILENAME is the name of a
     library, with no directory specified, since that is how `load' is
     normally called.  An error in FORMS does not undo the load, but
     does prevent execution of the rest of the FORMS.



File: lispref.info,  Node: Byte Compilation,  Next: Debugging,  Prev: Loading,  Up: Top

21 Byte Compilation
*******************

XEmacs 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-coded 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.

   In general, any version of Emacs can run byte-compiled code produced
by recent earlier versions of Emacs, but the reverse is not true.  In
particular, if you compile a program with XEmacs 20, the compiled code
may not run in earlier versions.

   The first time a compiled-function object is executed, the byte-code
instructions are validated and the byte-code is further optimized.  An
`invalid-byte-code' error is signaled if the byte-code is invalid, for
example if it contains invalid opcodes.  This usually means a bug in
the byte compiler.

   *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.
* Compilation Options::         Controlling the byte compiler's behavior.
* 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.
* Compiled-Function Objects::	The data type used for byte-compiled functions.
* Disassembly::                 Disassembling byte-code; how to read byte-code.
* Different Behavior::          When compiled code gives different results.


File: lispref.info,  Node: Speed of Byte-Code,  Next: Compilation Functions,  Prev: Byte Compilation,  Up: Byte Compilation

21.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 5000000)
     => ("Mon Sep 14 15:51:49 1998"
         "Mon Sep 14 15:52:07 1998")  ; 18 seconds

     (byte-compile 'silly-loop)
     => #<compiled-function
     (n)
     "...(23)"
     [current-time-string t1 n 0]
     2
     "Return time before and after N iterations of a loop.">

     (silly-loop 5000000)
     => ("Mon Sep 14 15:53:43 1998"
         "Mon Sep 14 15:53:49 1998")  ; 6 seconds

   In this example, the interpreted code required 18 seconds to run,
whereas the byte-compiled code required 6 seconds.  These results are
representative, but actual results will vary greatly.


File: lispref.info,  Node: Compilation Functions,  Next: Compilation Options,  Prev: Speed of Byte-Code,  Up: Byte Compilation

21.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'.

   When you run the byte compiler, you may get warnings in a buffer
called `*Compile-Log*'.  These report things in your program that
suggest a problem but are not necessarily erroneous.

   Be careful when byte-compiling code that uses macros.  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::.

   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 compiled-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)
          => #<compiled-function
          (integer)
          "...(21)"
          [integer 1 factorial]
          3
          "Compute factorial of INTEGER.">

     The result is a compiled-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.

 -- 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.

     If ARG is non-`nil', the result is inserted in the current buffer
     after the form; otherwise, it is printed in the minibuffer.

 -- 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 appending
     `c' to the end of FILENAME.

     If `load' is non-`nil', the file is loaded after having been
     compiled.

     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'.  When called interactively, it prompts
     for the file name.

          % 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-r--r--  1 lewis     638 Oct  8 20:25 push.elc

 -- Command: byte-recompile-directory directory &optional flag
          norecursion force
     This function recompiles every `.el' file in DIRECTORY that needs
     recompilation.  A file needs recompilation if a `.elc' file exists
     but is older than the `.el' file.

     Files in subdirectories of DIRECTORY are also processed unless
     optional argument NORECURSION is non-`nil'.

     When a `.el' file has no corresponding `.elc' file, then FLAG says
     what to do.  If it is `nil', these files are ignored.  If it is
     non-`nil', the user is asked whether to compile each such file.

     If the fourth optional argument FORCE is non-`nil', recompile
     every `.el' file that already has a `.elc' file.

     The return value of this command is unpredictable.

 -- Function: batch-byte-compile
     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.  (The
     file that gets the error will not, of course, produce any compiled
     code.)

          % xemacs -batch -f batch-byte-compile *.el

 -- Function: batch-byte-recompile-directory
     This function is similar to `batch-byte-compile' but runs the
     command `byte-recompile-directory' on the files remaining on the
     command line.

 -- Variable: byte-recompile-directory-ignore-errors-p
     When non-`nil', `byte-recompile-directory' will continue compiling
     even when an error occurs in a file.  Default: `nil', but bound to
     `t' by `batch-byte-recompile-directory'.

 -- Variable: byte-recompile-directory-recursively
     When non-`nil', `byte-recompile-directory' will recurse on
     subdirectories.  Default: `t'.

 -- Function: byte-code instructions constants stack-depth
     This function actually interprets byte-code.  Don't call this
     function yourself.  Only the byte compiler knows how to generate
     valid calls to this function.

     In newer Emacs versions (19 and up), byte code is usually executed
     as part of a compiled-function object, and only rarely due to an
     explicit call to `byte-code'.  A byte-compiled function was once
     actually defined with a body that calls `byte-code', but in recent
     versions of Emacs `byte-code' is only used to run isolated
     fragments of lisp code without an associated argument list.


File: lispref.info,  Node: Compilation Options,  Next: Docs and Compilation,  Prev: Compilation Functions,  Up: Byte Compilation

21.3 Options for the Byte Compiler
==================================

Warning: this node is a quick draft based on docstrings.  There may be
inaccuracies, as the docstrings occasionally disagree with each other.
This has not been checked yet.

   The byte compiler and optimizer are controlled by the following
variables.  The `byte-compiler-options' macro described below provides
a convenient way to set most of them on a file-by-file basis.

 -- Variable: emacs-lisp-file-regexp
     Regexp which matches Emacs Lisp source files.  You may want to
     redefine `byte-compile-dest-file' if you change this.  Default:
     `"\\.el$"'.

 -- Function: byte-compile-dest-file filename
     Convert an Emacs Lisp source file name to a compiled file name.
     This function may be redefined by the user, if necessary, for
     compatibility with `emacs-lisp-file-regexp'.

 -- Variable: byte-compile-verbose
     When non-`nil', print messages describing progress of
     byte-compiler.  Default: `t' if interactive on a not-too-slow
     terminal (see `search-slow-speed'), otherwise `nil'.

 -- Variable: byte-optimize
     Level of optimization in the byte compiler.

    `nil'
          Do no optimization.

    `t'
          Do all optimizations.

    `source'
          Do optimizations manipulating the source code only.

    `byte'
          Do optimizations manipulating the byte code (actually, LAP
          code) only.
     Default: `t'.

 -- Variable: byte-compile-delete-errors
     When non-`nil', the optimizer may delete forms that may signal an
     error if that is the only change in the function's behavior.  This
     includes variable references and calls to functions such as `car'.
     Default: `t'.

 -- Variable: byte-optimize-log nil
     When non-`nil', the byte-compiler logs optimizations into
     `*Compile-Log*'.

    `nil'
          Log no optimization.

    `t'
          Log all optimizations.

    `source'
          Log optimizations manipulating the source code only.

    `byte'
          Log optimizations manipulating the byte code (actually, LAP
          code) only.
     Default: `nil'.

 -- Variable: byte-compile-error-on-warn
     When non-`nil', the byte-compiler reports warnings with `error'.
     Default:  `nil'.

 -- Variable: byte-compile-default-warnings
     The warnings used when `byte-compile-warnings' is `t'.  Called
     `byte-compile-warning-types' in GNU Emacs.  Default: `(redefine
     callargs subr-callargs free-vars unresolved unused-vars obsolete)'.

 -- Variable: byte-compile-warnings
     List of warnings that the compiler should issue (`t' for the
     default set).  Elements of the list may be:

    `free-vars'
          References to variables not in the current lexical scope.

    `unused-vars'
          References to non-global variables bound but not referenced.

    `unresolved'
          Calls to unknown functions.

    `callargs'
          Lambda calls with args that don't match the definition.

    `subr-callargs'
          Calls to subrs with args that don't match the definition.

    `redefine'
          Function cell redefined from a macro to a lambda or vice
          versa, or redefined to take a different number of arguments.

    `obsolete'
          Use of an obsolete function or variable.

    `pedantic'
          Warn of use of compatible symbols.

     The default set is specified by `byte-compile-default-warnings' and
     normally encompasses all possible warnings.

     See also the macro `byte-compiler-options'.  Default: `t'.

   The compiler can generate a call graph, which gives information about
which functions call which functions.

 -- Variable: byte-compile-generate-call-tree
     When non-`nil', the compiler generates a call graph.  This records
     functions that were called and from where.  If the value is `t',
     compilation displays the call graph when it finishes.  If the
     value is neither `t' nor `nil', compilation asks you whether to
     display the graph.

     The call tree only lists functions called, not macros used. Those
     functions which the byte-code interpreter knows about directly
     (`eq', `cons', etc.) are not reported.

     The call tree also lists those functions which are not known to be
     called (that is, to which no calls have been compiled).  Functions
     which can be invoked interactively are excluded from this list.
     Default: `nil'.

 -- Variable: byte-compile-call-tree nil
     Alist of functions and their call tree, used internally.  Each
     element takes the form

     (FUNCTION CALLERS CALLS)

     where CALLERS is a list of functions that call FUNCTION, and CALLS
     is a list of functions for which calls were generated while
     compiling FUNCTION.

 -- Variable: byte-compile-call-tree-sort
     When non-`nil', sort the call tree.  The values `name', `callers',
     `calls', and `calls+callers' specify different fields to sort
     on.")  Default: `name'.

   `byte-compile-overwrite-file' controls treatment of existing
compiled files.

 -- Variable: byte-compile-overwrite-file
     When non-`nil', do not preserve backups of `.elc's.  Precisely, if
     `nil', old `.elc' files are deleted before the new one is saved,
     and `.elc' files will have the same modes as the corresponding
     `.el' file.  Otherwise, existing `.elc' files will simply be
     overwritten, and the existing modes will not be changed.  If this
     variable is `nil', then an `.elc' file which is a symbolic link
     will be turned into a normal file, instead of the file which the
     link points to being overwritten.  Default: `t'.

   Variables controlling recompiling directories are described elsewhere
*Note Compilation Functions::.  They are
`byte-recompile-directory-ignore-errors-p' and
`byte-recompile-directory-recursively'.

   The dynamic loading features are described elsewhere.  These are
controlled by the variables `byte-compile-dynamic' (*note Dynamic
Loading::) and `byte-compile-dynamic-docstrings' (*note Docs and
Compilation::).

   The byte compiler is a relatively recent development, and has evolved
significantly over the period covering Emacs versions 19 and 20.  The
following variables control use of newer functionality by the byte
compiler.  These are rarely needed since the release of XEmacs 21.

   Another set of compatibility issues arises between Mule and non-Mule
XEmacsen; there are no known compatibility issues specific to the byte
compiler.  There are also compatibility issues between XEmacs and GNU
Emacs's versions of the byte compiler.  While almost all of the byte
codes are the same, and code compiled by one version often runs
perfectly well on the other, this is very dangerous, and can result in
crashes or data loss.  Always recompile your Lisp when moving between
XEmacs and GNU Emacs.

 -- Variable: byte-compile-single-version nil
     When non-`nil', the choice of emacs version (v19 or v20) byte-codes
     will be hard-coded into bytecomp when it compiles itself.  If the
     compiler itself is compiled with optimization, this causes a
     speedup.  Default: `nil'.

 -- Variable: byte-compile-emacs19-compatibility
     When non-`nil' generate output that can run in Emacs 19.  Default:
     `nil' when Emacs version is 20 or above, otherwise `t'.

 -- Variable: byte-compile-print-gensym
     When non-`nil', the compiler may generate code that creates unique
     symbols at run-time.  This is achieved by printing uninterned
     symbols using the `#:SYMBOL' notation, so that they will be read
     uninterned when run.

     With this feature, code that uses uninterned symbols in macros will
     not be runnable under pre-21.0 XEmacsen.

     Default: When `byte-compile-emacs19-compatibility' is non-nil, this
     variable is ignored and considered to be `nil'.  Otherwise `t'.

 -- Variable: byte-compile-new-bytecodes
     This is completely ignored.  For backwards compatibility.

 -- Function: byte-compiler-options &rest args
     Set some compilation-parameters for this file.  This will affect
     only the file in which it appears; this does nothing when
     evaluated, or when loaded from a `.el' file.

     Each argument to this macro must be a list of a key and a value.
     (#### Need to check whether the newer variables are settable here.)

            Keys:		  Values:		Corresponding variable:

            verbose	  t, nil		byte-compile-verbose
            optimize	  t, nil, source, byte	byte-optimize
            warnings	  list of warnings	byte-compile-warnings
            file-format	  emacs19, emacs20	byte-compile-emacs19-compatibility

     The value specified with the `warnings'option must be a list,
     containing some subset of the following flags:

            free-vars	references to variables not in the current lexical scope.
            unused-vars	references to non-global variables bound but not referenced.
            unresolved	calls to unknown functions.
            callargs	lambda calls with args that don't match the definition.
            redefine	function cell redefined from a macro to a lambda or vice
          		versa, or redefined to take a different number of arguments.

     If the first element if the list is `+' or ``' then the specified
     elements are added to or removed from the current set of warnings,
     instead of the entire set of warnings being overwritten.  (####
     Need to check whether the newer warnings are settable here.)

     For example, something like this might appear at the top of a
     source file:

              (byte-compiler-options
                (optimize t)
                (warnings (- callargs))		; Don't warn about arglist mismatch
                (warnings (+ unused-vars))	; Do warn about unused bindings
                (file-format emacs19))


File: lispref.info,  Node: Docs and Compilation,  Next: Dynamic Loading,  Prev: Compilation Options,  Up: Byte Compilation

21.4 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 normally 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 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.

   Versions of Emacs up to and including XEmacs 19.14 and FSF Emacs
19.28 do not support the dynamic docstrings feature, and so will not be
able to load bytecode created by more recent Emacs versions.  You can
turn off the dynamic docstring feature by setting
`byte-compile-dynamic-docstrings' to `nil'.  Once this is done, you can
compile files that will load into older Emacs versions.  You can do
this globally, or for one source file by specifying a file-local
binding for the variable.  Here's one way to do that:

     -*-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.
     Default: t.

   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 best not to use
these constructs in Lisp source files.


File: lispref.info,  Node: Dynamic Loading,  Next: Eval During Compile,  Prev: Docs and Compilation,  Up: Byte Compilation

21.5 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 commands, provided that using one of them does not imply
you will soon (or ever) 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
     get nonsense results.

   If you compile a new version of the file, the best thing to do is
immediately load the new compiled file.  That will prevent any future
problems.

   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, like this:

     -*-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.  Default: nil.

 -- Function: fetch-bytecode function
     This immediately finishes loading the definition of FUNCTION from
     its byte-compiled file, if it is not fully loaded already.  The
     argument FUNCTION may be a compiled-function object or a function
     name.


File: lispref.info,  Node: Eval During Compile,  Next: Compiled-Function Objects,  Prev: Dynamic Loading,  Up: Byte Compilation

21.6 Evaluation During Compilation
==================================

These features permit you to write code to be evaluated during
compilation of a program.

 -- Macro: 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'.  Using `require' is
     preferable if there is a substantial amount of code to be executed
     in this way.

 -- Macro: eval-when-compile body
     This form marks BODY to be evaluated at compile time and not when
     the compiled program is loaded.  The result of evaluation by the
     compiler becomes a constant which appears in the compiled program.
     When the program is interpreted, not compiled at all, BODY is
     evaluated normally.

     At top level, this 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: lispref.info,  Node: Compiled-Function Objects,  Next: Disassembly,  Prev: Eval During Compile,  Up: Byte Compilation

21.7 Compiled-Function Objects
==============================

Byte-compiled functions have a special data type: they are
"compiled-function objects". The evaluator handles this data type
specially when it appears as a function to be called.

   The printed representation for a compiled-function object normally
begins with `#<compiled-function' and ends with `>'.  However, if the
variable `print-readably' is non-`nil', the object is printed beginning
with `#[' and ending with `]'.  This representation can be read
directly by the Lisp reader, and is used in byte-compiled files (those
ending in `.elc').

   In Emacs version 18, there was no compiled-function object data type;
compiled functions used the function `byte-code' to run the byte code.

   A compiled-function object has a number of different attributes.
They are:

ARGLIST
     The list of argument symbols.

INSTRUCTIONS
     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.

STACK-DEPTH
     The maximum stack size this function needs.

DOC-STRING
     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.

DOMAIN
     The domain (if any).  This is only meaningful if I18N3
     (message-translation) support was compiled into XEmacs.  This is a
     string defining which domain to find the translation for the
     documentation string and interactive prompt.  *Note Domain
     Specification::.

   Here's an example of a compiled-function object, in printed
representation.  It is the definition of the command `backward-sexp'.

     (symbol-function 'backward-sexp)
     => #<compiled-function
     (&optional arg)
     "...(15)" [arg 1 forward-sexp] 2 854740 "_p">

   The primitive way to create a compiled-function object is with
`make-byte-code':

 -- Function: make-byte-code arglist instructions constants stack-depth
          &optional doc-string interactive
     This function constructs and returns a compiled-function object
     with the specified attributes.

     _Please note:_ Unlike all other Emacs-lisp functions, calling this
     with five arguments is _not_ the same as calling it with six
     arguments, the last of which is `nil'.  If the INTERACTIVE arg is
     specified as `nil', then that means that this function was defined
     with `(interactive)'.  If the arg is not specified, then that means
     the function is not interactive.  This is terrible behavior which
     is retained for compatibility with old `.elc' files which expected
     these semantics.

   You should not try to come up with the elements for a
compiled-function object yourself, because if they are inconsistent,
XEmacs 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).

   The following primitives are provided for accessing the elements of
a compiled-function object.

 -- Function: compiled-function-arglist function
     This function returns the argument list of compiled-function object
     FUNCTION.

 -- Function: compiled-function-instructions function
     This function returns a string describing the byte-code
     instructions of compiled-function object FUNCTION.

 -- Function: compiled-function-constants function
     This function returns the vector of Lisp objects referenced by
     compiled-function object FUNCTION.

 -- Function: compiled-function-stack-depth function
     This function returns the maximum stack size needed by
     compiled-function object FUNCTION.

 -- Function: compiled-function-doc-string function
     This function returns the doc string of compiled-function object
     FUNCTION, if available.

 -- Function: compiled-function-interactive function
     This function returns the interactive spec of compiled-function
     object FUNCTION, if any.  The return value is `nil' or a
     two-element list, the first element of which is the symbol
     `interactive' and the second element is the interactive spec (a
     string or Lisp form).

 -- Function: compiled-function-domain function
     This function returns the domain of compiled-function object
     FUNCTION, if any.  The result will be a string or `nil'.  *Note
     Domain Specification::.


File: lispref.info,  Node: Disassembly,  Next: Different Behavior,  Prev: Compiled-Function Objects,  Up: Byte Compilation

21.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 humanly 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 stream
     This function prints the disassembled code for OBJECT.  If STREAM
     is supplied, then output goes there.  Otherwise, the disassembled
     code is printed to the stream `standard-output'.  The argument
     OBJECT can be a function name or a lambda expression.

     As a special exception, if this function is used interactively, it
     outputs to a buffer named `*Disassemble*'.

   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 value of `integer'
                                 ;   from the environment
                                 ;   and push the value
                                 ;   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 label 1 (which is also byte 7),
                                 ;   else continue.

     5   constant 1              ; Push 1 onto top of stack.

     6   return                  ; Return the top element
                                 ;   of the stack.

     7:1 varref   integer        ; Push value of `integer' onto stack.

     8   constant factorial      ; Push `factorial' onto stack.

     9   varref   integer        ; Push value of `integer' onto stack.

     10  sub1                    ; Pop `integer', decrement value,
                                 ;   push new value onto stack.

                                 ; Stack now contains:
                                 ;   - decremented value of `integer'
                                 ;   - `factorial'
                                 ;   - value of `integer'

     15  call     1              ; Call function `factorial' using
                                 ;   the first (i.e., the top) element
                                 ;   of the stack as the argument;
                                 ;   push returned value onto stack.

                                 ; Stack now contains:
                                 ;   - result of recursive
                                 ;        call to `factorial'
                                 ;   - value of `integer'

     12  mult                    ; Pop top two values off the stack,
                                 ;   multiply them,
                                 ;   pushing the result onto the stack.

     13  return                  ; Return the top element
                                 ;   of the stack.
          => nil

   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 set `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 label 1 (byte 3) if `n' <= 0
                                 ;   (this exits the while loop).
                                 ;   else pop top of stack
                                 ;   and continue

     11  varref   t1             ; Push value of `t1' onto stack.

     12  constant current-time-string  ; Push
                                       ;   `current-time-string'
                                       ;   onto top of stack.

     13  call     0              ; Call `current-time-string' again.

     14  unbind   1              ; Unbind `t1' in local environment.

     15  list2                   ; Pop top two elements off stack,
                                 ;   create a list of them,
                                 ;   and push list onto stack.

     16  return                  ; Return the top element of the stack.

          => nil


File: lispref.info,  Node: Different Behavior,  Prev: Disassembly,  Up: Byte Compilation

21.9 Different Behavior
=======================

The intent is that compiled byte-code and the corresponding code
executed by the Lisp interpreter produce identical results.  However,
there are some circumstances where the results will differ.

   * Arithmetic operations may be rearranged for efficiency or
     compile-time evaluation.  When floating point numbers are
     involved, this may produce different values or an overflow.

   * Some arithmetic operations may be optimized away.  For example, the
     expression `(+ x)' may be optimized to simply `x'.  If the value
     of `x' is a marker, then the value will be a marker instead of an
     integer.  If the value of `x' is a cons cell, then the interpreter
     will issue an error, while the bytecode will not.

     If you're trying to use `(+ OBJECT 0)' to convert OBJECT to
     integer, consider using an explicit conversion function, which is
     clearer and guaranteed to work.  Instead of `(+ CHAR 0)', use
     `(char-int CHAR)'.  Instead of `(+ MARKER 0)', you can write
     `(marker-position MARKER)', but this has its own efficiency
     problems. You many not need to convert from a marker at all, since
     most of the primitives convert automatically; test your code!

   For maximal equivalence between interpreted and compiled code, the
variables `byte-compile-delete-errors' and `byte-compile-optimize' can
be set to `nil', but this is not recommended.


File: lispref.info,  Node: Debugging,  Next: Read and Print,  Prev: Byte Compilation,  Up: Top

22 Debugging Lisp Programs
**************************

There are three ways to investigate a problem in an XEmacs 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 (either the default debugger or Edebug) to investigate
     what is happening during execution.

   * If the problem is syntactic, so that Lisp cannot even read the
     program, you can use the XEmacs 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 XEmacs Lisp debugger is implemented.
* Syntax Errors::       How to find syntax errors.
* Compilation Errors::  How to find errors that show up in byte compilation.
* Edebug::		A source-level XEmacs Lisp debugger.

   Another useful debugging tool is the dribble file.  When a dribble
file is open, XEmacs 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: lispref.info,  Node: Debugger,  Next: Syntax Errors,  Prev: Debugging,  Up: Debugging

22.1 The Lisp Debugger
======================

The "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 XEmacs 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: lispref.info,  Node: Error Debugging,  Next: Infinite Loops,  Prev: Debugger,  Up: Debugger

22.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 get Lisp errors when invoked in
inappropriate contexts (such as `C-f' at the end of the buffer) and
during ordinary editing it would be very unpleasant to enter the
debugger each time this happens.  If you want errors to enter the
debugger, set the variable `debug-on-error' to non-`nil'.

 -- 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
     errors call the debugger.  If it is `nil', none call the debugger.

     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 catch errors that
     happen in process filter functions and sentinels.  Therefore, these
     errors also can invoke the debugger.  *Note Processes::.

 -- User Option: debug-on-signal
     This variable is similar to `debug-on-error' but breaks whenever
     an error is signalled, regardless of whether it would be handled.

 -- 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.

   To debug an error that happens during loading of the `.emacs' file,
use the option `-debug-init', which binds `debug-on-error' to `t' while
`.emacs' is loaded and inhibits use of `condition-case' to catch init
file errors.

   If your `.emacs' file sets `debug-on-error', the effect may not last
past the end of loading `.emacs'.  (This is an undesirable byproduct of
the code that implements the `-debug-init' command line option.)  The
best way to make `.emacs' set `debug-on-error' permanently is with
`after-init-hook', like this:

     (add-hook 'after-init-hook
               '(lambda () (setq debug-on-error t)))


File: lispref.info,  Node: Infinite Loops,  Next: Function Debugging,  Prev: Error Debugging,  Up: Debugger

22.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 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: lispref.info,  Node: Function Debugging,  Next: Explicit Debug,  Prev: Infinite Loops,  Up: Debugger

22.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 `(debug
     'debug)' into the function definition as the first form.

     Any function 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't debug primitive functions (i.e., those
     written in C) this way.

     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.

     *Please note:* if you redefine a function after using
     `debug-on-entry' on it, the code to enter the debugger is lost.

     `debug-on-entry' returns FUNCTION-NAME.

          (defun fact (n)
            (if (zerop n) 1
                (* n (fact (1- n)))))
               => fact
          (debug-on-entry 'fact)
               => fact
          (fact 3)

          ------ Buffer: *Backtrace* ------
          Entering:
          * fact(3)
            eval-region(4870 4878 t)
            byte-code("...")
            eval-last-sexp(nil)
            (let ...)
            eval-insert-last-sexp(nil)
          * call-interactively(eval-insert-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 `nil' or the
     empty string, it cancels debugging for all functions.

     If `cancel-debug-on-entry' is called more than once on the same
     function, the second call does nothing.  `cancel-debug-on-entry'
     returns FUNCTION-NAME.


File: lispref.info,  Node: Explicit Debug,  Next: Using Debugger,  Prev: Function Debugging,  Up: Debugger

22.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'.  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: lispref.info,  Node: Using Debugger,  Next: Debugger Commands,  Prev: Explicit Debug,  Up: Debugger

22.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 XEmacs 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.

   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: lispref.info,  Node: Debugger Commands,  Next: Invoking the Debugger,  Prev: Using Debugger,  Up: Debugger

22.1.6 Debugger Commands
------------------------

Inside the debugger (in Debugger mode), these special commands are
available in addition to the usual cursor motion commands.  (Keep in
mind that all the usual facilities of XEmacs, such as switching windows
or buffers, are still available.)

   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 file for the function and
type `C-M-x' on its definition.)

   Here is a list of Debugger mode commands:

`c'
     Exit the debugger and continue execution.  This resumes execution
     of the program as if the debugger had never been entered (aside
     from the effect of any variables or data structures you may have
     changed while inside the debugger).

     Continuing when an error or quit was signalled will cause the
     normal action of the signalling to take place.  If you do not want
     this to happen, but instead want the program execution to continue
     as if the call to `signal' did not occur, use the `r' command.

`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.

`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 outside-the-debugger values so you can
     examine 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.

`q'
     Terminate the program being debugged; return to top-level XEmacs
     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'); 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.

     If the debugger was entered at the beginning of a function call,
     `r' has the same effect as `c', and the specified return value
     does not matter.

     If the debugger was entered through a call to `signal' (i.e. as a
     result of an error or quit), then returning a value will cause the
     call to `signal' itself to return, rather than throwing to
     top-level or invoking a handler, as is normal.  This allows you to
     correct an error (e.g. the type of an argument was wrong) or
     continue from a `debug-on-quit' as if it never happened.

     Note that some errors (e.g. any error signalled using the `error'
     function, and many errors signalled from a primitive function) are
     not continuable.  If you return a value from them and continue
     execution, then the error will immediately be signalled again.
     Other errors (e.g. wrong-type-argument errors) will be continually
     resignalled until the problem is corrected.


File: lispref.info,  Node: Invoking the Debugger,  Next: Internals of Debugger,  Prev: Debugger Commands,  Up: Debugger

22.1.7 Invoking the Debugger
----------------------------

Here we describe fully the function 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' 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.

     If the first of the DEBUGGER-ARGS passed to `debug' is `nil' (or
     if it is not one of the special values in the table below), then
     `debug' displays the rest of its arguments at the top of the
     `*Backtrace*' buffer.  This mechanism is used to display a message
     to the user.

     However, if the first argument passed to `debug' is one of the
     following special values, then it has special significance.
     Normally, these values are passed to `debug' only by the internals
     of XEmacs and the debugger, and not by programmers calling `debug'.

     The special values are:

    `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 `Entering:' as a line of
          text at the top of the buffer.

    `debug'
          `debug' as first argument indicates a call to `debug' because
          of entry to a function that was set to debug on entry.  The
          debugger displays `Entering:', 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 list form when
          `debug-on-next-call' is non-`nil'.  The debugger displays the
          following as the top line in the buffer:

               Beginning evaluation of function call form:

    `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
          `Return value:' on 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 `Signaling:' followed
          by the error signaled and any arguments to `signal'.  For
          example,

               (let ((debug-on-error t))
                 (/ 1 0))

               ------ Buffer: *Backtrace* ------
               Signaling: (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: lispref.info,  Node: Internals of Debugger,  Prev: Invoking the Debugger,  Up: Debugger

22.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).  Presumably this
     function will enter 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'.

 -- Command: backtrace &optional stream detailed
     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'.

     The backtrace is normally printed to `standard-output', but this
     can be changed by specifying a value for STREAM.  If DETAILED is
     non-`nil', the backtrace also shows places where currently active
     variable bindings, catches, condition-cases, and unwind-protects
     were made as well as function calls.

     In the following example, a Lisp expression calls `backtrace'
     explicitly.  This prints the backtrace to the stream
     `standard-output': in this case, to 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 operators are elided.

          (with-output-to-temp-buffer "backtrace-output"
            (let ((var 1))
              (save-excursion
                (setq var (eval '(progn
                                   (1+ var)
                                   (list 'testing (backtrace))))))))

               => 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-region(1973 2142 #<buffer *scratch*>)
            byte-code("...  for eval-print-last-sexp ...")
            eval-print-last-sexp(nil)
          * call-interactively(eval-print-last-sexp)
          ----------- Buffer: backtrace-output ------------

     The character `*' indicates a frame whose debug-on-exit flag is
     set.

 -- 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.

     The advantage, for the debugger, of using this variable rather than
     another 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 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: lispref.info,  Node: Syntax Errors,  Next: Compilation Errors,  Prev: Debugger,  Up: Debugging

22.2 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.

* 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: lispref.info,  Node: Excess Open,  Next: Excess Close,  Prev: Syntax Errors,  Up: Syntax Errors

22.2.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 insert a close
parenthesis at the end of the file and type `C-M-b' (`backward-sexp').
This will move you to the beginning of the defun that is unbalanced.
(Then type `C-<SPC> C-_ C-u C-<SPC>' to set the mark there, undo the
insertion of the close parenthesis, and finally return to the mark.)

   The next step is to determine precisely what is wrong.  There is no
way to be sure of this except to study 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.

   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: lispref.info,  Node: Excess Close,  Prev: Excess Open,  Up: Syntax Errors

22.2.2 Excess Close Parentheses
-------------------------------

To deal with an excess close parenthesis, first insert an open
parenthesis at the beginning of the file, back up over it, and type
`C-M-f' to find the end of the unbalanced defun.  (Then type `C-<SPC>
C-_ C-u C-<SPC>' to set the mark there, undo the insertion of the open
parenthesis, and finally return to the mark.)

   Then find the actual matching close parenthesis by typing `C-M-f' at
the beginning of the 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 fit the intended nesting of parentheses,
and you have put back those parentheses, `C-M-q' should not change
anything.


File: lispref.info,  Node: Compilation Errors,  Next: Edebug,  Prev: Syntax Errors,  Up: Debugging

22.3 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: lispref.info,  Node: Edebug,  Prev: Compilation Errors,  Up: Top

22.4 Edebug
===========

Edebug is a source-level debugger for XEmacs Lisp programs that
provides the following features:

   * Step through evaluation, stopping before and after each expression.

   * Set conditional or unconditional breakpoints, install embedded
     breakpoints, or a global break event.

   * Trace slow or fast stopping briefly at each stop point, or each
     breakpoint.

   * Display expression results and evaluate expressions as if outside
     of Edebug.  Interface with the custom printing package for
     printing circular structures.

   * Automatically reevaluate a list of expressions and display their
     results each time Edebug updates the display.

   * Output trace info on function enter and exit.

   * Errors stop before the source causing the error.

   * Display backtrace without Edebug calls.

   * Allow specification of argument evaluation for macros and defining
     forms.

   * Provide rudimentary coverage testing and display of frequency
     counts.


   The first three sections should tell you enough about Edebug to
enable you to use it.

* Menu:

* Using Edebug::		Introduction to use of Edebug.
* Instrumenting::		You must first instrument code.
* Edebug Execution Modes::	Execution modes, stopping more or less often.
* Jumping::			Commands to jump to a specified place.
* Edebug Misc::			Miscellaneous commands.
* Breakpoints::			Setting breakpoints to make the program stop.
* Trapping Errors::		trapping errors with Edebug.
* Edebug Views::		Views inside and outside of Edebug.
* Edebug Eval::			Evaluating expressions within Edebug.
* Eval List::			Automatic expression evaluation.
* Reading in Edebug::		Customization of reading.
* Printing in Edebug::		Customization of printing.
* Tracing::			How to produce tracing output.
* Coverage Testing::		How to test evaluation coverage.
* The Outside Context::		Data that Edebug saves and restores.
* Instrumenting Macro Calls::	Specifying how to handle macro calls.
* Edebug Options::		Option variables for customizing Edebug.


File: lispref.info,  Node: Using Edebug,  Next: Instrumenting,  Up: Edebug

22.4.1 Using Edebug
-------------------

To debug an XEmacs Lisp program with Edebug, you must first
"instrument" the Lisp code that you want to debug.  If you want to just
try it now, load `edebug.el', move point into a definition and 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.  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, depending on the selected Edebug
execution mode.  The initial execution mode is `step', by default,
which does stop execution.  *Note Edebug Execution Modes::.

   Within Edebug, you normally view an XEmacs buffer showing the source
of the Lisp function you are debugging.  This is referred to as the
"source code buffer"--but note that it is not always the same buffer
depending on which function is currently being executed.

   An arrow at the left margin indicates the line where the function is
executing.  Point initially shows where within the line the function is
executing, but you can move point yourself.

   If you instrument the definition of `fac' (shown below) and then
execute `(fac 3)', here is what you 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 show with periods the stop points found in the function `fac':

     (defun fac (n)
       .(if .(< 0 n.).
           .(* n. .(fac (1- n.).).).
         1).)

   While the source code buffer is selected, the special commands of
Edebug are available in it, in addition to the commands of XEmacs Lisp
mode.  (The buffer is temporarily made read-only, however.)  For
example, you can type the Edebug command <SPC> to execute until the
next stop point.  If you type <SPC> once after entry to `fac', here is
the display you will see:

     (defun fac (n)
     =>(if -!-(< 0 n)
           (* n (fac (1- n)))
         1))

   When Edebug stops execution after an expression, it displays the
expression's value in the echo area.

   Other frequently used commands are `b' to set a breakpoint at a stop
point, `g' to execute until a breakpoint is reached, and `q' to exit to
the top-level command loop.  Type `?' to display a list of all Edebug
commands.


File: lispref.info,  Node: Instrumenting,  Next: Edebug Execution Modes,  Prev: Using Edebug,  Up: Edebug

22.4.2 Instrumenting for Edebug
-------------------------------

In order to use Edebug to debug Lisp code, you must first "instrument"
the code.  Instrumenting a form inserts additional code into it which
invokes Edebug at the proper places.  Furthermore, if Edebug detects a
syntax error while instrumenting, point is left at the erroneous code
and an `invalid-read-syntax' error is signaled.

   Once you have loaded Edebug, the command `C-M-x' (`eval-defun') is
redefined so that when invoked with a prefix argument on a definition,
it instruments the definition before evaluating it.  (The source code
itself is not modified.)  If the variable `edebug-all-defs' is
non-`nil', that inverts the meaning of the prefix argument: then
`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 value of
`edebug-all-defs' or `edebug-all-forms'.

   Just before Edebug instruments any code, it calls any functions in
the variable `edebug-setup-hook' and resets its value 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.  For example,
`my-specs.el' may be loaded automatically when you use `my-package'
with Edebug by including the following code in `my-package.el'.

     (add-hook 'edebug-setup-hook
       (function (lambda () (require 'my-specs))))

   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 is not already instrumented.  If the location of
the definition is not known to Edebug, this command cannot be used.
After loading Edebug, `eval-region' records the position of every
definition it evaluates, even if not instrumenting it.  Also see the
command `i' (*Note Jumping::) which steps into the callee.

   Edebug knows how to instrument all the standard special operators, an
interactive form with an expression argument, anonymous lambda
expressions, and other defining forms.  (Specifications for macros
defined by `cl.el' (version 2.03) are provided in `cl-specs.el'.)
Edebug cannot know what a user-defined macro will do with the arguments
of a macro call so you must tell it.  See *Note Instrumenting Macro
Calls:: for the details.

   Note that a couple ways remain to evaluate expressions without
instrumenting them.  Loading a file via the `load' subroutine does not
instrument expressions for Edebug.  Evaluations in the minibuffer via
`eval-expression' (`M-ESC') are not instrumented.

   To remove instrumentation from a definition, simply reevaluate it
with one of the non-instrumenting commands, or reload the file.

   See *Note Edebug Eval:: for other evaluation functions available
inside of Edebug.


File: lispref.info,  Node: Edebug Execution Modes,  Next: Jumping,  Prev: Instrumenting,  Up: Edebug

22.4.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 Edebug displays the progress of the evaluation,
whether it stops at each stop point, or continues to the next
breakpoint, for example.

   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 for now, just wait for
     more Edebug commands (`edebug-stop').

`<SPC>'
     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
     Edebug Misc::.

`t'
     Trace: pause one second at each Edebug stop point
     (`edebug-trace-mode').

`T'
     Rapid trace: update 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 for one second at each breakpoint, but don't stop
     (`edebug-continue-mode').

`C'
     Rapid continue: update at each breakpoint, but don't actually pause
     (`edebug-Continue-fast-mode').

`G'
     Go non-stop: ignore breakpoints (`edebug-Go-nonstop-mode').  You
     can still stop the program by hitting any key.

   In general, the execution modes earlier in the above list run the
program more slowly or stop sooner.

   When you enter a new Edebug level, the initial execution mode comes
from the value of the variable `edebug-initial-mode'.  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.

   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 that 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 hit
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 Edebug commands do not work; when you exit
from Edebug, to resume the program, whether you are defining or
executing a keyboard macro is forgotten.  Also, defining or executing a
keyboard macro outside of Edebug does not affect the command loop inside
Edebug.  This is usually an advantage.  But see
`edebug-continue-kbd-macro'.


File: lispref.info,  Node: Jumping,  Next: Edebug Misc,  Prev: Edebug Execution Modes,  Up: Edebug

22.4.4 Jumping
--------------

Commands described here let you jump to a specified location.  All,
except `i', use temporary breakpoints to establish the stop point and
then switch to `go' mode.  Any other breakpoint reached before the
intended stop point will also stop execution.  See *Note Breakpoints::
for the details on breakpoints.

`f'
     Run the program forward over one expression
     (`edebug-forward-sexp').  More precisely, set a temporary
     breakpoint at the position that `C-M-f' would reach, then execute
     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.

     Be careful that the position `C-M-f' finds is a place that the
     program will really get to; this may not be true in a `cond', for
     example.

     This command does `forward-sexp' starting at point rather than the
     stop point.  If you want to execute one expression from the
     current stop point, type `w' first, to move point there.

`o'
     Continue "out of" an expression (`edebug-step-out').  It places a
     temporary breakpoint at the end of the sexp containing point.

     If the containing sexp is a function definition itself, it
     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.

`I'
     Step into the function or macro after point after first ensuring
     that it is instrumented.  It does this by calling
     `edebug-on-entry' and then switching to `go' mode.

     Although the automatic instrumentation is convenient, it is not
     later automatically uninstrumented.

`h'
     Proceed to the stop point near where point is using a temporary
     breakpoint (`edebug-goto-here').


   All the commands in this section may fail to work as expected in case
of nonlocal exit, because a nonlocal exit can bypass the temporary
breakpoint where you expected the program to stop.


File: lispref.info,  Node: Edebug Misc,  Next: Breakpoints,  Prev: Jumping,  Up: Edebug

22.4.5 Miscellaneous
--------------------

Some miscellaneous 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
     (`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.

   From the Edebug recursive edit, you may invoke commands that activate
Edebug again recursively.  Any time 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: lispref.info,  Node: Breakpoints,  Next: Trapping Errors,  Prev: Edebug Misc,  Up: Edebug

22.4.6 Breakpoints
------------------

There are three more ways to stop execution once it has started:
breakpoints, the global break condition, and embedded breakpoints.

   While using Edebug, you can specify "breakpoints" in the program you
are testing: points 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 the
     current point (`edebug-unset-breakpoint').

`x CONDITION <RET>'
     Set a conditional breakpoint which stops the program only if
     CONDITION evaluates to a non-`nil' value
     (`edebug-set-conditional-breakpoint').  If you use a prefix
     argument, the breakpoint is temporary (it turns off the first time
     it stops the program).

`B'
     Move point to the next breakpoint in the definition
     (`edebug-next-breakpoint').

   While in Edebug, you can set a breakpoint with `b' and unset one
with `u'.  First you must move point to a position at or before the
desired Edebug stop point, then hit the key to change the breakpoint.
Unsetting a breakpoint that has not been set does nothing.

   Reevaluating or reinstrumenting a definition clears all its
breakpoints.

   A "conditional breakpoint" tests a condition each time the program
gets there.  To set a conditional breakpoint, use `x', and specify the
condition expression in the minibuffer.  Setting a conditional
breakpoint at a stop point that already has a conditional breakpoint
puts the current condition expression in the minibuffer so you can edit
it.

   You can make both conditional and unconditional breakpoints
"temporary" by using a prefix arg to the command to set the breakpoint.
After breaking at a temporary breakpoint, it is automatically cleared.

   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 `B', which moves point
to the next breakpoint in the definition following point, or to the
first breakpoint if there are no following breakpoints.  This command
does not continue execution--it just moves point in the buffer.

* Menu:

* Global Break Condition::	Breaking on an event.
* Embedded Breakpoints::	Embedding breakpoints in code.


File: lispref.info,  Node: Global Break Condition,  Next: Embedded Breakpoints,  Up: Breakpoints

22.4.6.1 Global Break Condition
...............................

In contrast to breaking when execution reaches specified locations, you
can also cause a break when a certain event occurs.  The "global break
condition" is a condition that is repeatedly evaluated at every stop
point.  If it evaluates to a non-`nil' value, then execution is stopped
or paused depending on the execution mode, just like a breakpoint.  Any
errors that might occur as a result of evaluating the condition are
ignored, as if the result were `nil'.

   You can set or edit the condition expression, stored in
`edebug-global-break-condition', using `X'
(`edebug-set-global-break-condition').

   Using the global break condition is perhaps the fastest way to find
where in your code some event occurs, but since it is rather expensive
you should reset the condition to `nil' when not in use.


File: lispref.info,  Node: Embedded Breakpoints,  Prev: Global Break Condition,  Up: Breakpoints

22.4.6.2 Embedded Breakpoints
.............................

Since all breakpoints in a definition are cleared each time you
reinstrument it, you might rather create an "embedded breakpoint" which
is simply a call to the function `edebug'.  You can, of course, make
such a call conditional.  For example, in the `fac' function, 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, Edebug will stop before the call to `edebug'.  Depending on the
execution mode, Edebug will stop or pause.

   However, if no instrumented code is being executed, calling `edebug'
will instead invoke `debug'.  Calling `debug' will always invoke the
standard backtrace debugger.


File: lispref.info,  Node: Trapping Errors,  Next: Edebug Views,  Prev: Breakpoints,  Up: Edebug

22.4.7 Trapping Errors
----------------------

An error may be signaled by subroutines or XEmacs Lisp code.  If a
signal is not handled by a `condition-case', this indicates an
unrecognized situation has occurred.  If Edebug is not active when an
unhandled error is signaled, `debug' is run normally (if
`debug-on-error' is non-`nil').  But while Edebug is active,
`debug-on-error' and `debug-on-quit' are bound to `edebug-on-error' and
`edebug-on-quit', which are both `t' by default.  Actually, if
`debug-on-error' already has a non-`nil' value, that value is still
used.

   It is best to change the values of `edebug-on-error' or
`edebug-on-quit' when Edebug is not active since their values won't be
used until the next time Edebug is invoked at a deeper command level.
If you only 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.

   Edebug shows you the last stop point that it knew about before the
error was signaled.  This may be the location of a call to a function
which was not instrumented, within which the error actually occurred.
For an unbound variable error, the last known stop point might be quite
distant from the offending variable.  If the cause of the error is not
obvious at first, note that you can also get a full backtrace inside of
Edebug (see *Note Edebug Misc::).

   Edebug can also trap signals even if they are handled.  If
`debug-on-error' is a list of signal names, Edebug will stop when any
of these errors are signaled.  Edebug shows you the last known stop
point just as for unhandled errors.  After you continue execution, the
error is signaled again (but without being caught by Edebug).  Edebug
can only trap errors that are handled if they are signaled in Lisp code
(not subroutines) since it does so by temporarily replacing the
`signal' function.


File: lispref.info,  Node: Edebug Views,  Next: Edebug Eval,  Prev: Trapping Errors,  Up: Edebug

22.4.8 Edebug Views
-------------------

The following Edebug commands let you view aspects of the buffer and
window status that obtained before entry to Edebug.

`v'
     View the outside window configuration (`edebug-view-outside').

`p'
     Temporarily display the outside current buffer with point at its
     outside position (`edebug-bounce-point'). If prefix arg is
     supplied, sit for that many seconds instead.

`w'
     Move point back to the current stop point (`edebug-where') in the
     source code buffer.  Also, if you use this command in another
     window displaying the same buffer, this window will be used
     instead to display the buffer in the future.

`W'
     Toggle the `edebug-save-windows' variable which indicates whether
     the outside window configuration is saved and restored
     (`edebug-toggle-save-windows').  Also, each time it is toggled on,
     make the outside window configuration the same as the current
     window configuration.

     With a prefix argument, `edebug-toggle-save-windows' 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-xXW' from the global keymap.


   You can view the outside window configuration with `v' or just
bounce to the current point in the current buffer with `p', even if it
is not normally displayed.  After moving point, you may wish to pop
back to the stop point with `w' from a source code buffer.

   By using `W' twice, Edebug again saves and restores the outside
window configuration, but to the current configuration.  This is a
convenient way to, for example, add another buffer to be displayed
whenever Edebug is active.  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: lispref.info,  Node: Edebug Eval,  Next: Eval List,  Prev: Edebug Views,  Up: Edebug

22.4.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 things that Edebug explicitly
saves and restores.  See *Note The Outside Context:: for details on this
process.  Also see *Note Reading in Edebug:: and *Note Printing in
Edebug:: for topics related to evaluation.

`e EXP <RET>'
     Evaluate expression EXP in the context outside of Edebug
     (`edebug-eval-expression').  In other words, Edebug tries to avoid
     altering the effect of EXP.

`M-<ESC> EXP <RET>'
     Evaluate expression EXP in the context of Edebug itself.

`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'
(version 2.03 or later): `lexical-let', `macrolet', and
`symbol-macrolet'.


File: lispref.info,  Node: Eval List,  Next: Reading in Edebug,  Prev: Edebug Eval,  Up: Edebug

22.4.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 as well as these special commands:

`LFD'
     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 first expression of each
     group, reevaluate and redisplay (`edebug-update-eval-list').
     Groups are separated by comment lines.

`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
`LFD' 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 unless you add them to the evaluation list
with `C-c C-u'.  This command builds a new list from the first
expression of each "evaluation list group".  Groups are separated by
comment lines.  Be careful not to add expressions that execute
instrumented code otherwise an infinite loop will result.

   When the evaluation list is redisplayed, each expression is displayed
followed by the result of evaluating it, and a comment line.  If an
error occurs during an evaluation, the error message is displayed in a
string as if it were the result.  Therefore expressions that, for
example, use variables not currently valid do not interrupt your
debugging.

   Here is an example of what the evaluation list window looks like
after several expressions have been added to it:

     (current-buffer)
     #<buffer *scratch*>
     ;---------------------------------------------------------------
     (selected-window)
     #<window 16 on *scratch*>
     ;---------------------------------------------------------------
     (point)
     196
     ;---------------------------------------------------------------
     bad-var
     "Symbol's value as variable is void: bad-var"
     ;---------------------------------------------------------------
     (recursion-depth)
     0
     ;---------------------------------------------------------------
     this-command
     eval-last-sexp
     ;---------------------------------------------------------------

   To delete a group, move point into it and type `C-c C-d', or simply
delete the text for the group and update the evaluation list with `C-c
C-u'.  When you add a new group, be sure it is separated from its
neighbors by a comment line.

   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: lispref.info,  Node: Reading in Edebug,  Next: Printing in Edebug,  Prev: Eval List,  Up: Edebug

22.4.11 Reading in Edebug
-------------------------

To instrument a form, Edebug first reads the whole form.  Edebug
replaces the standard Lisp Reader with its own reader that remembers the
positions of expressions.  This reader is used by the Edebug
replacements for `eval-region', `eval-defun', `eval-buffer', and
`eval-current-buffer'.

   Another package, `cl-read.el', replaces the standard reader with one
that understands Common Lisp reader macros.  If you use that package,
Edebug will automatically load `edebug-cl-read.el' to provide
corresponding reader macros that remember positions of expressions.  If
you define new reader macros, you will have to define similar reader
macros for Edebug.


File: lispref.info,  Node: Printing in Edebug,  Next: Tracing,  Prev: Reading in Edebug,  Up: Edebug

22.4.12 Printing in Edebug
--------------------------

If the result of an expression in your program contains a circular
reference, you may get an error when Edebug attempts to print it.  You
can set `print-length' to a non-zero value to limit the print length of
lists (the number of cdrs), and in Emacs 19, set `print-level' to a
non-zero value to limit the print depth of lists.  But you can print
such circular structures and structures that share elements more
informatively by using the `cust-print' package.

   To load `cust-print' and activate custom printing only for Edebug,
simply use the command `M-x edebug-install-custom-print'.  To restore
the standard print functions, use `M-x edebug-uninstall-custom-print'.
You can also activate custom printing for printing in any Lisp code;
see the package for details.

   Here is an example of code that creates a circular structure:

     (progn
       (edebug-install-custom-print)
       (setq a '(x y))
       (setcar a a))

   Edebug will print the result of the `setcar' as `Result: #1=(#1#
y)'.  The `#1=' notation names the structure that follows it, and the
`#1#' notation references the previously named structure.  This
notation is used for any shared elements of lists or vectors.

   Independent of whether `cust-print' is active, while printing
results Edebug binds `print-length', `print-level', and `print-circle'
to `edebug-print-length' (`50'), `edebug-print-level' (`50'), and
`edebug-print-circle' (`t') respectively, if these values are
non-`nil'.  Also, `print-readably' is bound to `nil' since some objects
simply cannot be printed readably.


File: lispref.info,  Node: Tracing,  Next: Coverage Testing,  Prev: Printing in Edebug,  Up: Edebug

22.4.13 Tracing
---------------

In addition to automatic stepping through source code, which is also
called _tracing_ (see *Note Edebug Execution Modes::), Edebug can
produce a traditional trace listing of execution in a separate buffer,
`*edebug-trace*'.

   If the variable `edebug-trace' is non-`nil', each function entry and
exit adds lines to the trace buffer.  On function entry, Edebug prints
`::::{' followed by the function name and argument values.  On function
exit, Edebug prints `::::}' followed by the function name and result of
the function.  The number of `:'s is computed from the recursion depth.
The balanced braces in the trace buffer can be used to find the
matching beginning or end of function calls. These displays may be
customized by replacing the functions `edebug-print-trace-before' and
`edebug-print-trace-after', which take an arbitrary message string to
print.

   The macro `edebug-tracing' provides tracing similar to function
enter and exit tracing, but for arbitrary expressions.  This macro
should be explicitly inserted by you around expressions you wish to
trace the execution of.  The first argument is a message string
(evaluated), and the rest are expressions to evaluate.  The result of
the last expression is returned.

   Finally, you can insert arbitrary strings into the trace buffer with
explicit calls to `edebug-trace'.  The arguments of this function are
the same as for `message', but a newline is always inserted after each
string printed in this way.

   `edebug-tracing' and `edebug-trace' insert lines in the trace buffer
even if Edebug is not active.  Every time the trace buffer is added to,
the window is scrolled to show the last lines inserted.  (There may be
some display problems if you use tracing along with the evaluation
list.)


File: lispref.info,  Node: Coverage Testing,  Next: The Outside Context,  Prev: Tracing,  Up: Edebug

22.4.14 Coverage Testing
------------------------

Edebug provides a rudimentary coverage tester and display of execution
frequency.  Frequency counts are always accumulated, both before and
after evaluation of each instrumented expression, even if the execution
mode is `Go-nonstop'.  Coverage testing is only done if the option
`edebug-test-coverage' is non-`nil' because this is relatively
expensive.  Both data sets are displayed by `M-x
edebug-display-freq-count'.

 -- Command: edebug-display-freq-count
     Display the frequency count data for each line of the current
     definition.  The frequency counts are inserted as comment lines
     after each line, and you can undo all insertions with one `undo'
     command.  The counts are inserted starting under the `(' before an
     expression or the `)' after an expression, or on the last char of
     a symbol.  The counts are only displayed when they differ from
     previous counts on the same line.

     If coverage is being tested, whenever all known results of an
     expression are `eq', the char `=' will be appended after the count
     for that expression.  Note that this is always the case for an
     expression only evaluated once.

     To clear the frequency count and coverage data for a definition,
     reinstrument it.


   For example, after evaluating `(fac 5)' with an embedded breakpoint,
and setting `edebug-test-coverage' to `t', when the breakpoint is
reached, the frequency data is looks like this:

     (defun fac (n)
       (if (= n 0) (edebug))
     ;#6           1      0 =5
       (if (< 0 n)
     ;#5         =
           (* n (fac (1- n)))
     ;#    5               0
         1))
     ;#   0

   The comment lines show that `fac' has been called 6 times.  The
first `if' statement has returned 5 times with the same result each
time, and the same is true for the condition on the second `if'.  The
recursive call of `fac' has not returned at all.


File: lispref.info,  Node: The Outside Context,  Next: Instrumenting Macro Calls,  Prev: Coverage Testing,  Up: Edebug

22.4.15 The Outside Context
---------------------------

Edebug tries to be transparent to the program you are debugging.  In
addition, most evaluations you do within Edebug (see *Note Edebug
Eval::) occur in the same outside context which is temporarily restored
for the evaluation.  But Edebug is not completely successful and this
section explains precisely how it fails.  Edebug operation unavoidably
alters some data in XEmacs, and this can interfere with debugging
certain programs.  Also notice that Edebug's protection against change
of outside data means that any side effects _intended_ by the user in
the course of debugging will be defeated.

* 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: lispref.info,  Node: Checking Whether to Stop,  Next: Edebug Display Update,  Up: The Outside Context

22.4.15.1 Checking Whether to Stop
..................................

Whenever Edebug is entered just to think about whether to take some
action, it needs to save and restore certain data.

   * `max-lisp-eval-depth' and `max-specpdl-size' are both incremented
     one time 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-macro' is bound to
     `edebug-continue-kbd-macro'.



File: lispref.info,  Node: Edebug Display Update,  Next: Edebug Recursive Edit,  Prev: Checking Whether to Stop,  Up: The Outside Context

22.4.15.2 Edebug Display Update
...............................

When Edebug needs to display something (e.g., in trace mode), it saves
the current window configuration from "outside" Edebug.  When you exit
Edebug (by continuing the program), it restores the previous window
configuration.

   XEmacs redisplays only when it pauses.  Usually, when you continue
execution, the program comes back into Edebug at a breakpoint or after
stepping without pausing or reading input in between.  In such cases,
XEmacs never gets a chance to redisplay the "outside" configuration.
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, but some of these are deliberately not restored if an
error or quit signal occurs.

   * Which buffer is current, and where point and mark are in the
     current buffer are saved and restored.

   * The Edebug Display Update, is saved and restored if
     `edebug-save-windows' is non-`nil'.  It 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.

   * 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: lispref.info,  Node: Edebug Recursive Edit,  Prev: Edebug Display Update,  Up: The Outside Context

22.4.15.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, for whichever buffer was current.

   * `last-command', `this-command', `last-command-char',
     `last-input-char', `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.

     The key sequence returned by `this-command-keys' is changed by
     executing commands within Edebug and there is no way to reset the
     key sequence from Lisp.

     For Emacs 18, Edebug cannot save and restore the value of
     `unread-command-char'.  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: lispref.info,  Node: Instrumenting Macro Calls,  Next: Edebug Options,  Prev: The Outside Context,  Up: Edebug

22.4.16 Instrumenting Macro Calls
---------------------------------

When Edebug instruments an expression that calls a Lisp macro, it needs
additional advice to do the job properly.  This is because there is no
way to tell which subexpressions of the macro call may be evaluated.
(Evaluation may occur explicitly in the macro body, or when the
resulting expansion is evaluated, or any time later.)  You must explain
the format of macro call arguments by using `def-edebug-spec' to define
an "Edebug specification" for each macro.

 -- Macro: def-edebug-spec macro specification
     Specify which expressions of a call to macro 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.

     The MACRO argument may actually be any symbol, not just a macro
     name.

     Unless you are using Emacs 19 or XEmacs, this macro is only defined
     in Edebug, so you may want to use the following which is
     equivalent: `(put 'MACRO 'edebug-form-spec 'SPECIFICATION)'

   Here is a simple example that defines the specification for the
`for' macro described in the XEmacs Lisp Reference Manual, followed by
an alternative, equivalent specification.

     (def-edebug-spec for
       (symbolp "from" form "to" form "do" &rest form))

     (def-edebug-spec for
       (symbolp ['from form] ['to form] ['do body]))

   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 for 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.

* Menu:

* Specification List::		How to specify complex patterns of evaluation.
* Backtracking::		What Edebug does when matching fails.
* Debugging Backquote::	Debugging Backquote
* Specification Examples::	To help understand specifications.


File: lispref.info,  Node: Specification List,  Next: Backtracking,  Up: Instrumenting Macro Calls

22.4.16.1 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
"keyword specifications", are symbols beginning with ``&'' (e.g.
`&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.  Keyword specifications only apply to the
remainder of the sublist or group they are contained in and there is an
implicit grouping around a keyword specification and all following
elements in the sublist or group.

   If a specification list fails at some level, then backtracking may
be invoked to find some alternative at a higher level, or if no
alternatives remain, an error will be signaled.  See *Note
Backtracking:: for more details.

   Edebug specifications provide at least the power of regular
expression matching.  Some context-free constructs are also supported:
the matching of sublists with balanced parentheses, recursive
processing of forms, and recursion via indirect specifications.

   Each element of a specification list may be one of the following,
with the corresponding type of argument:

`sexp'
     A single unevaluated expression.

`form'
     A single evaluated expression, which is instrumented.

`place'
     A place as in the Common Lisp `setf' place argument.  It will be
     instrumented just like a form, but the macro is expected to strip
     the instrumentation.  Two functions, `edebug-unwrap' and
     `edebug-unwrap*', are provided to strip the instrumentation one
     level or recursively at all levels.

`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 function arguments
     might be quoted with `quote' rather than `function' since the body
     of a lambda expression will be instrumented either way.

`lambda-expr'
     An unquoted anonymous lambda expression.

`&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 should all succeed together, use `&optional [SPECS...]'.
     See the `defun' example below.

`&rest'
     All following elements in the specification list are repeated zero
     or more times.  All the elements need not match in the last
     repetition, however.

     To repeat only a few elements, use `[&rest SPECS...]'.  To specify
     all elements must match on every repetition, use `&rest
     [SPECS...]'.

`&or'
     Each of the following elements in the specification list is an
     alternative, processed left to right until one matches.  One of the
     alternatives must match otherwise the `&or' specification fails.

     Each list element following `&or' is a single alternative even if
     it is a keyword specification. (This breaks the implicit grouping
     rule.)  To group two or more list elements as a single
     alternative, enclose them in `[...]'.

`&not'
     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 `&not'
     specification succeeds.

`&define'
     Indicates that the specification is for a defining form.  The
     defining form itself is not instrumented (i.e. 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.

     Additional specifications that may only appear after `&define' are
     described here.  See the `defun' example below.

    `name'
          The argument, a symbol, is the name of the defining form.
          But a defining form need not be named at all, in which case a
          unique name will be created for it.

          The `name' specification may be used more than once in the
          specification and each subsequent use will append the
          corresponding symbol argument to the previous name with ``@''
          between them.  This is useful for generating unique but
          meaningful names for definitions such as `defadvice' and
          `defmethod'.

    `:name'
          The element following `:name' should be a symbol; it is used
          as an additional name component for the definition.  This is
          useful to add a unique, static component to the name of the
          definition.  It may be used more than once.  No argument is
          matched.

    `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.  See `lambda-list' and
          the example below.

    `lambda-list'
          This matches the whole argument list of an XEmacs Lisp lambda
          expression, which is a list of symbols and the keywords
          `&optional' and `&rest'

    `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 use this 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
          below.


`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 below.

`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 below.

`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 below.

     Otherwise, the symbol should be a predicate.  The predicate is
     called with the argument and the specification fails if the
     predicate fails.  The argument is not instrumented.

     Predicates that may be used include: `symbolp', `integerp',
     `stringp', `vectorp', `atom' (which matches a number, string,
     symbol, or vector), `keywordp', and `lambda-list-keywordp'.  The
     last two, defined in `edebug.el', test whether the argument is a
     symbol starting with ``:'' and ``&'' respectively.

`[ELEMENTS...]'
     Rather than matching a vector argument, a vector treats the
     ELEMENTS as a single "group specification".

`"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.

`'SYMBOL or (quote SYMBOL)'
     The argument should be the symbol SYMBOL.  But use a string
     specification instead.

`(vector ELEMENTS...)'
     The argument should be a vector whose elements must match the
     ELEMENTS in the specification.  See the backquote example below.

`(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 below.  Also see the description of a
     `nil' specification above for terminating such recursion.

     Note that a sublist specification of the form `(specs .  nil)'
     means the same as `(specs)', and `(specs .
     (sublist-elements...))' means the same as `(specs
     sublist-elements...)'.



File: lispref.info,  Node: Backtracking,  Next: Debugging Backquote,  Prev: Specification List,  Up: Instrumenting Macro Calls

22.4.16.2 Backtracking
......................

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.

   Backtracking is disabled for the remainder of a sublist or group when
certain conditions occur, described below.  Backtracking is reenabled
when a new alternative is established by `&optional', `&rest', or
`&or'.  It is also reenabled initially when processing a sublist or
group specification or an indirect specification.

   You might want to disable backtracking to commit to some alternative
so that Edebug can provide a more specific syntax error message.
Normally, if no alternative matches, Edebug reports that none matched,
but if one alternative is committed to, Edebug can report how it failed
to match.

   First, backtracking is disabled while matching any of the form
specifications (i.e. `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.

   Second, backtracking is disabled after successfully matching a quoted
symbol or string specification, since this usually indicates a
recognized construct.  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] ...]'.

   Third, backtracking may be explicitly disabled by using the `gate'
specification.  This is useful when you know that no higher
alternatives may apply.


File: lispref.info,  Node: Debugging Backquote,  Next: Specification Examples,  Prev: Backtracking,  Up: Instrumenting Macro Calls

22.4.16.3 Debugging Backquote
.............................

Backquote (``') is a macro that results in an expression that may or
may not be evaluated.  It is often used to simplify the definition of a
macro to return an expression that is evaluated, but Edebug does not
know when this is the case.  However, the forms inside unquotes (`,' and
`,@') are evaluated and Edebug instruments them.

   Nested backquotes are supported by Edebug, but there is a limit on
the support of quotes inside of backquotes.  Quoted forms (with `'')
are not normally evaluated, but if the quoted form appears immediately
within `,' and `,@' forms, Edebug treats this as a backquoted form at
the next higher level (even if there is not a next higher level - this
is difficult to fix).

   If the backquoted forms happen to be code intended to be evaluated,
you can have Edebug instrument them by using `edebug-`' instead of the
regular ``'.  Unquoted forms can always appear inside `edebug-`'
anywhere a form is normally allowed.  But `(, FORM)' may be used in two
other places specially recognized by Edebug: wherever a predicate
specification would match, and at the head of a list form in place of a
function name or lambda expression.  The FORM inside a spliced unquote,
`(,@ FORM)', will be wrapped, but the unquote form itself will not be
wrapped since this would interfere with the splicing.

   There is one other complication with using `edebug-`'.  If the
`edebug-`' call is in a macro and the macro may be called from code
that is also instrumented, and if unquoted forms contain any macro
arguments bound to instrumented forms, then you should modify the
specification for the macro as follows: the specifications for those
arguments must use `def-form' instead of `form'.  (This is to
reestablish the Edebugging context for those external forms.)

   For example, the `for' macro (*note Problems with Macros: ()Problems
with Macros.) is shown here but with `edebug-`' substituted for regular
``'.

     (defmacro inc (var)
       (list 'setq var (list '1+ var)))

     (defmacro for (var from init to final do &rest body)
       (let ((tempvar (make-symbol "max")))
         (edebug-` (let (((, var) (, init))
                         ((, tempvar) (, final)))
                     (while (<= (, var) (, tempvar))
                       (, body)
                       (inc (, var)))))))

   Here is the corresponding modified Edebug specification and some code
that calls the macro:

     (def-edebug-spec for
       (symbolp "from" def-form "to" def-form "do" &rest def-form))

     (let ((n 5))
       (for i from n to (* n (+ n 1)) do
         (message "%s" i)))

   After instrumenting the `for' macro and the macro call, Edebug first
steps to the beginning of the macro call, then into the macro body,
then through each of the unquoted expressions in the backquote showing
the expressions that will be embedded in the backquote form.  Then when
the macro expansion is evaluated, Edebug will step through the `let'
form and each time it gets to an unquoted form, it will jump back to an
argument of the macro call to step through that expression.  Finally
stepping will continue after the macro call.  Even more convoluted
execution paths may result when using anonymous functions.

   When the result of an expression is an instrumented expression, it is
difficult to see the expression inside the instrumentation.  So you may
want to set the option `edebug-unwrap-results' to a non-`nil' value
while debugging such expressions, but it would slow Edebug down to
always do this.


File: lispref.info,  Node: Specification Examples,  Prev: Debugging Backquote,  Up: Instrumenting Macro Calls

22.4.16.4 Specification Examples
................................

Here we provide several examples of Edebug specifications to show many
of its capabilities.

   A `let' special operator has a sequence of bindings and a body.  Each
of the bindings is either a symbol or a sublist with a symbol and
optional value.  In the specification below, notice the `gate' inside
of the sublist to prevent backtracking.

     (def-edebug-spec let
       ((&rest
         &or symbolp (gate symbolp &optional form))
        body))

   Edebug uses the following specifications for `defun' and `defmacro'
and the associated argument list and `interactive' specifications.  It
is necessary to handle the expression argument of an interactive form
specially since it is actually evaluated outside of the function body.

     (def-edebug-spec defmacro defun)      ; Indirect ref to `defun' spec
     (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
provided by Edebug 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: lispref.info,  Node: Edebug Options,  Prev: Instrumenting Macro Calls,  Up: Edebug

22.4.17 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.  See *Note Instrumenting::.

 -- User Option: edebug-all-defs
     If non-`nil', normal evaluation of any defining forms (e.g.
     `defun' and `defmacro') will instrument them for Edebug.  This
     applies to `eval-defun', `eval-region', and `eval-current-buffer'.

     Use the command `M-x edebug-all-defs' to toggle the value of this
     variable. You may want to make this variable local to each buffer
     by calling `(make-local-variable 'edebug-all-defs)' in your
     `emacs-lisp-mode-hook'.  See *Note Instrumenting::.

 -- User Option: edebug-all-forms
     If non-`nil', normal evaluation of any forms by `eval-defun',
     `eval-region', and `eval-current-buffer' will instrument them for
     Edebug.

     Use the command `M-x edebug-all-forms' to toggle the value of this
     option.  See *Note Instrumenting::.

 -- User Option: edebug-save-windows
     If non-`nil', save and restore window configuration on Edebug
     calls.  It takes some time to do this, so if your program does not
     care what happens to data about windows, you may want to set this
     variable to `nil'.

     If the value is a list, only the listed windows are saved and
     restored.

     `M-x edebug-toggle-save-windows' may be used to change this
     variable.  This command is bound to `W' in source code buffers.
     See *Note Edebug Display Update::.

 -- User Option: edebug-save-displayed-buffer-points
     If non-`nil', save and restore point in all displayed buffers.
     This is necessary if you are debugging code that changes the point
     of a buffer which is displayed in a non-selected window.  If
     Edebug or the user then selects the window, the buffer's point
     will be changed to the window's point.

     This is an expensive operation since it visits each window and
     therefore each displayed buffer twice for each Edebug activation,
     so it is best to avoid it if you can.  See *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'.  See *Note Edebug Execution Modes::.

 -- User Option: edebug-trace
     Non-`nil' means display a trace of 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.

     The default value is `nil'.

     Also see `edebug-tracing'.  See *Note Tracing::.

 -- User Option: edebug-test-coverage
     If non-`nil', Edebug tests coverage of all expressions debugged.
     This is done by comparing the result of each expression with the
     previous result. Coverage is considered OK if two different
     results are found.  So to sufficiently test the coverage of your
     code, try to execute it under conditions that evaluate all
     expressions more than once, and produce different results for each
     expression.

     Use `M-x edebug-display-freq-count' to display the frequency count
     and coverage information for a definition.  See *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.  See *Note Edebug Execution Modes::.

 -- User Option: edebug-print-length
     If non-`nil', bind `print-length' to this while printing results
     in Edebug.  The default value is `50'.  See *Note Printing in
     Edebug::.

 -- User Option: edebug-print-level
     If non-`nil', bind `print-level' to this while printing results in
     Edebug.  The default value is `50'.

 -- User Option: edebug-print-circle
     If non-`nil', bind `print-circle' to this while printing results
     in Edebug.  The default value is `nil'.

 -- User Option: edebug-on-error
     `debug-on-error' is bound to this while Edebug is active.  See
     *Note Trapping Errors::.

 -- User Option: edebug-on-quit
     `debug-on-quit' is bound to this while Edebug is active.  See
     *Note Trapping Errors::.

 -- User Option: edebug-unwrap-results
     Non-`nil' if Edebug should unwrap results of expressions.  This is
     useful when debugging macros where the results of expressions are
     instrumented expressions.  But don't do this when results might be
     circular or an infinite loop will result.  See *Note Debugging
     Backquote::.

 -- 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.  See
     *Note Global Break Condition::.


File: lispref.info,  Node: Read and Print,  Next: Minibuffers,  Prev: Debugging,  Up: Top

23 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: lispref.info,  Node: Streams Intro,  Next: Input Streams,  Prev: Read and Print,  Up: Read and Print

23.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.  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 inverses.  There are
three kinds of exceptions:

   * Printing can produce text that cannot be read.  For example,
     buffers, windows, frames, subprocesses and markers print into 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: lispref.info,  Node: Input Streams,  Next: Input Functions,  Prev: Streams Intro,  Up: Read and Print

23.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, one character per
     call.  Normally FUNCTION is called with no arguments, and should
     return a character.

     Occasionally FUNCTION is called with one argument (always a
     character).  When that happens, 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".

`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.

`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.

   In Emacs 18, reading a symbol discarded the delimiter terminating the
symbol.  Thus, point would end up at the beginning of `contents' rather
than after `the'.  The Emacs 19 behavior is superior because it
correctly handles input such as `bar(foo)', where the open-parenthesis
that ends one object is needed as the beginning of another object.

   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")))
          => #<marker at 1 in foo>
     (read m)
          => This
     m
          => #<marker at 5 in foo>   ;; 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 <RET>
     ---------- 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 remains 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'.


File: lispref.info,  Node: Input Functions,  Next: Output Streams,  Prev: Input Streams,  Up: Read and Print

23.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 END is also
     supplied, then reading stops 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'.


File: lispref.info,  Node: Output Streams,  Next: Output Functions,  Prev: Input Functions,  Up: Read and Print

23.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.

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 free to do anything at all with the characters it receives.

`t'
     The output characters are displayed in the echo area.

`nil'
     `nil' specified as an output stream means to the value of
     `standard-output' instead; that value is the "default output
     stream", and must be a non-`nil' output stream.

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 mostly one
of how you use a Lisp object, not a distinction of 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 ----------

     m
          => #<marker at 11 in foo>

     (print "More output for foo." m)
          => "More output for foo."

     ---------- Buffer: foo ----------
     "This is t
     "More output for foo."
     he -!-output"
     ---------- Buffer: foo ----------

     m
          => #<marker at 35 in foo>

   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
          => (?\n ?\" ?t ?u ?p ?t ?u ?o ?\  ?e ?h ?t
                     ?\  ?s ?i ?\  ?s ?i ?h ?T ?\" ?\n)

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: lispref.info,  Node: Output Functions,  Next: Output Variables,  Prev: Output Streams,  Up: Read and Print

23.5 Output Functions
=====================

This section describes the Lisp functions for printing Lisp objects.

   Some of the XEmacs 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 it is best to 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 better
to print without quoting.

   Printing a self-referent Lisp object requires an infinite amount of
text.  In certain cases, trying to produce this text leads to a stack
overflow.  XEmacs 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))
               => "#<marker at 2773 in strings.texi>"

     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 String Conversion::, for other ways to
     obtain the printed representation of a Lisp object as a string.


File: lispref.info,  Node: Output Variables,  Prev: Output Functions,  Up: Read and Print

23.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'.

 -- 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', as
     well as everything that uses them.  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-readably
     If non-`nil', then all objects will be printed in a readable form.
     If an object has no readable representation, then an error is
     signalled.  When `print-readably' is true, compiled-function
     objects will be written in `#[...]' form instead of in
     `#<compiled-function [...]>' form, and two-element lists of the
     form `(quote object)' will be written as the equivalent `'object'.
     Do not _set_ this variable; bind it instead.

 -- Variable: print-length
     The value of this variable is the maximum number of elements of a
     list that will be printed.  If a list 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.

     This variable exists in version 19 and later versions.

 -- Variable: print-string-length
     The value of this variable is the maximum number of characters of
     a string that will be printed.  If a string being printed has more
     than this many characters, it is abbreviated with an ellipsis.

 -- Variable: print-gensym
     If non-`nil', then uninterned symbols will be printed specially.
     Uninterned symbols are those which are not present in `obarray',
     that is, those which were made with `make-symbol' or by calling
     `intern' with a second argument.

     When `print-gensym' is true, such symbols will be preceded by
     `#:', which causes the reader to create a new symbol instead of
     interning and returning an existing one.  Beware: The `#:' syntax
     creates a new symbol each time it is seen, so if you print an
     object which contains two pointers to the same uninterned symbol,
     `read' will not duplicate that structure.

     Also, since XEmacs has no real notion of packages, there is no way
     for the printer to distinguish between symbols interned in no
     obarray, and symbols interned in an alternate obarray.

 -- Variable: float-output-format
     This variable holds the format descriptor string that Lisp uses to
     print floats.  This is a `%'-spec like those accepted by `printf'
     in C, but with some restrictions.  It must start with the two
     characters `%.'.  After that comes an integer precision
     specification, and then a letter which controls the format.  The
     letters allowed are `e', `f' and `g'.

        * Use `e' for exponential notation `DIG.DIGITSeEXPT'.

        * Use `f' for decimal point notation `DIGITS.DIGITS'.

        * Use `g' to choose the shorter of those two formats for the
          number at hand.

     The precision in any of these cases is the number of digits
     following the decimal point.  With `f', a precision of 0 means to
     omit the decimal point.  0 is not allowed with `f' or `g'.

     A value of `nil' means to use `%.16g'.

     Regardless of the value of `float-output-format', a floating point
     number will never be printed in such a way that it is ambiguous
     with an integer; that is, a floating-point number will always be
     printed with a decimal point and/or an exponent, even if the
     digits following the decimal point are all zero.  This is to
     preserve read-equivalence.


File: lispref.info,  Node: Minibuffers,  Next: Command Loop,  Prev: Read and Print,  Up: Top

24 Minibuffers
**************

A "minibuffer" is a special buffer that XEmacs 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, 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.
* 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 Misc::           Various customization hooks and variables.


File: lispref.info,  Node: Intro to Minibuffers,  Next: Text from Minibuffer,  Prev: Minibuffers,  Up: Minibuffers

24.1 Introduction to Minibuffers
================================

In most ways, a minibuffer is a normal XEmacs 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 minibuffer's window is normally a single line.  You can 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.

   If a command uses a minibuffer while there is an active minibuffer,
this is 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'.

   Like other buffers, a minibuffer may use any of several local keymaps
(*note Keymaps::); these contain various exit commands and in some cases
completion commands (*note Completion::).

   * `minibuffer-local-map' is for ordinary input (no completion).

   * `minibuffer-local-completion-map' is for permissive completion.

   * `minibuffer-local-must-match-map' is for strict completion and for
     cautious completion.


File: lispref.info,  Node: Text from Minibuffer,  Next: Object from Minibuffer,  Prev: Intro to Minibuffers,  Up: Minibuffers

24.2 Reading Text Strings with the Minibuffer
=============================================

Most often, the minibuffer is used to read text as a string.  It can
also be used to read a Lisp object in textual form.  The most basic
primitive for minibuffer input is `read-from-minibuffer'; it can do
either one.

   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' spec.  *Note
Defining Commands::.

 -- Function: read-from-minibuffer prompt-string &optional
          initial-contents keymap read hist abbrev-table default
     This function is the most general way to get input through 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, if INITIAL-CONTENTS is a string, `read-from-minibuffer'
     inserts it into the minibuffer, leaving point at the end.  The
     minibuffer appears with this text as its contents.

     The value of INITIAL-CONTENTS may also be a cons cell of the form
     `(STRING . POSITION)'.  This means to insert STRING in the
     minibuffer but put point POSITION characters from the beginning,
     rather than at the end.

     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 a default value to make available
     through the history commands.  It should be a string, or `nil'.

     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 ABBREV-TABLE specifies `local-abbrev-table' in the
     minibuffer (*note Standard Abbrev Tables::).

     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::.

     When the user types a command to exit the minibuffer,
     `read-from-minibuffer' uses the text in the minibuffer to produce
     its return value.  Normally it simply makes 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.)

     *Usage note:* The INITIAL-CONTENTS argument and the DEFAULT
     argument are two alternative features for more or less the same
     job.  It does not make sense to use both features in a single call
     to `read-from-minibuffer'.  In general, we recommend using
     DEFAULT, since this permits the user to insert the default value
     when it is wanted, but does not burden the user with deleting it
     from the minibuffer on other occasions.  However, if user is
     supposed to edit default value, INITIAL-CONTENTS may be preferred.

 -- Function: read-string prompt &optional initial history default-value
     This function reads a string from the minibuffer and returns it.
     The arguments PROMPT and INITIAL are used as in
     `read-from-minibuffer'.  The keymap used is `minibuffer-local-map'.

     The optional argument HISTORY, if non-`nil', specifies a history
     list and optionally the initial position in the list.  The optional
     argument DEFAULT-VALUE specifies a default value to return if the
     user enters null input; it should be a string.

     This function is a simplified interface to the
     `read-from-minibuffer' function:

          (read-string PROMPT INITIAL HISTORY DEFAULT)
          ==
          (read-from-minibuffer PROMPT INITIAL nil nil
                                HISTORY nil DEFAULT)))

 -- 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'

    <RET>
          `exit-minibuffer'

    `C-g'
          `abort-recursive-edit'

    `M-n'
          `next-history-element'

    `M-p'
          `previous-history-element'

    `M-r'
          `next-matching-history-element'

    `M-s'
          `previous-matching-history-element'


File: lispref.info,  Node: Object from Minibuffer,  Next: Minibuffer History,  Prev: Text from Minibuffer,  Up: Minibuffers

24.3 Reading Lisp Objects with the Minibuffer
=============================================

This section describes functions for reading Lisp objects with the
minibuffer.

 -- Function: read-expression prompt &optional initial history
          default-value
     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'.

     The optional argument HISTORY, if non-`nil', specifies a history
     list and optionally the initial position in the list.  The optional
     argument DEFAULT-VALUE specifies a default value to return if the
     user enters null input; it should be a string.

     This is a simplified interface to the `read-from-minibuffer'
     function:

          (read-expression PROMPT INITIAL HISTORY DEFAULT-VALUE)
          ==
          (read-from-minibuffer PROMPT INITIAL nil t
                                HISTORY nil DEFAULT-VALUE)

     Here is an example in which we supply the string `"(testing)"' as
     initial input:

          (read-expression
           "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 <RET> immediately to use the initial input as a
     default, or can edit the input.

 -- Function: read-minibuffer prompt &optional initial history
          default-value
     This is a FSF Emacs compatible function.  Use `read-expression'
     instead.

 -- Function: eval-minibuffer prompt &optional initial history
          default-value
     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'.

     The optional argument HISTORY, if non-`nil', specifies a history
     list and optionally the initial position in the list.  The optional
     argument DEFAULT-VALUE specifies a default value to return if the
     user enters null input; it should be a string.

     This function simply evaluates the result of a call to
     `read-expression':

          (eval-minibuffer PROMPT INITIAL)
          ==
          (eval (read-expression PROMPT INITIAL))

 -- Function: edit-and-eval-command prompt form &optional history
     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 <RET> right away would exit the minibuffer and evaluate the
     expression, thus moving point forward one word.
     `edit-and-eval-command' returns `t' in this example.


File: lispref.info,  Node: Minibuffer History,  Next: Completion,  Prev: Object from Minibuffer,  Up: Minibuffers

24.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.

   The basic minibuffer input functions `read-from-minibuffer' and
`completing-read' both accept an optional argument named HIST which is
how you specify the history list.  Here are the possible values:

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 (an integer, counting from
     zero which specifies the most recent element of the history).

     If you specify STARTPOS, then you should also specify that element
     of the history as the initial minibuffer contents, for consistency.

   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.

   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: 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.

 -- Variable: Info-minibuffer-history
     A history list for Info mode's minibuffer.

 -- Variable: Manual-page-minibuffer-history
     A history list for `manual-entry'.

   There are many other minibuffer history lists, defined by various
libraries.  An `M-x apropos' search for `history' should prove fruitful
in discovering them.


File: lispref.info,  Node: Completion,  Next: Yes-or-No Queries,  Prev: Minibuffer History,  Up: Minibuffers

24.5 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 <TAB> (`minibuffer-complete'), Emacs extends the name as far as it
can.

   Standard XEmacs 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.
                             (These are too low level to use the minibuffer.)
* 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.
* Programmed Completion::  Finding the completions for a given file name.


File: lispref.info,  Node: Basic Completion,  Next: Minibuffer Completion,  Prev: Completion,  Up: Completion

24.5.1 Basic Completion Functions
---------------------------------

The two functions `try-completion' and `all-completions' have nothing
in themselves to do with minibuffers.  We describe them in this chapter
so as 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 prefix of all possible
     completions of STRING in COLLECTION.  The value of COLLECTION must
     be an alist, an obarray, or a function that implements a virtual
     set of strings (see below).

     Completion compares STRING against each of the permissible
     completions specified by COLLECTION; if the beginning of the
     permissible completion equals STRING, it matches.  If no
     permissible completions match, `try-completion' returns `nil'.  If
     only one permissible completion matches, and the match is exact,
     then `try-completion' returns `t'.  Otherwise, the value is the
     longest initial sequence common to all the permissible completions
     that match.

     If COLLECTION is an alist (*note Association Lists::), the CARs of
     the alist elements form the set of permissible completions.

     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 the argument PREDICATE is non-`nil', then it must be a function
     of one argument.  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 cons cell from the alist
     (the CAR of which is a string) or else it is a symbol (_not_ a
     symbol name) from the obarray.

     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::.

     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
     This function returns a list of all possible completions of STRING.
     The arguments to this function are the same as those of
     `try-completion'.

     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")

 -- Variable: completion-ignore-case
     If the value of this variable is non-`nil', XEmacs does not
     consider case significant in completion.


File: lispref.info,  Node: Minibuffer Completion,  Next: Completion Commands,  Prev: Basic Completion,  Up: Completion

24.5.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
     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.  If INITIAL is non-`nil',
     `completing-read' inserts it into the minibuffer as part of the
     input.  Then it allows the user to edit the input, providing
     several commands to attempt completion.

     The actual completion is done by passing COLLECTION and PREDICATE
     to the function `try-completion'.  This happens in certain
     commands bound in the local keymaps used for completion.

     If REQUIRE-MATCH is `t', the usual minibuffer exit commands won't
     exit unless the input completes to an element of COLLECTION.  If
     REQUIRE-MATCH is neither `nil' nor `t', then the exit commands
     won't exit unless the input typed is itself an element of
     COLLECTION.  If REQUIRE-MATCH is `nil', the exit commands work
     regardless of the input in the minibuffer.

     However, empty input is always permitted, regardless of the value
     of REQUIRE-MATCH; in that case, `completing-read' returns DEFAULT.
     The value of DEFAULT (if non-`nil') is also available to the user
     through the history commands.

     The user can exit with null input by typing <RET> with an empty
     minibuffer.  Then `completing-read' returns `""'.  This is how the
     user requests whatever default the command uses for the value being
     read.  The user can return using <RET> in this way regardless of
     the value of REQUIRE-MATCH, and regardless of whether the empty
     string is included in COLLECTION.

     The function `completing-read' works by calling `read-expression'.
     It 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::.

     Completion ignores case when comparing the input against the
     possible matches, if the built-in variable
     `completion-ignore-case' is non-`nil'.  *Note Basic Completion::.

     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 `<DEL> <DEL> b <RET>', `completing-read'
     returns `barfoo'.

     The `completing-read' function binds three variables to pass
     information to the commands that actually do completion.  These
     variables are `minibuffer-completion-table',
     `minibuffer-completion-predicate' and
     `minibuffer-completion-confirm'.  For more information about them,
     see *Note Completion Commands::.


File: lispref.info,  Node: Completion Commands,  Next: High-Level Completion,  Prev: Minibuffer Completion,  Up: Completion

24.5.3 Minibuffer Commands That Do Completion
---------------------------------------------

This section describes the keymaps, commands and user options used in
the minibuffer to do completion.

 -- 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'

    <SPC>
          `minibuffer-complete-word'

    <TAB>
          `minibuffer-complete'

     with other characters bound as in `minibuffer-local-map' (*note
     Text from Minibuffer::).

 -- 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'

    <SPC>
          `minibuffer-complete-word'

    <TAB>
          `minibuffer-complete'

    `C-j'
          `minibuffer-complete-and-exit'

    <RET>
          `minibuffer-complete-and-exit'

     with other characters bound as in `minibuffer-local-map'.

 -- Variable: minibuffer-completion-table
     The value of this variable is the alist or obarray 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.

 -- 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.

 -- Variable: minibuffer-completion-confirm
     When the value of this variable is non-`nil', XEmacs asks for
     confirmation of a completion before exiting the minibuffer.  The
     function `minibuffer-complete-and-exit' checks the value of this
     variable before it exits.

 -- 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 &rest cl-keys
     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, or a list of two
     strings, which is printed as if the strings were concatenated.

     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)))

 -- 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.


File: lispref.info,  Node: High-Level Completion,  Next: Reading File Names,  Prev: Completion Commands,  Up: Completion

24.5.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' spec.  *Note
Defining Commands::.

 -- Function: read-buffer prompt &optional default existing
     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 or a buffer.  It is mentioned in
     the prompt, but is not inserted in the minibuffer as initial input.

     If EXISTING is non-`nil', then the name specified must be that of
     an existing buffer.  The usual commands to exit the minibuffer do
     not exit if the text is not valid, and <RET> does completion to
     attempt to find a valid name.  (However, DEFAULT is not checked
     for validity; it is returned, whatever it is, if the user exits
     with the minibuffer empty.)

     In the following example, the user enters `minibuffer.t', and then
     types <RET>.  The argument EXISTING 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 <RET>'.
               => "minibuffer.texi"

 -- Function: read-command prompt &optional default-value
     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-VALUE specifies what to return if the user
     enters null input.  It can be a symbol or a string; if it is a
     string, `read-command' interns it before returning it.  If DEFAULT
     is `nil', that means no default has been specified; then if the
     user enters null input, the return value is `nil'.

          (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 <RET>', then this function returns
     `forward-char'.

     The `read-command' function is a simplified interface to the
     function `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-value
     This function reads the name of a user variable and returns it as a
     symbol.

     The argument DEFAULT-VALUE specifies what to return if the user
     enters null input.  It can be a symbol or a string; if it is a
     string, `read-variable' interns it before returning it.  If
     DEFAULT-VALUE is `nil', that means no default has been specified;
     then if the user enters null input, the return value is `nil'.

          (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 <RET>', `read-variable' returns
     `fill-prefix'.

     This function 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))


File: lispref.info,  Node: Reading File Names,  Next: Programmed Completion,  Prev: High-Level Completion,  Up: Completion

24.5.5 Reading File Names
-------------------------

Here is another high-level completion function, designed for reading a
file name.  It provides special features including automatic insertion
of the default directory.

 -- Function: read-file-name prompt &optional directory default
          existing initial history
     This function reads a file name in the minibuffer, prompting with
     PROMPT and providing completion.  If DEFAULT is non-`nil', then
     the function returns DEFAULT if the user just types <RET>.
     DEFAULT is not checked for validity; it is returned, whatever it
     is, if the user exits with the minibuffer empty.

     If EXISTING is non-`nil', then the user must specify the name of
     an existing file; <RET> performs completion to make the name valid
     if possible, and then refuses to exit if it is not valid.  If the
     value of EXISTING is neither `nil' nor `t', then <RET> also
     requires confirmation after completion.  If EXISTING is `nil',
     then the name of a nonexistent file is acceptable.

     The argument DIRECTORY specifies the directory to use for
     completion of relative file names.  If `insert-default-directory'
     is non-`nil', DIRECTORY is also inserted in the minibuffer as
     initial input.  It defaults to the current buffer's value of
     `default-directory'.

     If you specify INITIAL, that is an initial file name to insert in
     the buffer (after DIRECTORY, if that is inserted).  In this case,
     point goes at the beginning of INITIAL.  The default for INITIAL
     is `nil'--don't insert any file name.  To see what INITIAL does,
     try the command `C-x C-v'.

     Here is an example:

          (read-file-name "The file is ")

          ;; After evaluation of the preceding expression,
          ;;   the following appears in the minibuffer:

          ---------- Buffer: Minibuffer ----------
          The file is /gp/gnu/elisp/-!-
          ---------- Buffer: Minibuffer ----------

     Typing `manual <TAB>' results in the following:

          ---------- Buffer: Minibuffer ----------
          The file is /gp/gnu/elisp/manual.texi-!-
          ---------- Buffer: Minibuffer ----------

     If the user types <RET>, `read-file-name' returns the file name as
     the string `"/gp/gnu/elisp/manual.texi"'.

 -- User Option: insert-default-directory
     This variable is used by `read-file-name'.  Its value controls
     whether `read-file-name' starts by placing the name of the default
     directory in the minibuffer, plus the initial file name if any.
     If the value of this variable is `nil', then `read-file-name' does
     not place any initial input in the minibuffer (unless you specify
     initial input with the INITIAL argument).  In that case, the
     default directory is still used for completion of relative file
     names, but is not displayed.

     For example:

          ;; Here the minibuffer starts out with the default directory.
          (let ((insert-default-directory t))
            (read-file-name "The file is "))

          ---------- Buffer: Minibuffer ----------
          The file is ~lewis/manual/-!-
          ---------- Buffer: Minibuffer ----------

          ;; Here the minibuffer is empty and only the prompt
          ;;   appears on its line.
          (let ((insert-default-directory nil))
            (read-file-name "The file is "))

          ---------- Buffer: Minibuffer ----------
          The file is -!-
          ---------- Buffer: Minibuffer ----------


File: lispref.info,  Node: Programmed Completion,  Prev: Reading File Names,  Up: Completion

24.5.6 Programmed Completion
----------------------------

Sometimes it is not possible to create an alist or an obarray
containing all the intended possible completions.  In such a case, you
can supply your own function to compute the completion of a given
string.  This is called "programmed completion".

   To use this feature, pass a symbol with a function definition as the
COLLECTION argument to `completing-read'.  The function
`completing-read' arranges to pass your completion function along to
`try-completion' and `all-completions', which will then let your
function do all the work.

   The completion function should accept three arguments:

   * The string to be completed.

   * The predicate function to filter possible matches, or `nil' if
     none.  Your function should call the predicate for each possible
     match, and ignore the possible match if the predicate returns
     `nil'.

   * A flag specifying the type of operation.

   There are three flag values for three operations:

   * `nil' specifies `try-completion'.  The completion function should
     return the completion of the specified string, or `t' if the
     string is a unique and exact match already, or `nil' if the string
     matches no possibility.

     If the string is an exact match for one possibility, but also
     matches other longer possibilities, the function should return the
     string, not `t'.

   * `t' specifies `all-completions'.  The completion function should
     return a list of all possible completions of the specified string.

   * `lambda' specifies a test for an exact match.  The completion
     function should return `t' if the specified string is an exact
     match for some possibility; `nil' otherwise.

   It would be consistent and clean for completion functions to allow
lambda expressions (lists that are functions) as well as function
symbols as COLLECTION, but this is impossible.  Lists as completion
tables are already assigned another meaning--as alists.  It would be
unreliable to fail to handle an alist normally because it is also a
possible function.  So you must arrange for any function you wish to
use for completion to be encapsulated in a symbol.

   Emacs uses programmed completion when completing file names.  *Note
File Name Completion::.


File: lispref.info,  Node: Yes-or-No Queries,  Next: Multiple Queries,  Prev: Completion,  Up: Minibuffers

24.6 Yes-or-No Queries
======================

This section describes functions used to ask the user a yes-or-no
question.  The function `y-or-n-p' can be answered with a single
character; it is useful for questions where an inadvertent wrong answer
will not have serious consequences.  `yes-or-no-p' is suitable for more
momentous questions, since it requires three or four characters to
answer.  Variations of these functions can be used to ask a yes-or-no
question using a dialog box, or optionally using one.

   If either of these functions is called in a command that was invoked
using the mouse, then it uses a dialog box or pop-up menu to ask the
question.  Otherwise, it uses keyboard input.

   Strictly speaking, `yes-or-no-p' uses the minibuffer and `y-or-n-p'
does not; but it seems best to describe them together.

 -- Function: y-or-n-p prompt
     This function asks the user a question, expecting input in the echo
     area.  It returns `t' if the user types `y', `nil' if the user
     types `n'.  This function also accepts <SPC> to mean yes and <DEL>
     to mean no.  It accepts `C-]' to mean "quit", like `C-g', because
     the question might look like a minibuffer and for that reason the
     user might try to use `C-]' to get out.  The answer is a single
     character, with no <RET> needed to terminate it.  Upper and lower
     case are equivalent.

     "Asking the question" means printing PROMPT in the echo area,
     followed by the string `(y or n) '.  If the input is not one of
     the expected answers (`y', `n', `<SPC>', `<DEL>', or something
     that quits), the function responds `Please answer y or n.', and
     repeats the request.

     This function does not actually use the minibuffer, since it does
     not allow editing of the answer.  It actually uses the echo area
     (*note The Echo Area::), which uses the same screen space as the
     minibuffer.  The cursor moves to the echo area while the question
     is being asked.

     The answers and their meanings, even `y' and `n', are not
     hardwired.  The keymap `query-replace-map' specifies them.  *Note
     Search and Replace::.

     In the following example, the user first types `q', which is
     invalid.  At the next prompt the user types `y'.

          (y-or-n-p "Do you need a lift? ")

          ;; After evaluation of the preceding expression,
          ;;   the following prompt appears in the echo area:

          ---------- Echo area ----------
          Do you need a lift? (y or n)
          ---------- Echo area ----------

          ;; If the user then types `q', the following appears:

          ---------- Echo area ----------
          Please answer y or n.  Do you need a lift? (y or n)
          ---------- Echo area ----------

          ;; When the user types a valid answer,
          ;;   it is displayed after the question:

          ---------- Echo area ----------
          Do you need a lift? (y or n) y
          ---------- Echo area ----------

     We show successive lines of echo area messages, but only one
     actually appears on the screen at a time.

 -- Function: yes-or-no-p prompt
     This function asks the user a question, expecting input in the
     minibuffer.  It returns `t' if the user enters `yes', `nil' if the
     user types `no'.  The user must type <RET> to finalize the
     response.  Upper and lower case are equivalent.

     `yes-or-no-p' starts by displaying PROMPT in the echo area,
     followed by `(yes or no) '.  The user must type one of the
     expected responses; otherwise, the function responds `Please answer
     yes or no.', waits about two seconds and repeats the request.

     `yes-or-no-p' requires more work from the user than `y-or-n-p' and
     is appropriate for more crucial decisions.

     Here is an example:

          (yes-or-no-p "Do you really want to remove everything? ")

          ;; After evaluation of the preceding expression,
          ;;   the following prompt appears,
          ;;   with an empty minibuffer:

          ---------- Buffer: minibuffer ----------
          Do you really want to remove everything? (yes or no)
          ---------- Buffer: minibuffer ----------

     If the user first types `y <RET>', which is invalid because this
     function demands the entire word `yes', it responds by displaying
     these prompts, with a brief pause between them:

          ---------- Buffer: minibuffer ----------
          Please answer yes or no.
          Do you really want to remove everything? (yes or no)
          ---------- Buffer: minibuffer ----------

 -- Function: yes-or-no-p-dialog-box prompt
     This function asks the user a "y or n" question with a popup dialog
     box.  It returns `t' if the answer is "yes".  PROMPT is the string
     to display to ask the question.

   The following functions ask a question either in the minibuffer or a
dialog box, depending on whether the last user event (which presumably
invoked this command) was a keyboard or mouse event.  When XEmacs is
running on a window system, the functions `y-or-n-p' and `yes-or-no-p'
are replaced with the following functions, so that menu items bring up
dialog boxes instead of minibuffer questions.

 -- Function: y-or-n-p-maybe-dialog-box prompt
     This function asks user a "y or n" question, using either a dialog
     box or the minibuffer, as appropriate.

 -- Function: yes-or-no-p-maybe-dialog-box prompt
     This function asks user a "yes or no" question, using either a
     dialog box or the minibuffer, as appropriate.


File: lispref.info,  Node: Multiple Queries,  Next: Reading a Password,  Prev: Yes-or-No Queries,  Up: Minibuffers

24.7 Asking Multiple Y-or-N Questions
=====================================

When you have a series of similar questions to ask, such as "Do you
want to save this buffer" for each buffer in turn, you should use
`map-y-or-n-p' to ask the collection of questions, rather than asking
each question individually.  This gives the user certain convenient
facilities such as the ability to answer the whole series at once.

 -- Function: map-y-or-n-p prompter actor list &optional help
          action-alist
     This function, new in Emacs 19, asks the user a series of
     questions, reading a single-character answer in the echo area for
     each one.

     The value of LIST specifies the objects to ask questions about.
     It should be either a list of objects or a generator function.  If
     it is a function, it should expect no arguments, and should return
     either the next object to ask about, or `nil' meaning stop asking
     questions.

     The argument PROMPTER specifies how to ask each question.  If
     PROMPTER is a string, the question text is computed like this:

          (format PROMPTER OBJECT)

     where OBJECT is the next object to ask about (as obtained from
     LIST).

     If not a string, PROMPTER should be a function of one argument
     (the next object to ask about) and should return the question
     text.  If the value is a string, that is the question to ask the
     user.  The function can also return `t' meaning do act on this
     object (and don't ask the user), or `nil' meaning ignore this
     object (and don't ask the user).

     The argument ACTOR says how to act on the answers that the user
     gives.  It should be a function of one argument, and it is called
     with each object that the user says yes for.  Its argument is
     always an object obtained from LIST.

     If the argument HELP is given, it should be a list of this form:

          (SINGULAR PLURAL ACTION)

     where SINGULAR is a string containing a singular noun that
     describes the objects conceptually being acted on, PLURAL is the
     corresponding plural noun, and ACTION is a transitive verb
     describing what ACTOR does.

     If you don't specify HELP, the default is `("object" "objects"
     "act on")'.

     Each time a question is asked, the user may enter `y', `Y', or
     <SPC> to act on that object; `n', `N', or <DEL> to skip that
     object; `!' to act on all following objects; <ESC> or `q' to exit
     (skip all following objects); `.' (period) to act on the current
     object and then exit; or `C-h' to get help.  These are the same
     answers that `query-replace' accepts.  The keymap
     `query-replace-map' defines their meaning for `map-y-or-n-p' as
     well as for `query-replace'; see *Note Search and Replace::.

     You can use ACTION-ALIST to specify additional possible answers
     and what they mean.  It is an alist of elements of the form `(CHAR
     FUNCTION HELP)', each of which defines one additional answer.  In
     this element, CHAR is a character (the answer); FUNCTION is a
     function of one argument (an object from LIST); HELP is a string.

     When the user responds with CHAR, `map-y-or-n-p' calls FUNCTION.
     If it returns non-`nil', the object is considered "acted upon",
     and `map-y-or-n-p' advances to the next object in LIST.  If it
     returns `nil', the prompt is repeated for the same object.

     If `map-y-or-n-p' is called in a command that was invoked using the
     mouse--more precisely, if `last-nonmenu-event' (*note Command Loop
     Info::) is either `nil' or a list--then it uses a dialog box or
     pop-up menu to ask the question.  In this case, it does not use
     keyboard input or the echo area.  You can force use of the mouse
     or use of keyboard input by binding `last-nonmenu-event' to a
     suitable value around the call.

     The return value of `map-y-or-n-p' is the number of objects acted
     on.


File: lispref.info,  Node: Reading a Password,  Next: Minibuffer Misc,  Prev: Multiple Queries,  Up: Minibuffers

24.8 Reading a Password
=======================

To read a password to pass to another program, you can use the function
`read-passwd'.

 -- Function: read-passwd prompt &optional confirm default
     This function reads a password, prompting with PROMPT.  It does
     not echo the password as the user types it; instead, it echoes `.'
     for each character in the password.

     The optional argument CONFIRM, if non-`nil', says to read the
     password twice and insist it must be the same both times.  If it
     isn't the same, the user has to type it over and over until the
     last two times match.

     The optional argument DEFAULT specifies the default password to
     return if the user enters empty input.  It is translated to `.'
     and inserted in the minibuffer. If DEFAULT is `nil', then
     `read-passwd' returns the null string in that case.

 -- User Option: passwd-invert-frame-when-keyboard-grabbed
     If non-`nil', swap the foreground and background colors of all
     faces while reading a password.  Default values is `t', unless
     feature `infodock' is provided.

 -- User Option: passwd-echo
     This specifies the character echoed when typing a password.  When
     `nil', nothing is echoed.


File: lispref.info,  Node: Minibuffer Misc,  Prev: Reading a Password,  Up: Minibuffers

24.9 Minibuffer Miscellany
==========================

This section describes some basic functions and variables related to
minibuffers.

 -- Command: exit-minibuffer
     This command exits the active minibuffer.  It is normally bound to
     keys in minibuffer local keymaps.

 -- Command: self-insert-and-exit
     This command exits the active minibuffer after inserting the last
     character typed on the keyboard (found in `last-command-char';
     *note Command Loop Info::).

 -- Command: previous-history-element n
     This command replaces the minibuffer contents with the value of the
     Nth previous (older) history element.

 -- Command: next-history-element n
     This command replaces the minibuffer contents with the value of the
     Nth more recent history element.

 -- Command: previous-matching-history-element pattern
     This command replaces the minibuffer contents with the value of the
     previous (older) history element that matches PATTERN (a regular
     expression).

 -- Command: next-matching-history-element pattern
     This command replaces the minibuffer contents with the value of
     the next (newer) history element that matches PATTERN (a regular
     expression).

 -- Function: minibuffer-prompt
     This function returns the prompt string of the currently active
     minibuffer.  If no minibuffer is active, it returns `nil'.

 -- Function: minibuffer-prompt-width
     This function returns the display width of the prompt string of the
     currently active minibuffer.  If no minibuffer is active, it
     returns 0.

 -- Variable: minibuffer-setup-hook
     This is a normal hook that is run whenever the minibuffer is
     entered.  *Note Hooks::.

 -- Variable: minibuffer-exit-hook
     This is a normal hook that is run whenever the minibuffer is
     exited.  *Note Hooks::.

 -- Variable: minibuffer-help-form
     The current value of this variable is used to rebind `help-form'
     locally inside the minibuffer (*note Help Functions::).

 -- Function: active-minibuffer-window
     This function returns the currently active minibuffer window, or
     `nil' if none is currently active.

 -- Function: minibuffer-window &optional frame
     This function returns the minibuffer window used for frame FRAME.
     If FRAME is `nil', that stands for the current frame.  Note that
     the minibuffer window used by a frame need not be part of that
     frame--a frame that has no minibuffer of its own necessarily uses
     some other frame's minibuffer window.

 -- Function: window-minibuffer-p &optional window
     This function returns non-`nil' if WINDOW is a minibuffer window.

   It is not correct to determine whether a given window is a
minibuffer by comparing it with the result of `(minibuffer-window)',
because there can be more than one minibuffer window if there is more
than one frame.

 -- Function: minibuffer-window-active-p window
     This function returns non-`nil' if WINDOW, assumed to be a
     minibuffer window, is currently active.

 -- Variable: minibuffer-scroll-window
     If the value of this variable is non-`nil', it should be a window
     object.  When the function `scroll-other-window' is called in the
     minibuffer, it scrolls this window.

   Finally, some functions and variables deal with recursive minibuffers
(*note Recursive Editing::):

 -- Function: minibuffer-depth
     This function returns the current depth of activations of the
     minibuffer, a nonnegative integer.  If no minibuffers are active,
     it returns zero.

 -- User Option: enable-recursive-minibuffers
     If this variable is non-`nil', you can invoke commands (such as
     `find-file') that use minibuffers even while the minibuffer window
     is active.  Such invocation produces a recursive editing level for
     a new minibuffer.  The outer-level minibuffer is invisible while
     you are editing the inner one.

     This variable only affects invoking the minibuffer while the
     minibuffer window is selected.   If you switch windows while in the
     minibuffer, you can always invoke minibuffer commands while some
     other window is selected.

   In FSF Emacs 19, if a command name has a property
`enable-recursive-minibuffers' that is non-`nil', then the command can
use the minibuffer to read arguments even if it is invoked from the
minibuffer.  The minibuffer command `next-matching-history-element'
(normally `M-s' in the minibuffer) uses this feature.

   This is not implemented in XEmacs because it is a kludge.  If you
want to explicitly set the value of `enable-recursive-minibuffers' in
this fashion, just use an evaluated interactive spec and bind
`enable-recursive-minibuffers' while reading from the minibuffer.  See
the definition of `next-matching-history-element' in `lisp/minibuf.el'.


File: lispref.info,  Node: Command Loop,  Next: Keymaps,  Prev: Minibuffers,  Up: Top

25 Command Loop
***************

When you run XEmacs, it enters the "editor command loop" almost
immediately.  This loop reads events, executes their definitions, and
displays the results.  In this chapter, we describe how these things
are done, and the subroutines that allow Lisp programs to do them.

* Menu:

* Command Overview::    How the command loop reads commands.
* Defining Commands::   Specifying how a function should read arguments.
* Interactive Call::    Calling a command, so that it will read arguments.
* Command Loop Info::   Variables set by the command loop for you to examine.
* Events::		What input looks like when you read it.
* Reading Input::       How to read input events from the keyboard or mouse.
* Waiting::             Waiting for user input or elapsed time.
* Quitting::            How C-g works.  How to catch or defer quitting.
* Prefix Command Arguments::    How the commands to set prefix args work.
* Recursive Editing::   Entering a recursive edit,
                          and why you usually shouldn't.
* Disabling Commands::  How the command loop handles disabled commands.
* Command History::     How the command history is set up, and how accessed.
* Keyboard Macros::     How keyboard macros are implemented.


File: lispref.info,  Node: Command Overview,  Next: Defining Commands,  Prev: Command Loop,  Up: Command Loop

25.1 Command Loop Overview
==========================

The command loop in XEmacs is a standard event loop, reading events one
at a time with `next-event' and handling them with `dispatch-event'.
An event is typically a single user action, such as a keypress, mouse
movement, or menu selection; but they can also be notifications from
the window system, informing XEmacs that (for example) part of its
window was just uncovered and needs to be redrawn.  *Note Events::.
Pending events are held in a first-in, first-out list called the "event
queue": events are read from the head of the list, and newly arriving
events are added to the tail.  In this way, events are always processed
in the order in which they arrive.

   `dispatch-event' does most of the work of handling user actions.
The first thing it must do is put the events together into a key
sequence, which is a sequence of events that translates into a command.
It does this by consulting the active keymaps, which specify what the
valid key sequences are and how to translate them into commands.  *Note
Key Lookup::, for information on how this is done.  The result of the
translation should be a keyboard macro or an interactively callable
function.  If the key is `M-x', then it reads the name of another
command, which it then calls.  This is done by the command
`execute-extended-command' (*note Interactive Call::).

   To execute a command requires first reading the arguments for it.
This is done by calling `command-execute' (*note Interactive Call::).
For commands written in Lisp, the `interactive' specification says how
to read the arguments.  This may use the prefix argument (*note Prefix
Command Arguments::) or may read with prompting in the minibuffer
(*note Minibuffers::).  For example, the command `find-file' has an
`interactive' specification which says to read a file name using the
minibuffer.  The command's function body does not use the minibuffer;
if you call this command from Lisp code as a function, you must supply
the file name string as an ordinary Lisp function argument.

   If the command is a string or vector (i.e., a keyboard macro) then
`execute-kbd-macro' is used to execute it.  You can call this function
yourself (*note Keyboard Macros::).

   To terminate the execution of a running command, type `C-g'.  This
character causes "quitting" (*note Quitting::).

 -- Variable: pre-command-hook
     The editor command loop runs this normal hook before each command.
     At that time, `this-command' contains the command that is about to
     run, and `last-command' describes the previous command.  *Note
     Hooks::.

 -- Variable: post-command-hook
     The editor command loop runs this normal hook after each command.
     (In FSF Emacs, it is also run when the command loop is entered, or
     reentered after an error or quit.)  At that time, `this-command'
     describes the command that just ran, and `last-command' describes
     the command before that.  *Note Hooks::.

   Quitting is suppressed while running `pre-command-hook' and
`post-command-hook'.  If an error happens while executing one of these
hooks, it terminates execution of the hook, but that is all it does.


File: lispref.info,  Node: Defining Commands,  Next: Interactive Call,  Prev: Command Overview,  Up: Command Loop

25.2 Defining Commands
======================

A Lisp function becomes a command when its body contains, at top level,
a form that calls the special operator `interactive'.  This operator
does nothing when actually executed, but its presence serves as a flag
to indicate that interactive calling is permitted.  Its argument
controls the reading of arguments for an interactive call.

* Menu:

* Using Interactive::     General rules for `interactive'.
* Interactive Codes::     The standard letter-codes for reading arguments
                             in various ways.
* Interactive Examples::  Examples of how to read interactive arguments.


File: lispref.info,  Node: Using Interactive,  Next: Interactive Codes,  Prev: Defining Commands,  Up: Defining Commands

25.2.1 Using `interactive'
--------------------------

This section describes how to write the `interactive' form that makes a
Lisp function an interactively-callable command.

 -- Special Operator: interactive arg-descriptor
     This special operator declares that the function in which it
     appears is a command, and that it may therefore be called
     interactively (via `M-x' or by entering a key sequence bound to
     it).  The argument ARG-DESCRIPTOR declares how to compute the
     arguments to the command when the command is called interactively.

     A command may be called from Lisp programs like any other
     function, but then the caller supplies the arguments and
     ARG-DESCRIPTOR has no effect.

     The `interactive' form has its effect because the command loop
     (actually, its subroutine `call-interactively') scans through the
     function definition looking for it, before calling the function.
     Once the function is called, all its body forms including the
     `interactive' form are executed, but at this time `interactive'
     simply returns `nil' without even evaluating its argument.

   There are three possibilities for the argument ARG-DESCRIPTOR:

   * It may be omitted or `nil'; then the command is called with no
     arguments.  This leads quickly to an error if the command requires
     one or more arguments.

   * It may be a Lisp expression that is not a string; then it should
     be a form that is evaluated to get a list of arguments to pass to
     the command.  

     If this expression reads keyboard input (this includes using the
     minibuffer), keep in mind that the integer value of point or the
     mark before reading input may be incorrect after reading input.
     This is because the current buffer may be receiving subprocess
     output; if subprocess output arrives while the command is waiting
     for input, it could relocate point and the mark.

     Here's an example of what _not_ to do:

          (interactive
           (list (region-beginning) (region-end)
                 (read-string "Foo: " nil 'my-history)))

     Here's how to avoid the problem, by examining point and the mark
     only after reading the keyboard input:

          (interactive
           (let ((string (read-string "Foo: " nil 'my-history)))
             (list (region-beginning) (region-end) string)))

   * It may be a string; then its contents should consist of a code
     character followed by a prompt (which some code characters use and
     some ignore).  The prompt ends either with the end of the string
     or with a newline.  Here is a simple example:

          (interactive "bFrobnicate buffer: ")

     The code letter `b' says to read the name of an existing buffer,
     with completion.  The buffer name is the sole argument passed to
     the command.  The rest of the string is a prompt.

     If there is a newline character in the string, it terminates the
     prompt.  If the string does not end there, then the rest of the
     string should contain another code character and prompt,
     specifying another argument.  You can specify any number of
     arguments in this way.

     The prompt string can use `%' to include previous argument values
     (starting with the first argument) in the prompt.  This is done
     using `format' (*note Formatting Strings::).  For example, here is
     how you could read the name of an existing buffer followed by a
     new name to give to that buffer:

          (interactive "bBuffer to rename: \nsRename buffer %s to: ")

     If the first character in the string is `*', then an error is
     signaled if the buffer is read-only.

     If the first character in the string is `@', and if the key
     sequence used to invoke the command includes any mouse events, then
     the window associated with the first of those events is selected
     before the command is run.

     If the first character in the string is `_', then this command will
     not cause the region to be deactivated when it completes; that is,
     `zmacs-region-stays' will be set to `t' when the command exits
     successfully.

     You can use `*', `@', and `_' together; the order does not matter.
     Actual reading of arguments is controlled by the rest of the
     prompt string (starting with the first character that is not `*',
     `@', or `_').

 -- Function: function-interactive function
     This function retrieves the interactive specification of FUNCTION,
     which may be any funcallable object.  The specification will be
     returned as the list of the symbol `interactive' and the specs.  If
     FUNCTION is not interactive, `nil' will be returned.

