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: String Properties,  Next: Formatting Strings,  Prev: Modifying Strings,  Up: Strings and Characters

10.9 String Properties
======================

Just as with symbols, extents, faces, and glyphs, you can attach
additional information to strings in the form of "string properties".
These differ from text properties, which are logically attached to
particular characters in the string, and from properties on extents in
the string, which are attached to ranges of characters in the string.
In particular, a text or extent property that covers the whole string
is not the same as a string property.

   To attach a property to a string, use `put'.  To retrieve a property
from a string, use `get'.  You can also use `remprop' to remove a
property from a string and `object-plist' to retrieve a list of all the
properties of a string.


File: lispref.info,  Node: Formatting Strings,  Next: Character Case,  Prev: String Properties,  Up: Strings and Characters

10.10 Formatting Strings
========================

"Formatting" means constructing a string by substitution of computed
values at various places in a constant string.  This string controls
how the other values are printed as well as where they appear; it is
called a "format string".

   Formatting is often useful for computing messages to be displayed.
In fact, the functions `message' and `error' provide the same
formatting feature described here; they differ from `format' only in
how they use the result of formatting.

 -- Function: format control-string &rest objects
     This function returns a new string that is made by copying those
     parts of CONTROL-STRING that are not format specifications
     literally, and replacing any format specifications seen in the
     original with encodings of the corresponding OBJECTS, in order.
     The arguments OBJECTS are the computed values to be formatted.

 -- Function: format-into stream control-string &rest objects
     This function accepts CONTROL-STRING and OBJECTS in the same way
     as `format'. It takes an additional argument STREAM, a valid
     output stream, *note Output Functions::.  It writes the output
     string into that stream and returns STREAM. See the function
     `make-string-output-stream' for one way of buffering output to be
     accessed later.  This function is analagous to Common Lisp's
     `format', but note that supplying a STREAM of `nil' means the text
     will be printed to the minibuffer rather than into a string that
     is returned.

   A format specification is a sequence of characters beginning with a
`%'.  Thus, if there is a `%d' in STRING, the `format' function
replaces it with the printed representation of one of the values to be
formatted (one of the arguments OBJECTS).  For example:

     (format "The value of fill-column is %d." fill-column)
          => "The value of fill-column is 72."

   If STRING contains more than one format specification, the format
specifications correspond with successive values from OBJECTS.  Thus,
the first format specification in STRING uses the first such value, the
second format specification uses the second such value, and so on.  Any
extra format specifications (those for which there are no corresponding
values) cause unpredictable behavior.  Any extra values to be formatted
are ignored.

   Any extents in STRING or in OBJECTS are carried over into the output
string, as with `concat' *note Creating Strings::.  If the format
specification makes the output string longer than STRING, the new
characters are inserted before the `%' of each format specification,
and whether extent info applies to them depends on the `start-open' and
`end-open' properties of those extents that abut the spec. *note Extent
Endpoints::. If you are not curious about extent endpoints and their
implications, but still would like to use extents in format sequences,
have your extents apply either to the entirety of a `%'-sequence, or
not at all.

   Certain format specifications require values of particular types.
However, no error is signaled if the value actually supplied fails to
have the expected type.  Instead, the output is likely to be
meaningless.

   Here is a table of valid format specifications:

`%s'
     Replace the specification with the printed representation of the
     object, made without quoting.  Thus, strings are represented by
     their contents alone, with no `"' characters, and symbols appear
     without `\' characters.  This is equivalent to printing the object
     with `princ'.

     If there is no corresponding object, the empty string is used.

`%S'
     Replace the specification with the printed representation of the
     object, made with quoting.  Thus, strings are enclosed in `"'
     characters, and `\' characters appear where necessary before
     special characters.  This is equivalent to printing the object
     with `prin1'.

     If there is no corresponding object, the empty string is used.

`%o'
     Replace the specification with the base-eight representation of a
     signed rational, that is, an integer or a ratio.

`%d'
`%i'
     Replace the specification with the base-ten representation of a
     signed rational.

`%x'
     Replace the specification with the base-sixteen representation of a
     signed rational, using lowercase letters.

`%X'
     Replace the specification with the base-sixteen representation of a
     signed rational, using uppercase letters.

`%b'
     Replace the specification with the base-two representation of a
     signed rational.

`%c'
     Replace the specification with the character which is the value
     given.

`%e'
     Replace the specification with the exponential notation for a
     floating point number (e.g. `7.85200e+03').

`%f'
     Replace the specification with the decimal-point notation for a
     floating point number.

`%g'
     Replace the specification with notation for a floating point
     number, using a "pretty format".  Either exponential notation or
     decimal-point notation will be used (usually whichever is
     shorter), and trailing zeroes are removed from the fractional part.

`%%'
     A single `%' is placed in the string.  This format specification is
     unusual in that it does not use a value.  For example, `(format "%%
     %d" 30)' returns `"% 30"'.

`%u'
     This is syntactic sugar for `%ud', and means to replace the
     specification with the base-ten representation of an unsigned
     rational. See below for the documentation of `u', the unsigned
     modifier.

   Any other format character results in an `Invalid format operation'
error.

   Here are several examples:

     (format "The name of this buffer is %s." (buffer-name))
          => "The name of this buffer is strings.texi."

     (format "The buffer object prints as %s." (current-buffer))
          => "The buffer object prints as #<buffer strings.texi>."

     (format "The octal value of %d is %o,
              and the hex value is %x." 18 18 18)
          => "The octal value of 18 is 22,
              and the hex value is 12."

   There are many additional flags and specifications that can occur
between the `%' and the format character, in the following order:

  1. An optional repositioning specification, which is a positive
     integer followed by a `$'.

  2. Zero or more of the optional flag characters `-', `+', ` ', `0',
     and `#'.

  3. An asterisk (`*', meaning that the field width is now assumed to
     have been specified as an argument.

  4. An optional minimum field width.

  5. An optional precision, preceded by a `.' character.

   A "repositioning" specification changes which argument to `format'
is used by the current and all following format specifications.
Normally the first specification uses the first argument, the second
specification uses the second argument, etc.  Using a repositioning
specification, you can change this.  By placing a number N followed by
a `$' between the `%' and the format character, you cause the
specification to use the Nth argument.  The next specification will use
the N+1'th argument, etc.

   For example:

     (format "Can't find file `%s' in directory `%s'."
             "ignatius.c" "loyola/")
          => "Can't find file `ignatius.c' in directory `loyola/'."

     (format "In directory `%2$s', the file `%1$s' was not found."
             "ignatius.c" "loyola/")
          => "In directory `loyola/', the file `ignatius.c' was not found."

     (format
         "The numbers %d and %d are %1$x and %x in hex and %1$o and %o in octal."
         37 12)
     => "The numbers 37 and 12 are 25 and c in hex and 45 and 14 in octal."

   As you can see, this lets you reprocess arguments more than once or
reword a format specification (thereby moving the arguments around)
without having to actually reorder the arguments.  This is especially
useful in translating messages from one language to another: Different
languages use different word orders, and this sometimes entails changing
the order of the arguments.  By using repositioning specifications,
this can be accomplished without having to embed knowledge of particular
languages into the location in the program's code where the message is
displayed.

   All the specification characters allow an optional numeric prefix
between the `%' and the character, and following any repositioning
specification or flag.  The optional numeric prefix defines the minimum
width for the object.  If the printed representation of the object
contains fewer characters than this, then it is padded.  The padding is
normally on the left, but will be on the right if the `-' flag
character is given.  The padding character is normally a space, but if
the `0' flag character is given, zeroes are used for padding.  See also
the `!' flag character to specify an arbitrary character.

     (format "%06d is padded on the left with zeroes" 123)
          => "000123 is padded on the left with zeroes"

     (format "%-6d is padded on the right" 123)
          => "123    is padded on the right"

   `format' never truncates an object's printed representation, no
matter what width you specify.  Thus, you can use a numeric prefix to
specify a minimum spacing between columns with no risk of losing
information.

   In the following three examples, `%7s' specifies a minimum width of
7.  In the first case, the string inserted in place of `%7s' has only 3
letters, so 4 blank spaces are inserted for padding.  In the second
case, the string `"specification"' is 13 letters wide but is not
truncated.  In the third case, the padding is on the right.

     (format "The word `%7s' actually has %d letters in it."
             "foo" (length "foo"))
          => "The word `    foo' actually has 3 letters in it."

     (format "The word `%7s' actually has %d letters in it."
             "specification" (length "specification"))
          => "The word `specification' actually has 13 letters in it."

     (format "The word `%-7s' actually has %d letters in it."
             "foo" (length "foo"))
          => "The word `foo    ' actually has 3 letters in it."

   After any minimum field width, a precision may be specified by
preceding it with a `.' character.  The precision specifies the minimum
number of digits to appear in `%d', `%i', `%o', `%x', and `%X'
conversions (the number is padded on the left with zeroes as
necessary); the number of digits printed after the decimal point for
`%f', `%e', and `%E' conversions; the number of significant digits
printed in `%g' and `%G' conversions; and the maximum number of
non-padding characters printed in `%s' and `%S' conversions.  The
default precision for floating-point conversions is six.

   The other flag characters have the following meanings:

   * The ` ' flag means prefix non-negative numbers with a space.

   * The `+' flag means prefix non-negative numbers with a plus sign.

   * The `#' flag means print numbers in an alternate, more verbose
     format: octal numbers begin with zero; hex numbers begin with a
     `0x' or `0X'; a decimal point is printed in `%f', `%e', and `%E'
     conversions even if no numbers are printed after it; and trailing
     zeroes are not omitted in `%g' and `%G' conversions.

   * The `&' flag is analogous to the `#' flag for rationals (integers
     and ratios).  Instead of the C-like syntax described for `#',
     however, it means to print numbers preceded by `#x' (when the `x'
     conversion character is specified), by `#o', or by `#b', when the
     `o' or `b' conversion characters are specified.  This is the usual
     Common Lisp syntax for rationals in the corresponding base.

   * The `!' flag takes a single character immediately following it, and
     specifies that character be used instead of space for padding.

   * The `~' flag means that any sign character should be placed before
     the radix specifier with `#' or `&', and is the default when `&'
     is also specified.


   An optional length modifier may be specified after any minimum field
width or precision.  The length modifiers available are `hh', `h', `l'
(ell), `ll' \(ell-ell), `z'.  These mean that a following integer
conversion character will print an integer truncated to eight, sixteen,
thirty-two, sixty-four, or (once more) thirty-two bits, respectively.
Note that this contrasts with ANSI C, where the bit length depends on
the machine choices for the bit width of the various fixed-width
integer types.  The `z' modifier is redundant in the formatting
available to Lisp but is used in the formatting made available to the
XEmacs C code.

   An optional unsigned modifier, the character `u', may be specified
after any length modifier and before a rational conversion character.
This specifies that the following rational conversion is to treat its
argument as unsigned.  With no length modifier specified, or for a
ratio, this simply means that `format' will error if the corresponding
argument is negative.  If a length modifier is specified, `format' will
print a positive integer reflecting the twos' complement representation
of the argument in the given number of bits.  If there is no following
rational conversion character, `u' on its own is treated as equivalent
to `ud', and so the argument will be printed in decimal.

         (format "%hux" -1)
         => "ffff"

         (format "%hhu" -1)
         => "255"

         (format "%lux" (- (expt 2 30)))
         => "c0000000" ;; most-negative-fixnum on a 32 bit machine.


File: lispref.info,  Node: Character Case,  Next: Case Tables,  Prev: Formatting Strings,  Up: Strings and Characters

10.11 Character Case
====================

The character case functions change the case of single characters or of
the contents of strings.  The functions convert only alphabetic
characters (the letters `A' through `Z' and `a' through `z'); other
characters are not altered.  The functions do not modify the strings
that are passed to them as arguments.

   The examples below use the characters `X' and `x' which have ASCII
codes 88 and 120 respectively.

 -- Function: downcase string-or-char &optional buffer
     This function converts a character or a string to lower case.

     When the argument to `downcase' is a string, the function creates
     and returns a new string in which each letter in the argument that
     is upper case is converted to lower case.  When the argument to
     `downcase' is a character, `downcase' returns the corresponding
     lower case character. (This value is actually an integer under
     XEmacs 19.) If the original character is lower case, or is not a
     letter, then the value equals the original character.

     Optional second arg BUFFER specifies which buffer's case tables to
     use, and defaults to the current buffer.

          (downcase "The cat in the hat")
               => "the cat in the hat"

          (downcase ?X)
               => ?x   ;; Under XEmacs 20.
               => 120  ;; Under XEmacs 19.

 -- Function: upcase string-or-char &optional buffer
     This function converts a character or a string to upper case.

     When the argument to `upcase' is a string, the function creates
     and returns a new string in which each letter in the argument that
     is lower case is converted to upper case.

     When the argument to `upcase' is a character, `upcase' returns the
     corresponding upper case character. (This value is actually an
     integer under XEmacs 19.)  If the original character is upper
     case, or is not a letter, then the value equals the original
     character.

     Optional second arg BUFFER specifies which buffer's case tables to
     use, and defaults to the current buffer.

          (upcase "The cat in the hat")
               => "THE CAT IN THE HAT"

          (upcase ?x)
               => ?X   ;; Under XEmacs 20.
               => 88   ;; Under XEmacs 19.

 -- Function: capitalize string-or-char &optional buffer
     This function capitalizes strings or characters.  If
     STRING-OR-CHAR is a string, the function creates and returns a new
     string, whose contents are a copy of STRING-OR-CHAR in which each
     word has been capitalized.  This means that the first character of
     each word is converted to upper case, and the rest are converted
     to lower case.

     The definition of a word is any sequence of consecutive characters
     that are assigned to the word constituent syntax class in the
     current syntax table (*note Syntax Class Table::).

     When the argument to `capitalize' is a character, `capitalize' has
     the same result as `upcase'.

     Optional second arg BUFFER specifies which buffer's case tables to
     use, and defaults to the current buffer.

          (capitalize "The cat in the hat")
               => "The Cat In The Hat"

          (capitalize "THE 77TH-HATTED CAT")
               => "The 77th-Hatted Cat"

          (capitalize ?x)
               => ?X   ;; Under XEmacs 20.
               => 88   ;; Under XEmacs 19.


File: lispref.info,  Node: Case Tables,  Next: Char Tables,  Prev: Character Case,  Up: Strings and Characters

10.12 The Case Table
====================

You can customize case conversion by installing a special "case table".
A case table specifies the mapping between upper case and lower case
letters.  It affects both the string and character case conversion
functions (see the previous section) and those that apply to text in the
buffer (*note Case Changes::).  You need a case table if you are using a
language which has letters other than the standard ASCII letters.

   A case table is a list of this form:

     (DOWNCASE UPCASE CANONICALIZE EQUIVALENCES)

where each element is either `nil' or a string of length 256.  The
element DOWNCASE says how to map each character to its lower-case
equivalent.  The element UPCASE maps each character to its upper-case
equivalent.  If lower and upper case characters are in one-to-one
correspondence, use `nil' for UPCASE; then XEmacs deduces the upcase
table from DOWNCASE.

   For some languages, upper and lower case letters are not in
one-to-one correspondence.  There may be two different lower case
letters with the same upper case equivalent.  In these cases, you need
to specify the maps for both directions.

   The element CANONICALIZE maps each character to a canonical
equivalent; any two characters that are related by case-conversion have
the same canonical equivalent character.

   The element EQUIVALENCES is a map that cyclicly permutes each
equivalence class (of characters with the same canonical equivalent).
(For ordinary ASCII, this would map `a' into `A' and `A' into `a', and
likewise for each set of equivalent characters.)

   When you construct a case table, you can provide `nil' for
CANONICALIZE; then Emacs fills in this string from UPCASE and DOWNCASE.
You can also provide `nil' for EQUIVALENCES; then Emacs fills in this
string from CANONICALIZE.  In a case table that is actually in use,
those components are non-`nil'.  Do not try to specify EQUIVALENCES
without also specifying CANONICALIZE.

   Each buffer has a case table.  XEmacs also has a "standard case
table" which is copied into each buffer when you create the buffer.
Changing the standard case table doesn't affect any existing buffers.

   Here are the functions for working with case tables:

 -- Function: case-table-p object
     This predicate returns non-`nil' if OBJECT is a valid case table.

 -- Function: set-standard-case-table case-table
     This function makes CASE-TABLE the standard case table, so that it
     will apply to any buffers created subsequently.

 -- Function: standard-case-table
     This returns the standard case table.

 -- Function: current-case-table &optional buffer
     This function returns the case table of BUFFER, which defaults to
     the current buffer.

 -- Function: set-case-table case-table
     This sets the current buffer's case table to CASE-TABLE.

   The following three functions are convenient subroutines for packages
that define non-ASCII character sets.  They modify a string
DOWNCASE-TABLE provided as an argument; this should be a string to be
used as the DOWNCASE part of a case table.  They also modify the
standard syntax table.  *Note Syntax Tables::.

 -- Function: set-case-syntax-pair uc lc downcase-table
     This function specifies a pair of corresponding letters, one upper
     case and one lower case.

 -- Function: set-case-syntax-delims l r downcase-table
     This function makes characters L and R a matching pair of
     case-invariant delimiters.

 -- Function: set-case-syntax char syntax downcase-table
     This function makes CHAR case-invariant, with syntax SYNTAX.

 -- Command: describe-buffer-case-table
     This command displays a description of the contents of the current
     buffer's case table.

   You can load the library `iso-syntax' to set up the standard syntax
table and define a case table for the 8-bit ISO Latin 1 character set.


File: lispref.info,  Node: Char Tables,  Prev: Case Tables,  Up: Strings and Characters

10.13 The Char Table
====================

A char table is a table that maps characters (or ranges of characters)
to values.  Char tables are specialized for characters, only allowing
particular sorts of ranges to be assigned values.  Although this loses
in generality, it makes for extremely fast (constant-time) lookups, and
thus is feasible for applications that do an extremely large number of
lookups (e.g. scanning a buffer for a character in a particular syntax,
where a lookup in the syntax table must occur once per character).

   Note that char tables as a primitive type, and all of the functions
in this section, exist only in XEmacs 20.  In XEmacs 19, char tables are
generally implemented using a vector of 256 elements.

   When MULE support exists, the types of ranges that can be assigned
values are

   * all characters

   * an entire charset

   * a single row in a two-octet charset

   * a single character

   When MULE support is not present, the types of ranges that can be
assigned values are

   * all characters

   * a single character

 -- Function: char-table-p object
     This function returns non-`nil' if OBJECT is a char table.

* Menu:

* Char Table Types::            Char tables have different uses.
* Working With Char Tables::    Creating and working with char tables.


File: lispref.info,  Node: Char Table Types,  Next: Working With Char Tables,  Prev: Char Tables,  Up: Char Tables

10.13.1 Char Table Types
------------------------

Each char table type is used for a different purpose and allows
different sorts of values.  The different char table types are

`category'
     Used for category tables, which specify the regexp categories that
     a character is in.  The valid values are `nil' or a bit vector of
     95 elements.  Higher-level Lisp functions are provided for working
     with category tables.  Currently categories and category tables
     only exist when MULE support is present.

`char'
     A generalized char table, for mapping from one character to
     another.  Used for case tables, syntax matching tables,
     `keyboard-translate-table', etc.  The valid values are characters.

`generic'
     An even more generalized char table, for mapping from a character
     to anything.

`display'
     Used for display tables, which specify how a particular character
     is to appear when displayed.  #### Not yet implemented.

`syntax'
     Used for syntax tables, which specify the syntax of a particular
     character.  Higher-level Lisp functions are provided for working
     with syntax tables.  The valid values are fixnums.

 -- Function: char-table-type char-table
     This function returns the type of char table CHAR-TABLE.

 -- Function: char-table-type-list
     This function returns a list of the recognized char table types.

 -- Function: valid-char-table-type-p type
     This function returns `t' if TYPE if a recognized char table type.


File: lispref.info,  Node: Working With Char Tables,  Prev: Char Table Types,  Up: Char Tables

10.13.2 Working With Char Tables
--------------------------------

 -- Function: make-char-table type
     This function makes a new, empty char table of type TYPE.  TYPE
     should be a symbol, one of `char', `category', `display',
     `generic', or `syntax'.

 -- Function: put-char-table range value char-table
     This function sets the value for chars in RANGE to be VALUE in
     CHAR-TABLE.

     RANGE specifies one or more characters to be affected and should be
     one of the following:

        * `t' (all characters are affected)

        * A charset (only allowed when MULE support is present)

        * A vector of two elements: a two-octet charset and a row number
          (only allowed when MULE support is present)

        * A single character

     VALUE must be a value appropriate for the type of CHAR-TABLE.

 -- Function: get-char-table character char-table
     This function finds the value for CHARACTER in CHAR-TABLE.

 -- Function: get-range-char-table range char-table &optional multi
     This function finds the value for a range in CHAR-TABLE.  If there
     is more than one value, MULTI is returned (defaults to `nil').

 -- Function: reset-char-table char-table
     This function resets CHAR-TABLE to its default state.

 -- Function: map-char-table function char-table &optional range
     This function maps FUNCTION over entries in CHAR-TABLE, calling it
     with two args, each key and value in the table.

     RANGE specifies a subrange to map over and is in the same format
     as the RANGE argument to `put-range-table'.  If omitted or `t', it
     defaults to the entire table.

 -- Function: valid-char-table-value-p value char-table-type
     This function returns non-`nil' if VALUE is a valid value for
     CHAR-TABLE-TYPE.

 -- Function: check-valid-char-table-value value char-table-type
     This function signals an error if VALUE is not a valid value for
     CHAR-TABLE-TYPE.


File: lispref.info,  Node: Lists,  Next: Sequences Arrays Vectors,  Prev: Strings and Characters,  Up: Top

11 Lists
********

A "list" represents a sequence of zero or more elements (which may be
any Lisp objects).  The important difference between lists and vectors
is that two or more lists can share part of their structure; in
addition, you can insert or delete elements in a list without copying
the whole list.

* Menu:

* Cons Cells::              How lists are made out of cons cells.
* Lists as Boxes::          Graphical notation to explain lists.
* List-related Predicates:: Is this object a list?  Comparing two lists.
* List Elements::           Extracting the pieces of a list.
* Building Lists::          Creating list structure.
* Modifying Lists::         Storing new pieces into an existing list.
* Sets And Lists::          A list can represent a finite mathematical set.
* Association Lists::       A list can represent a finite relation or mapping.
* Property Lists::          A different way to represent a finite mapping.
* Weak Lists::              A list with special garbage-collection behavior.


File: lispref.info,  Node: Cons Cells,  Next: Lists as Boxes,  Prev: Lists,  Up: Lists

11.1 Lists and Cons Cells
=========================

Lists in Lisp are not a primitive data type; they are built up from
"cons cells".  A cons cell is a data object that represents an ordered
pair.  It records two Lisp objects, one labeled as the CAR, and the
other labeled as the CDR.  These names are traditional; see *Note Cons
Cell Type::.  CDR is pronounced "could-er."

   A list is a series of cons cells chained together, one cons cell per
element of the list.  By convention, the CARs of the cons cells are the
elements of the list, and the CDRs are used to chain the list: the CDR
of each cons cell is the following cons cell.  The CDR of the last cons
cell is `nil'.  This asymmetry between the CAR and the CDR is entirely
a matter of convention; at the level of cons cells, the CAR and CDR
slots have the same characteristics.

   Because most cons cells are used as part of lists, the phrase "list
structure" has come to mean any structure made out of cons cells.

   The symbol `nil' is considered a list as well as a symbol; it is the
list with no elements.  For convenience, the symbol `nil' is considered
to have `nil' as its CDR (and also as its CAR).

   The CDR of any nonempty list L is a list containing all the elements
of L except the first.


File: lispref.info,  Node: Lists as Boxes,  Next: List-related Predicates,  Prev: Cons Cells,  Up: Lists

11.2 Lists as Linked Pairs of Boxes
===================================

A cons cell can be illustrated as a pair of boxes.  The first box
represents the CAR and the second box represents the CDR.  Here is an
illustration of the two-element list, `(tulip lily)', made from two
cons cells:

      ---------------         ---------------
     | car   | cdr   |       | car   | cdr   |
     | tulip |   o---------->| lily  |  nil  |
     |       |       |       |       |       |
      ---------------         ---------------

   Each pair of boxes represents a cons cell.  Each box "refers to",
"points to" or "contains" a Lisp object.  (These terms are synonymous.)
The first box, which is the CAR of the first cons cell, contains the
symbol `tulip'.  The arrow from the CDR of the first cons cell to the
second cons cell indicates that the CDR of the first cons cell points
to the second cons cell.

   The same list can be illustrated in a different sort of box notation
like this:

         ___ ___      ___ ___
        |___|___|--> |___|___|--> nil
          |            |
          |            |
           --> tulip    --> lily

   Here is a more complex illustration, showing the three-element list,
`((pine needles) oak maple)', the first element of which is a
two-element list:

         ___ ___      ___ ___      ___ ___
        |___|___|--> |___|___|--> |___|___|--> nil
          |            |            |
          |            |            |
          |             --> oak      --> maple
          |
          |     ___ ___      ___ ___
           --> |___|___|--> |___|___|--> nil
                 |            |
                 |            |
                  --> pine     --> needles

   The same list represented in the first box notation looks like this:

      --------------       --------------       --------------
     | car   | cdr  |     | car   | cdr  |     | car   | cdr  |
     |   o   |   o------->| oak   |   o------->| maple |  nil |
     |   |   |      |     |       |      |     |       |      |
      -- | ---------       --------------       --------------
         |
         |
         |        --------------       ----------------
         |       | car   | cdr  |     | car     | cdr  |
          ------>| pine  |   o------->| needles |  nil |
                 |       |      |     |         |      |
                  --------------       ----------------

   *Note Cons Cell Type::, for the read and print syntax of cons cells
and lists, and for more "box and arrow" illustrations of lists.


File: lispref.info,  Node: List-related Predicates,  Next: List Elements,  Prev: Lists as Boxes,  Up: Lists

11.3 Predicates on Lists
========================

The following predicates test whether a Lisp object is an atom, is a
cons cell or is a list, or whether it is the distinguished object
`nil'.  (Many of these predicates can be defined in terms of the
others, but they are used so often that it is worth having all of them.)

 -- Function: consp object
     This function returns `t' if OBJECT is a cons cell, `nil'
     otherwise.  `nil' is not a cons cell, although it _is_ a list.

 -- Function: atom object
     This function returns `t' if OBJECT is an atom, `nil' otherwise.
     All objects except cons cells are atoms.  The symbol `nil' is an
     atom and is also a list; it is the only Lisp object that is both.

          (atom OBJECT) == (not (consp OBJECT))

 -- Function: listp object
     This function returns `t' if OBJECT is a cons cell or `nil'.
     Otherwise, it returns `nil'.  `true-list-p' is slower, but in some
     circumstances it is more appropriate.

          (listp '(1))
               => t
          (listp '())
               => t

 -- Function: nlistp object
     This function is the opposite of `listp': it returns `t' if OBJECT
     is not a list.  Otherwise, it returns `nil'.

          (listp OBJECT) == (not (nlistp OBJECT))

 -- Function: true-list-p object
     This function returns `t' if OBJECT is an acyclic,
     `nil'-terminated (ie, not dotted), list.  Otherwise it returns
     `nil'.  `listp' is faster.

 -- Function: null object
     This function returns `t' if OBJECT is `nil', and returns `nil'
     otherwise.  This function is identical to `not', but as a matter
     of clarity we use `null' when OBJECT is considered a list and
     `not' when it is considered a truth value (see `not' in *Note
     Combining Conditions::).

          (null '(1))
               => nil
          (null '())
               => t


File: lispref.info,  Node: List Elements,  Next: Building Lists,  Prev: List-related Predicates,  Up: Lists

11.4 Accessing Elements of Lists
================================

 -- Function: car cons-cell
     This function returns the value pointed to by the first pointer of
     the cons cell CONS-CELL.  Expressed another way, this function
     returns the CAR of CONS-CELL.

     As a special case, if CONS-CELL is `nil', then `car' is defined to
     return `nil'; therefore, any list is a valid argument for `car'.
     An error is signaled if the argument is not a cons cell or `nil'.

          (car '(a b c))
               => a
          (car '())
               => nil

 -- Function: cdr cons-cell
     This function returns the value pointed to by the second pointer of
     the cons cell CONS-CELL.  Expressed another way, this function
     returns the CDR of CONS-CELL.

     As a special case, if CONS-CELL is `nil', then `cdr' is defined to
     return `nil'; therefore, any list is a valid argument for `cdr'.
     An error is signaled if the argument is not a cons cell or `nil'.

          (cdr '(a b c))
               => (b c)
          (cdr '())
               => nil

 -- Function: car-safe object
     This function lets you take the CAR of a cons cell while avoiding
     errors for other data types.  It returns the CAR of OBJECT if
     OBJECT is a cons cell, `nil' otherwise.  This is in contrast to
     `car', which signals an error if OBJECT is not a list.

          (car-safe OBJECT)
          ==
          (let ((x OBJECT))
            (if (consp x)
                (car x)
              nil))

 -- Function: cdr-safe object
     This function lets you take the CDR of a cons cell while avoiding
     errors for other data types.  It returns the CDR of OBJECT if
     OBJECT is a cons cell, `nil' otherwise.  This is in contrast to
     `cdr', which signals an error if OBJECT is not a list.

          (cdr-safe OBJECT)
          ==
          (let ((x OBJECT))
            (if (consp x)
                (cdr x)
              nil))

 -- Function: nth n list
     This function returns the Nth element of LIST.  Elements are
     numbered starting with zero, so the CAR of LIST is element number
     zero.  If the length of LIST is N or less, the value is `nil'.

     If N is negative, `nth' returns the first element of LIST.

          (nth 2 '(1 2 3 4))
               => 3
          (nth 10 '(1 2 3 4))
               => nil
          (nth -3 '(1 2 3 4))
               => 1

          (nth n x) == (car (nthcdr n x))

 -- Function: nthcdr n list
     This function returns the Nth CDR of LIST.  In other words, it
     removes the first N links of LIST and returns what follows.

     If N is zero or negative, `nthcdr' returns all of LIST.  If the
     length of LIST is N or less, `nthcdr' returns `nil'.

          (nthcdr 1 '(1 2 3 4))
               => (2 3 4)
          (nthcdr 10 '(1 2 3 4))
               => nil
          (nthcdr -3 '(1 2 3 4))
               => (1 2 3 4)

Many convenience functions are provided to make it easier for you to
access particular elements in a nested list.  All of these can be
rewritten in terms of the functions just described.

 -- Function: caar cons-cell
 -- Function: cadr cons-cell
 -- Function: cdar cons-cell
 -- Function: cddr cons-cell
 -- Function: caaar cons-cell
 -- Function: caadr cons-cell
 -- Function: cadar cons-cell
 -- Function: caddr cons-cell
 -- Function: cdaar cons-cell
 -- Function: cdadr cons-cell
 -- Function: cddar cons-cell
 -- Function: cdddr cons-cell
 -- Function: caaaar cons-cell
 -- Function: caaadr cons-cell
 -- Function: caadar cons-cell
 -- Function: caaddr cons-cell
 -- Function: cadaar cons-cell
 -- Function: cadadr cons-cell
 -- Function: caddar cons-cell
 -- Function: cadddr cons-cell
 -- Function: cdaaar cons-cell
 -- Function: cdaadr cons-cell
 -- Function: cdadar cons-cell
 -- Function: cdaddr cons-cell
 -- Function: cddaar cons-cell
 -- Function: cddadr cons-cell
 -- Function: cdddar cons-cell
 -- Function: cddddr cons-cell
     Each of these functions is equivalent to one or more applications
     of `car' and/or `cdr'.  For example,

          (cadr x)

     is equivalent to

          (car (cdr x))

     and

          (cdaddr x)

     is equivalent to

          (cdr (car (cdr (cdr x))))

     That is to say, read the a's and d's from right to left and apply
     a `car' or `cdr' for each a or d found, respectively.

 -- Function: first list
     This is equivalent to `(nth 0 LIST)', i.e. the first element of
     LIST. (Note that this is also equivalent to `car'.)

 -- Function: second list
     This is equivalent to `(nth 1 LIST)', i.e. the second element of
     LIST.

 -- Function: third list
 -- Function: fourth list
 -- Function: fifth list
 -- Function: sixth list
 -- Function: seventh list
 -- Function: eighth list
 -- Function: ninth list
 -- Function: tenth list
     These are equivalent to `(nth 2 LIST)' through `(nth 9 LIST)'
     respectively, i.e. the third through tenth elements of LIST.


File: lispref.info,  Node: Building Lists,  Next: Modifying Lists,  Prev: List Elements,  Up: Lists

11.5 Building Cons Cells and Lists
==================================

Many functions build lists, as lists reside at the very heart of Lisp.
`cons' is the fundamental list-building function; however, it is
interesting to note that `list' is used more times in the source code
for Emacs than `cons'.

 -- Function: cons object1 object2
     This function is the fundamental function used to build new list
     structure.  It creates a new cons cell, making OBJECT1 the CAR,
     and OBJECT2 the CDR.  It then returns the new cons cell.  The
     arguments OBJECT1 and OBJECT2 may be any Lisp objects, but most
     often OBJECT2 is a list.

          (cons 1 '(2))
               => (1 2)
          (cons 1 '())
               => (1)
          (cons 1 2)
               => (1 . 2)

     `cons' is often used to add a single element to the front of a
     list.  This is called "consing the element onto the list".  For
     example:

          (setq list (cons newelt list))

     Note that there is no conflict between the variable named `list'
     used in this example and the function named `list' described below;
     any symbol can serve both purposes.

 -- Function: list &rest objects
     This function creates a list with OBJECTS as its elements.  The
     resulting list is always `nil'-terminated.  If no OBJECTS are
     given, the empty list is returned.

          (list 1 2 3 4 5)
               => (1 2 3 4 5)
          (list 1 2 '(3 4 5) 'foo)
               => (1 2 (3 4 5) foo)
          (list)
               => nil

 -- Function: make-list length object
     This function creates a list of length LENGTH, in which all the
     elements have the identical value OBJECT.  Compare `make-list'
     with `make-string' (*note Creating Strings::).

          (make-list 3 'pigs)
               => (pigs pigs pigs)
          (make-list 0 'pigs)
               => nil

 -- Function: append &rest sequences
     This function returns a list containing all the elements of
     SEQUENCES.  The SEQUENCES may be lists, vectors, or strings, but
     the last one should be a list.  All arguments except the last one
     are copied, so none of them are altered.

     More generally, the final argument to `append' may be any Lisp
     object.  The final argument is not copied or converted; it becomes
     the CDR of the last cons cell in the new list.  If the final
     argument is itself a list, then its elements become in effect
     elements of the result list.  If the final element is not a list,
     the result is a "dotted list" since its final CDR is not `nil' as
     required in a true list.

     See `nconc' in *Note Rearrangement::, for a way to join lists with
     no copying.

     Here is an example of using `append':

          (setq trees '(pine oak))
               => (pine oak)
          (setq more-trees (append '(maple birch) trees))
               => (maple birch pine oak)

          trees
               => (pine oak)
          more-trees
               => (maple birch pine oak)
          (eq trees (cdr (cdr more-trees)))
               => t

     You can see how `append' works by looking at a box diagram.  The
     variable `trees' is set to the list `(pine oak)' and then the
     variable `more-trees' is set to the list `(maple birch pine oak)'.
     However, the variable `trees' continues to refer to the original
     list:

          more-trees                trees
          |                           |
          |     ___ ___      ___ ___   -> ___ ___      ___ ___
           --> |___|___|--> |___|___|--> |___|___|--> |___|___|--> nil
                 |            |            |            |
                 |            |            |            |
                  --> maple    -->birch     --> pine     --> oak

     An empty sequence contributes nothing to the value returned by
     `append'.  As a consequence of this, a final `nil' argument forces
     a copy of the previous argument.

          trees
               => (pine oak)
          (setq wood (append trees ()))
               => (pine oak)
          wood
               => (pine oak)
          (eq wood trees)
               => nil

     This once was the usual way to copy a list, before the function
     `copy-sequence' was invented.  *Note Sequences Arrays Vectors::.

     With the help of `apply', we can append all the lists in a list of
     lists:

          (apply 'append '((a b c) nil (x y z) nil))
               => (a b c x y z)

     If no SEQUENCES are given, `nil' is returned:

          (append)
               => nil

     Here are some examples where the final argument is not a list:

          (append '(x y) 'z)
               => (x y . z)
          (append '(x y) [z])
               => (x y . [z])

     The second example shows that when the final argument is a
     sequence but not a list, the sequence's elements do not become
     elements of the resulting list.  Instead, the sequence becomes the
     final CDR, like any other non-list final argument.

     The `append' function also allows integers as arguments.  It
     converts them to strings of digits, making up the decimal print
     representation of the integer, and then uses the strings instead
     of the original integers.  *Don't use this feature; we plan to
     eliminate it.  If you already use this feature, change your
     programs now!*  The proper way to convert an integer to a decimal
     number in this way is with `format' (*note Formatting Strings::)
     or `number-to-string' (*note String Conversion::).

 -- Function: reverse sequence
     This function creates a new sequence whose elements are the
     elements of SEQUENCE, but in reverse order.  The original argument
     SEQUENCE is _not_ altered.

          (setq x '(1 2 3 4))
               => (1 2 3 4)
          (reverse x)
               => (4 3 2 1)
          x
               => (1 2 3 4)


File: lispref.info,  Node: Modifying Lists,  Next: Sets And Lists,  Prev: Building Lists,  Up: Lists

11.6 Modifying Existing List Structure
======================================

You can modify the CAR and CDR contents of a cons cell with the
primitives `setcar' and `setcdr'.

     Common Lisp note: Common Lisp uses functions `rplaca' and `rplacd'
     to alter list structure; they change structure the same way as
     `setcar' and `setcdr', but the Common Lisp functions return the
     cons cell while `setcar' and `setcdr' return the new CAR or CDR.

* Menu:

* Setcar::          Replacing an element in a list.
* Setcdr::          Replacing part of the list backbone.
                      This can be used to remove or add elements.
* Rearrangement::   Reordering the elements in a list; combining lists.


File: lispref.info,  Node: Setcar,  Next: Setcdr,  Prev: Modifying Lists,  Up: Modifying Lists

11.6.1 Altering List Elements with `setcar'
-------------------------------------------

Changing the CAR of a cons cell is done with `setcar'.  When used on a
list, `setcar' replaces one element of a list with a different element.

 -- Function: setcar cons-cell object
     This function stores OBJECT as the new CAR of CONS-CELL, replacing
     its previous CAR.  It returns the value OBJECT.  For example:

          (setq x '(1 2))
               => (1 2)
          (setcar x 4)
               => 4
          x
               => (4 2)

   When a cons cell is part of the shared structure of several lists,
storing a new CAR into the cons changes one element of each of these
lists.  Here is an example:

     ;; Create two lists that are partly shared.
     (setq x1 '(a b c))
          => (a b c)
     (setq x2 (cons 'z (cdr x1)))
          => (z b c)

     ;; Replace the CAR of a shared link.
     (setcar (cdr x1) 'foo)
          => foo
     x1                           ; Both lists are changed.
          => (a foo c)
     x2
          => (z foo c)

     ;; Replace the CAR of a link that is not shared.
     (setcar x1 'baz)
          => baz
     x1                           ; Only one list is changed.
          => (baz foo c)
     x2
          => (z foo c)

   Here is a graphical depiction of the shared structure of the two
lists in the variables `x1' and `x2', showing why replacing `b' changes
them both:

             ___ ___        ___ ___      ___ ___
     x1---> |___|___|----> |___|___|--> |___|___|--> nil
              |        -->   |            |
              |       |      |            |
               --> a  |       --> b        --> c
                      |
            ___ ___   |
     x2--> |___|___|--
             |
             |
              --> z

   Here is an alternative form of box diagram, showing the same
relationship:

     x1:
      --------------       --------------       --------------
     | car   | cdr  |     | car   | cdr  |     | car   | cdr  |
     |   a   |   o------->|   b   |   o------->|   c   |  nil |
     |       |      |  -->|       |      |     |       |      |
      --------------  |    --------------       --------------
                      |
     x2:              |
      --------------  |
     | car   | cdr  | |
     |   z   |   o----
     |       |      |
      --------------


File: lispref.info,  Node: Setcdr,  Next: Rearrangement,  Prev: Setcar,  Up: Modifying Lists

11.6.2 Altering the CDR of a List
---------------------------------

The lowest-level primitive for modifying a CDR is `setcdr':

 -- Function: setcdr cons-cell object
     This function stores OBJECT as the new CDR of CONS-CELL, replacing
     its previous CDR.  It returns the value OBJECT.

   Here is an example of replacing the CDR of a list with a different
list.  All but the first element of the list are removed in favor of a
different sequence of elements.  The first element is unchanged,
because it resides in the CAR of the list, and is not reached via the
CDR.

     (setq x '(1 2 3))
          => (1 2 3)
     (setcdr x '(4))
          => (4)
     x
          => (1 4)

   You can delete elements from the middle of a list by altering the
CDRs of the cons cells in the list.  For example, here we delete the
second element, `b', from the list `(a b c)', by changing the CDR of
the first cell:

     (setq x1 '(a b c))
          => (a b c)
     (setcdr x1 (cdr (cdr x1)))
          => (c)
     x1
          => (a c)

   Here is the result in box notation:

                        --------------------
                       |                    |
      --------------   |   --------------   |    --------------
     | car   | cdr  |  |  | car   | cdr  |   -->| car   | cdr  |
     |   a   |   o-----   |   b   |   o-------->|   c   |  nil |
     |       |      |     |       |      |      |       |      |
      --------------       --------------        --------------

The second cons cell, which previously held the element `b', still
exists and its CAR is still `b', but it no longer forms part of this
list.

   It is equally easy to insert a new element by changing CDRs:

     (setq x1 '(a b c))
          => (a b c)
     (setcdr x1 (cons 'd (cdr x1)))
          => (d b c)
     x1
          => (a d b c)

   Here is this result in box notation:

      --------------        -------------       -------------
     | car  | cdr   |      | car  | cdr  |     | car  | cdr  |
     |   a  |   o   |   -->|   b  |   o------->|   c  |  nil |
     |      |   |   |  |   |      |      |     |      |      |
      --------- | --   |    -------------       -------------
                |      |
          -----         --------
         |                      |
         |    ---------------   |
         |   | car   | cdr   |  |
          -->|   d   |   o------
             |       |       |
              ---------------


File: lispref.info,  Node: Rearrangement,  Prev: Setcdr,  Up: Modifying Lists

11.6.3 Functions that Rearrange Lists
-------------------------------------

Here are some functions that rearrange lists "destructively" by
modifying the CDRs of their component cons cells.  We call these
functions "destructive" because they chew up the original lists passed
to them as arguments, to produce a new list that is the returned value.

   See `delq', in *Note Sets And Lists::, for another function that
modifies cons cells.

 -- Function: nconc &rest lists
     This function returns a list containing all the elements of LISTS.
     Unlike `append' (*note Building Lists::), the LISTS are _not_
     copied.  Instead, the last CDR of each of the LISTS is changed to
     refer to the following list.  The last of the LISTS is not
     altered.  For example:

          (setq x '(1 2 3))
               => (1 2 3)
          (nconc x '(4 5))
               => (1 2 3 4 5)
          x
               => (1 2 3 4 5)

     Since the last argument of `nconc' is not itself modified, it is
     reasonable to use a constant list, such as `'(4 5)', as in the
     above example.  For the same reason, the last argument need not be
     a list:

          (setq x '(1 2 3))
               => (1 2 3)
          (nconc x 'z)
               => (1 2 3 . z)
          x
               => (1 2 3 . z)

     A common pitfall is to use a quoted constant list as a non-last
     argument to `nconc'.  If you do this, your program will change
     each time you run it!  Here is what happens:

          (defun add-foo (x)            ; We want this function to add
            (nconc '(foo) x))           ;   `foo' to the front of its arg.

          (symbol-function 'add-foo)
               => (lambda (x) (nconc (quote (foo)) x))

          (setq xx (add-foo '(1 2)))    ; It seems to work.
               => (foo 1 2)
          (setq xy (add-foo '(3 4)))    ; What happened?
               => (foo 1 2 3 4)
          (eq xx xy)
               => t

          (symbol-function 'add-foo)
               => (lambda (x) (nconc (quote (foo 1 2 3 4) x)))

 -- Function: nreverse sequence
     This function reverses the order of the elements of SEQUENCE.
     Unlike `reverse', `nreverse' alters its argument.  If SEQUENCE is
     a list, it does this by reversing the CDRs in the cons cells
     forming the sequence.  The cons cell that used to be the last one
     in SEQUENCE becomes the first cell of the value.

     For example:

          (setq x '(1 2 3 4))
               => (1 2 3 4)
          x
               => (1 2 3 4)
          (nreverse x)
               => (4 3 2 1)
          ;; The cell that was first is now last.
          x
               => (1)

     To avoid confusion, we usually store the result of `nreverse' back
     in the same variable which held the original sequence:

          (setq x (nreverse x))

     Here is the `nreverse' of our favorite example, `(a b c)',
     presented graphically:

          Original list head:                       Reversed list:
           -------------        -------------        ------------
          | car  | cdr  |      | car  | cdr  |      | car | cdr  |
          |   a  |  nil |<--   |   b  |   o  |<--   |   c |   o  |
          |      |      |   |  |      |   |  |   |  |     |   |  |
           -------------    |   --------- | -    |   -------- | -
                            |             |      |            |
                             -------------        ------------

 -- Function: sort* sequence predicate &key (key #'identity)
     This function sorts SEQUENCE stably, though destructively, and
     returns the sorted sequence.  It compares elements using
     PREDICATE.  A stable sort is one in which elements with equal sort
     keys maintain their relative order before and after the sort.
     Stability is important when successive sorts are used to order
     elements according to different criteria.

     SEQUENCE can be any sequence, that is, a list, a vector, a
     bit-vector, or a string.

     The argument PREDICATE must be a function that accepts two
     arguments.  It is called with two elements of SEQUENCE.  To get an
     increasing order sort, the PREDICATE should return `t' if the
     first element is "less than" the second, or `nil' if not.

     The keyword argument KEY, if supplied, is a function used to
     extract an object to be used for comparison from each element of
     SEQUENCE, and defaults to `identity'.  For example, to sort a
     vector of lists by the numeric value of the first element, you
     could use the following code:

          (setq example-vector [(1 "foo") (3.14159 bar) (2 . quux)])
               => [(1 "foo") (3.14159 bar) (2 . quux)]
          (sort* example-vector #'< :key #'car)
               => [(1 "foo") (2 . quux) (3.14159 bar)]

     If SEQUENCE is a list, `sort*' rearranges the cons cells forming
     SEQUENCE by changing CDRs.  A nondestructive sort function would
     create new cons cells to store the elements in their sorted order.
     `sort*' treats other sequence types in an analogous fashion--if
     you wish to make a sorted copy without destroying the original,
     copy it first with `copy-sequence' and then sort.

     Sorting will not change the CARs of the cons cells of a list
     SEQUENCE; the cons cell that originally contained the element `a'
     in SEQUENCE still has `a' in its CAR after sorting, but it now
     appears in a different position in the sequence due to the change
     of CDRs.  For example:

          (setq nums '(1 3 2 6 5 4 0))
               => (1 3 2 6 5 4 0)
          (sort* nums '<)
               => (0 1 2 3 4 5 6)
          nums
               => (1 2 3 4 5 6)

     Note that the list in `nums' no longer contains 0; this is the same
     cons cell that it was before, but it is no longer the first one in
     the list.  Don't assume a variable that formerly held the argument
     now holds the entire sorted list!  Instead, save the result of
     `sort*' and use that.  Most often we store the result back into
     the variable that held the original sequence:

          (setq nums (sort* nums '<))

     In this implementation, `sort' is a function alias for `sort*',
     and accepts the same arguments.  In older XEmacs, and in current
     GNU Emacs, `sort' only accepted lists, and did not accept the KEY
     argument, so the byte-compiler will warn you if you call `sort'
     with more than two arguments.

     *Note Sorting::, for more functions that perform sorting.  See
     `documentation' in *Note Accessing Documentation::, for a useful
     example of `sort*'.


File: lispref.info,  Node: Sets And Lists,  Next: Association Lists,  Prev: Modifying Lists,  Up: Lists

11.7 Using Lists as Sets
========================

A list can represent an unordered mathematical set--simply consider a
value an element of a set if it appears in the list, and ignore the
order of the list.  XEmacs provides set operations inherited from Common
Lisp.

 -- Function: member* item list &key :test :test-not :key
     This function tests to see whether ITEM is a member of LIST,
     comparing with `eql'.  If it is, `member*' returns the tail of
     LIST starting with the first occurrence of ITEM.  Otherwise, it
     returns `nil'.

     This is equivalent to the Common Lisp `member' function, but that
     name was already taken in Emacs Lisp, whence the asterisk at the
     end of `member*'.

     The `:test' keyword argument allows you to specify the test used to
     decide whether ITEM is equivalent to a given element of LIST.  The
     function should return non-`nil' if the items match, `nil' if they
     do not.  The `:test-not' keyword is similar, but the meaning of
     `nil' and non-`nil' results are reversed. The `:key' keyword
     allows you to examine a component of each object in LIST, rather
     than the object itself.

          (member* 'b '(a b c b a))
               => (b c b a)
          (member* '(2) '((1) (2))) ; `(2)' and `(2)' are not `eql'.
               => nil
          (member* '(2) '((1) (2)) :test #'equal) ; but they are `equal'.
               => ((2))
          (member* 3 '((1) (2) (3) (4)) :key 'car) ; key not applied to ITEM
               => ((3) (4))

 -- Function: memq item list
     This is equivalent to calling `(member* item list :test 'eq)', but
     for historical reasons is more common in the XEmacs code base.
     Both expressions compile to the same byte-code.

 -- Function: member item list
     This is equivalent to calling `(member* item list :test 'equal)'.

 -- Function: remove* item sequence &key (test #'eql) (key #'identity)
          (start 0) (end (length sequence)) from-end count test-not
     This function removes all occurrences of OBJECT from SEQUENCE,
     which can be a list, vector, or bit-vector.

     The `:test' keyword argument allows you to specify the test used to
     decide whether ITEM is equivalent to a given element of SEQUENCE.
     The function should return non-`nil' if the items match, `nil' if
     they do not.  The `:test-not' keyword is similar, but the meaning
     of `nil' and non-`nil' results are reversed. The `:key' keyword
     allows you to examine a component of each object in SEQUENCE,
     rather than the object itself.

     The `:start' and `:end' keywords allow you to specify a zero-based
     subrange of SEQUENCE to operate on, `remove*' will call the test
     function on all items of SEQUENCE between the index specified by
     `:start', inclusive, and `:end', exclusive. `:count' gives a
     maximum number of items to remove, and `:from-end', most useful in
     combination with `:count', specifies that the removal should start
     from the end of SEQUENCE.

     As with `member*', this function is equivalent to the Common Lisp
     function of almost the same name (the Common Lisp function has no
     asterisk.)

     When `remove*' removes elements from the front of a list SEQUENCE,
     it does so simply by advancing down the list and returning a
     sublist that starts after those elements:

          (remove* 'a '(a b c)) == (cdr '(a b c))

     When an element to be deleted appears in the middle of the list,
     removing it involves copying the list conses up to that point, and
     setting the tail of the copied list to the tail of the original
     list past that point.

          (setq sample-list '(a b c (4)))
               => (a b c (4))
          (remove* 'a sample-list)
               => (b c (4))
          sample-list
               => (a b c (4))
          (remove* 'c sample-list)
               => (a b (4))
          sample-list
               => (a b c (4))

     Don't assume that a variable which formerly held the argument LIST
     now has fewer elements, or that it still holds the original list!
     Instead, save the result of `remove*' and use that.  Most often we
     store the result back into the variable that held the original
     list:

          (setq flowers (remove* 'rose flowers))

     In the following example, the `(4)' that `remove*' attempts to
     match and the `(4)' in the `sample-list' are not `eql':

          (remove* '(4) sample-list)
               => (a b c (4))

 -- Function: remq item sequence
     This is equivalent to calling `(remove* item sequence :test #'eq)'.

 -- Function: remove item sequence
     This is equivalent to calling `(remove* item sequence :test
     #'equal)'.

 -- Function: delete* item sequence &key (test #'eql) (key #'identity)
          (start 0) (end (length sequence)) from-end count test-not
     This is like `remove*', but a list SEQUENCE is modified in-place
     (`destructively', in Lisp parlance). So some of the examples above
     change:

          (setq sample-list '(a b c (4)))
               => (a b c (4))
          (delete* 'c sample-list)
               => (a b (4))
          sample-list
               => (a b (4))

 -- Function: delq item sequence
     This is equivalent to calling `(delete* item sequence :test #'eq)'.

 -- Function: delete item list
     This is equivalent to calling `(delete* item sequence :test
     #'equal)'.

 -- Function: subsetp list1 list2 &key :test :test-not :key
     This function returns non-`nil' if every item in LIST1 is present
     in LIST2.

 -- Function: union list1 list2 &key :test :test-not :key :stable
     This function calculates the union of two lists, returning a list
     containing all those items that appear in either list.  It doesn't
     guarantee that duplicates in LIST1 or LIST2 will be eliminated;
     see `remove-duplicates' if this is important to you.

     A non-nil value for the `:stable' keyword, not specified by Common
     Lisp, means return the items in the order they appear in LIST1,
     followed by the remaining items in the order they appear in LIST2.
     The other keywords are as in `member*'.

     `union' does not modify LIST1 or LIST2.

 -- Function: intersection list1 list2 &key :test :test-not :key :stable
     This function calculates the intersection of two lists, returning
     a list containing all those items that appear in both lists.  It
     doesn't guarantee that duplicates in LIST1 or LIST2 will be
     eliminated; see `remove-duplicates' if this is important to you.
     `intersection' does not modify either list.

     A non-nil value for the `:stable' keyword, not specified by Common
     Lisp, means return the items in the order they appear in LIST1.
     The other keywords are as in `member*'.

 -- Function: set-difference list1 list2 &key :test :test-not :key
          :stable
     This function returns those items that are in LIST1 but not in
     LIST2.  It does not modify either list.

     A non-nil value for the `:stable' keyword, not specified by Common
     Lisp, means return the items in the order they appear in LIST1.
     The other keywords are as in `member*'.

 -- Function: set-exclusive-or list1 list2 &key :test :test-not :key
          :stable
     This function returns those items that are in LIST1 but not in
     LIST2, together with those in LIST2 but not in LIST1.  It does not
     modify either list.

     A non-nil value for the `:stable' keyword, not specified by Common
     Lisp, means return the items in the order they appear in LIST1,
     followed by the remaining items in the order they appear in LIST2.
     The other keywords are as in `member*'.

   The following functions are equivalent to the previous four
functions, but with two important differences; they do not accept the
`:stable' keyword, and they modify one or both list arguments in the
same way `delete*' does.

 -- Function: nintersection list1 list2 &key :test :test-not :key

 -- Function: nset-difference list1 list2 &key :test :test-not :key

 -- Function: nset-exclusive-or list1 list2 &key :test :test-not :key

 -- Function: nunion list1 list2 &key :test :test-not :key

   See also the function `add-to-list', in *Note Setting Variables::,
for another way to add an element to a list stored in a variable.


File: lispref.info,  Node: Association Lists,  Next: Property Lists,  Prev: Sets And Lists,  Up: Lists

11.8 Association Lists
======================

An "association list", or "alist" for short, records a mapping from
keys to values.  It is a list of cons cells called "associations": the
CAR of each cell is the "key", and the CDR is the "associated value".(1)

   Here is an example of an alist.  The key `pine' is associated with
the value `cones'; the key `oak' is associated with `acorns'; and the
key `maple' is associated with `seeds'.

     '((pine . cones)
       (oak . acorns)
       (maple . seeds))

   The associated values in an alist may be any Lisp objects; so may the
keys.  For example, in the following alist, the symbol `a' is
associated with the number `1', and the string `"b"' is associated with
the _list_ `(2 3)', which is the CDR of the alist element:

     ((a . 1) ("b" 2 3))

   Sometimes it is better to design an alist to store the associated
value in the CAR of the CDR of the element.  Here is an example:

     '((rose red) (lily white) (buttercup yellow))

Here we regard `red' as the value associated with `rose'.  One
advantage of this method is that you can store other related
information--even a list of other items--in the CDR of the CDR.  One
disadvantage is that you cannot use `rassq' (see below) to find the
element containing a given value.  When neither of these considerations
is important, the choice is a matter of taste, as long as you are
consistent about it for any given alist.

   Note that the same alist shown above could be regarded as having the
associated value in the CDR of the element; the value associated with
`rose' would be the list `(red)'.

   Association lists are often used to record information that you might
otherwise keep on a stack, since new associations may be added easily to
the front of the list.  When searching an association list for an
association with a given key, the first one found is returned, if there
is more than one.

   In XEmacs Lisp, it is _not_ an error if an element of an association
list is not a cons cell.  The alist search functions simply ignore such
elements.  Many other versions of Lisp signal errors in such cases, and
it is good practice to avoid adding non-cons-cells to association lists.

   Note that property lists are similar to association lists in several
respects.  A property list behaves like an association list in which
each key can occur only once.  *Note Property Lists::, for a comparison
of property lists and association lists.

 -- Function: assoc* key alist &key :test :test-not :key
     This function returns the first association for KEY in ALIST.  It
     compares KEY against the alist elements using `eql' (*note
     Equality Predicates::), or the test specified with the `:test'
     keyword. It returns `nil' if no association in ALIST has a CAR
     `equal' to KEY.  For example:

          (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
               => ((pine . cones) (oak . acorns) (maple . seeds))
          (assoc* 'oak trees)
               => (oak . acorns)
          (cdr (assoc* 'oak trees))
               => acorns
          (assoc* 'birch trees)
               => nil

     Here is another example, in which the keys and values are not
     symbols:

          (setq needles-per-cluster
                '((2 "Austrian Pine" "Red Pine")
                  (3 "Pitch Pine")
                  (5 "White Pine")))

          (cdr (assoc* 3 needles-per-cluster))
               => ("Pitch Pine")
          (cdr (assoc* 2 needles-per-cluster))
               => ("Austrian Pine" "Red Pine")

     The `:test' keyword argument allows you to specify the test used to
     decide whether KEY is equivalent to a given element of ALIST.  The
     function should return non-`nil' if the items match, `nil' if they
     do not.  The `:test-not' keyword is similar, but the meaning of
     `nil' and non-`nil' results are reversed. The `:key' keyword
     allows you to examine a component of each CAR in ALIST, rather
     than the CAR itself.

 -- Function: assoc key alist &optional test
     This is equivalent to calling `(assoc* key alist :test (or test
     'equal)'.

     Calling `assoc' without a TEST argument is portable to basically
     any version of Emacs; however the TEST argument is a relatively
     recent GNU addition, it is more portable to call `(require 'cl)'
     and to use `assoc*'.

 -- Function: assq key alist
     This is equivalent to calling `(assoc* key alist :test 'eq)', and
     compiles to the same byte code.

          (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
               => ((pine . cones) (oak . acorns) (maple . seeds))
          (assq 'pine trees)
               => (pine . cones)

     `assq' is not usually useful in alists where the keys may not be
     symbols:

          (setq leaves
                '(("simple leaves" . oak)
                  ("compound leaves" . horsechestnut)))

          (assq "simple leaves" leaves)
               => nil
          (assoc "simple leaves" leaves)
               => ("simple leaves" . oak)

 -- Function: rassoc* value alist &key :test :test-not :key
     This function returns the first association with value VALUE in
     ALIST.  It returns `nil' if no association in ALIST has a CDR
     `eql' to VALUE.

     `rassoc*' is like `assoc*' except that it compares the CDR of each
     ALIST association instead of the CAR.  You can think of this as
     "reverse `assoc*'", finding the key for a given value.

     The keywords work similarly to `assoc*'.

 -- Function: rassq value alist
     This is equivalent to calling `(rassoc* value alist :test 'eq)',
     and compiles to the same byte code. For example:

          (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))

          (rassq 'acorns trees)
               => (oak . acorns)
          (rassq 'spores trees)
               => nil

     Note that `rassq' cannot search for a value stored in the CAR of
     the CDR of an element:

          (setq colors '((rose red) (lily white) (buttercup yellow)))

          (rassq 'white colors)
               => nil

     In this case, the CDR of the association `(lily white)' is not the
     symbol `white', but rather the list `(white)'.  This becomes
     clearer if the association is written in dotted pair notation:

          (lily white) == (lily . (white))

 -- Function: copy-alist alist
     This function returns a two-level deep copy of ALIST: it creates a
     new copy of each association, so that you can alter the
     associations of the new alist without changing the old one.

          (setq needles-per-cluster
                '((2 . ("Austrian Pine" "Red Pine"))
                  (3 . ("Pitch Pine"))
                  (5 . ("White Pine"))))
          =>
          ((2 "Austrian Pine" "Red Pine")
           (3 "Pitch Pine")
           (5 "White Pine"))

          (setq copy (copy-alist needles-per-cluster))
          =>
          ((2 "Austrian Pine" "Red Pine")
           (3 "Pitch Pine")
           (5 "White Pine"))

          (eq needles-per-cluster copy)
               => nil
          (equal needles-per-cluster copy)
               => t
          (eq (car needles-per-cluster) (car copy))
               => nil
          (cdr (car (cdr needles-per-cluster)))
               => ("Pitch Pine")
          (eq (cdr (car (cdr needles-per-cluster)))
              (cdr (car (cdr copy))))
               => t

     This example shows how `copy-alist' makes it possible to change
     the associations of one copy without affecting the other:

          (setcdr (assq 3 copy) '("Martian Vacuum Pine"))
          (cdr (assq 3 needles-per-cluster))
               => ("Pitch Pine")

   For removing elements from alists, use `remove*' or `delete*' with
appropriate `:key' arguments.  If it is necessary that XEmacs not error
on encountering a non-cons in such a list, there are XEmacs-specific
functions `remassq', `remrassq', `remassoc', and `remrassoc' with this
behavior, but they are neither available under GNU Emacs nor Common
Lisp.  They are marked as obsolete, and it is preferable to fix your
code to avoid adding non-cons objects to alists.

   ---------- Footnotes ----------

   (1) This usage of "key" is not related to the term "key sequence";
it means a value used to look up an item in a table.  In this case, the
table is the alist, and the alist associations are the items.


File: lispref.info,  Node: Property Lists,  Next: Weak Lists,  Prev: Association Lists,  Up: Lists

11.9 Property Lists
===================

A "property list" (or "plist") is another way of representing a mapping
from keys to values.  Instead of the list consisting of conses of a key
and a value, the keys and values alternate as successive entries in the
list.  Thus, the association list

     ((a . 1) (b . 2) (c . 3))

   has the equivalent property list form

     (a 1 b 2 c 3)

   Property lists are used to represent the properties associated with
various sorts of objects, such as symbols, strings, frames, etc.  The
convention is that property lists can be modified in-place, while
association lists generally are not.

   Plists come in two varieties: "normal" plists, whose keys are
compared with `eq', and "lax" plists, whose keys are compared with
`equal',

 -- Function: valid-plist-p plist
     Given a plist, this function returns non-`nil' if its format is
     correct.  If it returns `nil', `check-valid-plist' will signal an
     error when given the plist; that means it's a malformed or circular
     plist or has non-symbols as keywords.

 -- Function: check-valid-plist plist
     Given a plist, this function signals an error if there is anything
     wrong with it.  This means that it's a malformed or circular plist.

* Menu:

* Working With Normal Plists::       Functions for normal plists.
* Working With Lax Plists::          Functions for lax plists.
* Converting Plists To/From Alists:: Alist to plist and vice-versa.


File: lispref.info,  Node: Working With Normal Plists,  Next: Working With Lax Plists,  Prev: Property Lists,  Up: Property Lists

11.9.1 Working With Normal Plists
---------------------------------

 -- Function: plist-get plist property &optional default
     This function extracts a value from a property list.  The function
     returns the value corresponding to the given PROPERTY, or DEFAULT
     if PROPERTY is not one of the properties on the list.

 -- Function: plist-put plist property value
     This function changes the value in PLIST of PROPERTY to VALUE.  If
     PROPERTY is already a property on the list, its value is set to
     VALUE, otherwise the new PROPERTY VALUE pair is added.  The new
     plist is returned; use `(setq x (plist-put x property value))' to
     be sure to use the new value.  The PLIST is modified by side
     effects.

 -- Function: plist-remprop plist property
     This function removes from PLIST the property PROPERTY and its
     value.  The new plist is returned; use `(setq x (plist-remprop x
     property))' to be sure to use the new value.  The PLIST is
     modified by side effects.

 -- Function: plist-member plist property
     This function returns `t' if PROPERTY has a value specified in
     PLIST.

   In the following functions, if optional arg NIL-MEANS-NOT-PRESENT is
non-`nil', then a property with a `nil' value is ignored or removed.
This feature is a virus that has infected old Lisp implementations (and
thus E-Lisp, due to RMS's enamorment with old Lisps), but should not be
used except for backward compatibility.

 -- Function: plists-eq a b &optional nil-means-not-present
     This function returns non-`nil' if property lists A and B are `eq'
     (i.e. their values are `eq').

 -- Function: plists-equal a b &optional nil-means-not-present
     This function returns non-`nil' if property lists A and B are
     `equal' (i.e. their values are `equal'; their keys are still
     compared using `eq').

 -- Function: canonicalize-plist plist &optional nil-means-not-present
     This function destructively removes any duplicate entries from a
     plist.  In such cases, the first entry applies.

     The new plist is returned.  If NIL-MEANS-NOT-PRESENT is given, the
     return value may not be `eq' to the passed-in value, so make sure
     to `setq' the value back into where it came from.


File: lispref.info,  Node: Working With Lax Plists,  Next: Converting Plists To/From Alists,  Prev: Working With Normal Plists,  Up: Property Lists

11.9.2 Working With Lax Plists
------------------------------

Recall that a "lax plist" is a property list whose keys are compared
using `equal' instead of `eq'.

 -- Function: lax-plist-get lax-plist property &optional default
     This function extracts a value from a lax property list.  The
     function returns the value corresponding to the given PROPERTY, or
     DEFAULT if PROPERTY is not one of the properties on the list.

 -- Function: lax-plist-put lax-plist property value
     This function changes the value in LAX-PLIST of PROPERTY to VALUE.

 -- Function: lax-plist-remprop lax-plist property
     This function removes from LAX-PLIST the property PROPERTY and its
     value.  The new plist is returned; use `(setq x (lax-plist-remprop
     x property))' to be sure to use the new value.  The LAX-PLIST is
     modified by side effects.

 -- Function: lax-plist-member lax-plist property
     This function returns `t' if PROPERTY has a value specified in
     LAX-PLIST.

   In the following functions, if optional arg NIL-MEANS-NOT-PRESENT is
non-`nil', then a property with a `nil' value is ignored or removed.
This feature is a virus that has infected old Lisp implementations (and
thus E-Lisp, due to RMS's enamorment with old Lisps), but should not be
used except for backward compatibility.

 -- Function: lax-plists-eq a b &optional nil-means-not-present
     This function returns non-`nil' if lax property lists A and B are
     `eq' (i.e. their values are `eq'; their keys are still compared
     using `equal').

 -- Function: lax-plists-equal a b &optional nil-means-not-present
     This function returns non-`nil' if lax property lists A and B are
     `equal' (i.e. their values are `equal').

 -- Function: canonicalize-lax-plist lax-plist &optional
          nil-means-not-present
     This function destructively removes any duplicate entries from a
     lax plist.  In such cases, the first entry applies.

     The new plist is returned.  If NIL-MEANS-NOT-PRESENT is given, the
     return value may not be `eq' to the passed-in value, so make sure
     to `setq' the value back into where it came from.


File: lispref.info,  Node: Converting Plists To/From Alists,  Prev: Working With Lax Plists,  Up: Property Lists

11.9.3 Converting Plists To/From Alists
---------------------------------------

 -- Function: alist-to-plist alist
     This function converts association list ALIST into the equivalent
     property-list form.  The plist is returned.  This converts from

          ((a . 1) (b . 2) (c . 3))

     into

          (a 1 b 2 c 3)

     The original alist is not modified.

 -- Function: plist-to-alist plist
     This function converts property list PLIST into the equivalent
     association-list form.  The alist is returned.  This converts from

          (a 1 b 2 c 3)

     into

          ((a . 1) (b . 2) (c . 3))

     The original plist is not modified.

   The following two functions are equivalent to the preceding two
except that they destructively modify their arguments, using cons cells
from the original list to form the new list rather than allocating new
cons cells.

 -- Function: destructive-alist-to-plist alist
     This function destructively converts association list ALIST into
     the equivalent property-list form.  The plist is returned.

 -- Function: destructive-plist-to-alist plist
     This function destructively converts property list PLIST into the
     equivalent association-list form.  The alist is returned.


File: lispref.info,  Node: Weak Lists,  Prev: Property Lists,  Up: Lists

11.10 Weak Lists
================

A "weak list" is a special sort of list whose members are not counted
as references for the purpose of garbage collection.  This means that,
for any object in the list, if there are no references to the object
anywhere outside of the list (or other weak list or weak hash table),
that object will disappear the next time a garbage collection happens.
Weak lists can be useful for keeping track of things such as unobtrusive
lists of another function's buffers or markers.  When that function is
done with the elements, they will automatically disappear from the list.

   Weak lists are used internally, for example, to manage the list
holding the children of an extent--an extent that is unused but has a
parent will still be reclaimed, and will automatically be removed from
its parent's list of children.

   Weak lists are similar to weak hash tables (*note Weak Hash
Tables::).

 -- Function: weak-list-p object
     This function returns non-`nil' if OBJECT is a weak list.

   Weak lists come in one of four types:

`simple'
     Objects in the list disappear if not referenced outside of the
     list.

`assoc'
     Objects in the list disappear if they are conses and either the
     car or the cdr of the cons is not referenced outside of the list.

`key-assoc'
     Objects in the list disappear if they are conses and the car is not
     referenced outside of the list.

`value-assoc'
     Objects in the list disappear if they are conses and the cdr is not
     referenced outside of the list.

 -- Function: make-weak-list &optional type
     This function creates a new weak list of type TYPE.  TYPE is a
     symbol (one of `simple', `assoc', `key-assoc', or `value-assoc',
     as described above) and defaults to `simple'.

 -- Function: weak-list-type weak
     This function returns the type of the given weak-list object.

 -- Function: weak-list-list weak
     This function returns the list contained in a weak-list object.

 -- Function: set-weak-list-list weak new-list
     This function changes the list contained in a weak-list object.


File: lispref.info,  Node: Sequences Arrays Vectors,  Next: Symbols,  Prev: Lists,  Up: Top

12 Sequences, Arrays, and Vectors
*********************************

Recall that the "sequence" type is the union of four other Lisp types:
lists, vectors, bit vectors, and strings.  In other words, any list is
a sequence, any vector is a sequence, any bit vector is a sequence, and
any string is a sequence.  The common property that all sequences have
is that each is an ordered collection of elements.

   An "array" is a single primitive object that has a slot for each
elements.  All the elements are accessible in constant time, but the
length of an existing array cannot be changed.  Strings, vectors, and
bit vectors are the three types of arrays.

   A list is a sequence of elements, but it is not a single primitive
object; it is made of cons cells, one cell per element.  Finding the
Nth element requires looking through N cons cells, so elements farther
from the beginning of the list take longer to access.  But it is
possible to add elements to the list, or remove elements.

   The following diagram shows the relationship between these types:

               ___________________________________
              |                                   |
              |          Sequence                 |
              |  ______   ______________________  |
              | |      | |                      | |
              | | List | |         Array        | |
              | |      | |  ________   _______  | |
              | |______| | |        | |       | | |
              |          | | Vector | | String| | |
              |          | |________| |_______| | |
              |          |  __________________  | |
              |          | |                  | | |
              |          | |    Bit Vector    | | |
              |          | |__________________| | |
              |          |______________________| |
              |___________________________________|

   The elements of vectors and lists may be any Lisp objects.  The
elements of strings are all characters.  The elements of bit vectors
are the numbers 0 and 1.

* Menu:

* Sequence Functions::    Functions that accept any kind of sequence.
* Arrays::                Characteristics of arrays in XEmacs Lisp.
* Array Functions::       Functions specifically for arrays.
* Vectors::               Special characteristics of XEmacs Lisp vectors.
* Vector Functions::      Functions specifically for vectors.
* Bit Vectors::           Special characteristics of XEmacs Lisp bit vectors.
* Bit Vector Functions::  Functions specifically for bit vectors.


File: lispref.info,  Node: Sequence Functions,  Next: Arrays,  Prev: Sequences Arrays Vectors,  Up: Sequences Arrays Vectors

12.1 Sequences
==============

In XEmacs Lisp, a "sequence" is either a list, a vector, a bit vector,
or a string.  The common property that all sequences have is that each
is an ordered collection of elements.  This section describes functions
that accept any kind of sequence.

 -- Function: sequencep object
     Returns `t' if OBJECT is a list, vector, bit vector, or string,
     `nil' otherwise.

 -- Function: copy-sequence sequence
     Returns a copy of SEQUENCE.  The copy is the same type of object
     as the original sequence, and it has the same elements in the same
     order.

     Storing a new element into the copy does not affect the original
     SEQUENCE, and vice versa.  However, the elements of the new
     sequence are not copies; they are identical (`eq') to the elements
     of the original.  Therefore, changes made within these elements, as
     found via the copied sequence, are also visible in the original
     sequence.

     If the sequence is a string with extents or text properties, the
     extents and text properties in the copy are also copied, not
     shared with the original. (This means that modifying the extents
     or text properties of the original will not affect the copy.)
     However, the actual values of the properties are shared.  *Note
     Extents::, *Note Text Properties::.

     See also `append' in *Note Building Lists::, `concat' in *Note
     Creating Strings::, `vconcat' in *Note Vectors::, and `bvconcat'
     in *Note Bit Vectors::, for other ways to copy sequences.

          (setq bar '(1 2))
               => (1 2)
          (setq x (vector 'foo bar))
               => [foo (1 2)]
          (setq y (copy-sequence x))
               => [foo (1 2)]

          (eq x y)
               => nil
          (equal x y)
               => t
          (eq (elt x 1) (elt y 1))
               => t

          ;; Replacing an element of one sequence.
          (aset x 0 'quux)
          x => [quux (1 2)]
          y => [foo (1 2)]

          ;; Modifying the inside of a shared element.
          (setcar (aref x 1) 69)
          x => [quux (69 2)]
          y => [foo (69 2)]

          ;; Creating a bit vector.
          (bit-vector 1 0 1 1 0 1 0 0)
               => #*10110100

 -- Function: length sequence
     Returns the number of elements in SEQUENCE.  If SEQUENCE is a cons
     cell that is not a list (because the final CDR is not `nil'), a
     `wrong-type-argument' error is signaled.

          (length '(1 2 3))
              => 3
          (length ())
              => 0
          (length "foobar")
              => 6
          (length [1 2 3])
              => 3
          (length #*01101)
              => 5

 -- Function: elt sequence index
     This function returns the element of SEQUENCE indexed by INDEX.
     Legitimate values of INDEX are integers ranging from 0 up to one
     less than the length of SEQUENCE.  If SEQUENCE is a list, then
     out-of-range values of INDEX return `nil'; otherwise, they trigger
     an `args-out-of-range' error.

          (elt [1 2 3 4] 2)
               => 3
          (elt '(1 2 3 4) 2)
               => 3
          (char-to-string (elt "1234" 2))
               => "3"
          (elt #*00010000 3)
               => 1
          (elt [1 2 3 4] 4)
               error-->Args out of range: [1 2 3 4], 4
          (elt [1 2 3 4] -1)
               error-->Args out of range: [1 2 3 4], -1

     This function generalizes `aref' (*note Array Functions::) and
     `nth' (*note List Elements::).

 -- Function: fill sequence object &key :start :end
     This function fills the sequence SEQUENCE with OBJECT, so that
     each element of SEQUENCE between the indices specified by `:start'
     (inclusive) and `:end' (exclusive), is OBJECT.  It returns
     SEQUENCE.

          (setq a [a b c d e f g])
               => [a b c d e f g]
          (fill a 0 :end 2)
               => [0 0 c d e f g]
          (fill a 0)
               => [0 0 0 0 0 0 0]
          a
               => [0 0 0 0 0 0 0]

          (setq s "When in the course")
               => "When in the course"
          (fill s ?-)
               => "------------------"

          (setq bv #*1101)
               => #*1101
          (fill bv 0)
               => #*0000

     If SEQUENCE is of a type that cannot hold OBJECT ( bit-vector can
     only hold the integers one or zero, strings can only hold
     characters) a `wrong-type-argument' error results.


File: lispref.info,  Node: Arrays,  Next: Array Functions,  Prev: Sequence Functions,  Up: Sequences Arrays Vectors

12.2 Arrays
===========

An "array" object has slots that hold a number of other Lisp objects,
called the elements of the array.  Any element of an array may be
accessed in constant time.  In contrast, an element of a list requires
access time that is proportional to the position of the element in the
list.

   When you create an array, you must specify how many elements it has.
The amount of space allocated depends on the number of elements.
Therefore, it is impossible to change the size of an array once it is
created; you cannot add or remove elements.  However, you can replace an
element with a different value.

   XEmacs defines three types of array, all of which are
one-dimensional: "strings", "vectors", and "bit vectors".  A vector is a
general array; its elements can be any Lisp objects.  A string is a
specialized array; its elements must be characters.  A bit vector is
another specialized array; its elements must be bits (an integer, either
0 or 1).  Each type of array has its own read syntax.  *Note String
Type::, *Note Vector Type::, and *Note Bit Vector Type::.

   All kinds of array share these characteristics:

   * The first element of an array has index zero, the second element
     has index 1, and so on.  This is called "zero-origin" indexing.
     For example, an array of four elements has indices 0, 1, 2, and 3.

   * The elements of an array may be referenced or changed with the
     functions `aref' and `aset', respectively (*note Array
     Functions::).

   In principle, if you wish to have an array of text characters, you
could use either a string or a vector.  In practice, we always choose
strings for such applications, for four reasons:

   * They usually occupy one-fourth the space of a vector of the same
     elements.  (This is one-eighth the space for 64-bit machines such
     as the DEC Alpha, and may also be different when MULE support is
     compiled into XEmacs.)

   * Strings are printed in a way that shows the contents more clearly
     as characters.

   * Strings can hold extent and text properties.  *Note Extents::,
     *Note Text Properties::.

   * Many of the specialized editing and I/O facilities of XEmacs
     accept only strings.  For example, you cannot insert a vector of
     characters into a buffer the way you can insert a string.  *Note
     Strings and Characters::.

   By contrast, for an array of keyboard input characters (such as a key
sequence), a vector may be necessary, because many keyboard input
characters are non-printable and are represented with symbols rather
than with characters.  *Note Key Sequence Input::.

   Similarly, when representing an array of bits, a bit vector has the
following advantages over a regular vector:

   * They occupy 1/32nd the space of a vector of the same elements.
     (1/64th on 64-bit machines such as the DEC Alpha.)

   * Bit vectors are printed in a way that shows the contents more
     clearly as bits.


File: lispref.info,  Node: Array Functions,  Next: Vectors,  Prev: Arrays,  Up: Sequences Arrays Vectors

12.3 Functions that Operate on Arrays
=====================================

In this section, we describe the functions that accept strings, vectors,
and bit vectors.

 -- Function: arrayp object
     This function returns `t' if OBJECT is an array (i.e., a string,
     vector, or bit vector).

          (arrayp "asdf")
          => t
          (arrayp [a])
          => t
          (arrayp #*101)
          => t

 -- Function: aref array index
     This function returns the INDEXth element of ARRAY.  The first
     element is at index zero.

          (setq primes [2 3 5 7 11 13])
               => [2 3 5 7 11 13]
          (aref primes 4)
               => 11
          (elt primes 4)
               => 11

          (aref "abcdefg" 1)
               => ?b

          (aref #*1101 2)
               => 0

     See also the function `elt', in *Note Sequence Functions::.

 -- Function: aset array index object
     This function sets the INDEXth element of ARRAY to be OBJECT.  It
     returns OBJECT.

          (setq w [foo bar baz])
               => [foo bar baz]
          (aset w 0 'fu)
               => fu
          w
               => [fu bar baz]

          (setq x "asdfasfd")
               => "asdfasfd"
          (aset x 3 ?Z)
               => ?Z
          x
               => "asdZasfd"

          (setq bv #*1111)
               => #*1111
          (aset bv 2 0)
               => 0
          bv
               => #*1101

     If ARRAY is a string and OBJECT is not a character, a
     `wrong-type-argument' error results.

   The general sequence functions `copy-sequence' and `length' are
often useful for objects known to be arrays.  *Note Sequence
Functions::.


File: lispref.info,  Node: Vectors,  Next: Vector Functions,  Prev: Array Functions,  Up: Sequences Arrays Vectors

12.4 Vectors
============

Arrays in Lisp, like arrays in most languages, are blocks of memory
whose elements can be accessed in constant time.  A "vector" is a
general-purpose array; its elements can be any Lisp objects.  (The other
kind of array in XEmacs Lisp is the "string", whose elements must be
characters.)  Vectors in XEmacs serve as obarrays (vectors of symbols),
although this is a shortcoming that should be fixed.  They are also used
internally as part of the representation of a byte-compiled function; if
you print such a function, you will see a vector in it.

   In XEmacs Lisp, the indices of the elements of a vector start from
zero and count up from there.

   Vectors are printed with square brackets surrounding the elements.
Thus, a vector whose elements are the symbols `a', `b' and `a' is
printed as `[a b a]'.  You can write vectors in the same way in Lisp
input.

   A vector, like a string or a number, is considered a constant for
evaluation: the result of evaluating it is the same vector.  This does
not evaluate or even examine the elements of the vector.  *Note
Self-Evaluating Forms::.

   Here are examples of these principles:

     (setq avector [1 two '(three) "four" [five]])
          => [1 two (quote (three)) "four" [five]]
     (eval avector)
          => [1 two (quote (three)) "four" [five]]
     (eq avector (eval avector))
          => t


File: lispref.info,  Node: Vector Functions,  Next: Bit Vectors,  Prev: Vectors,  Up: Sequences Arrays Vectors

12.5 Functions That Operate on Vectors
======================================

Here are some functions that relate to vectors:

 -- Function: vectorp object
     This function returns `t' if OBJECT is a vector.

          (vectorp [a])
               => t
          (vectorp "asdf")
               => nil

 -- Function: vector &rest objects
     This function creates and returns a vector whose elements are the
     arguments, OBJECTS.

          (vector 'foo 23 [bar baz] "rats")
               => [foo 23 [bar baz] "rats"]
          (vector)
               => []

 -- Function: make-vector length object
     This function returns a new vector consisting of LENGTH elements,
     each initialized to OBJECT.

          (setq sleepy (make-vector 9 'Z))
               => [Z Z Z Z Z Z Z Z Z]

 -- Function: vconcat &rest sequences
     This function returns a new vector containing all the elements of
     the SEQUENCES.  The arguments SEQUENCES may be lists, vectors, or
     strings.  If no SEQUENCES are given, an empty vector is returned.

     The value is a newly constructed vector that is not `eq' to any
     existing vector.

          (setq a (vconcat '(A B C) '(D E F)))
               => [A B C D E F]
          (eq a (vconcat a))
               => nil
          (vconcat)
               => []
          (vconcat [A B C] "aa" '(foo (6 7)))
               => [A B C 97 97 foo (6 7)]

     The `vconcat' function also allows integers as arguments.  It
     converts them to strings of digits, making up the decimal print
     representation of the integer, and then uses the strings instead
     of the original integers.  *Don't use this feature; we plan to
     eliminate it.  If you already use this feature, change your
     programs now!*  The proper way to convert an integer to a decimal
     number in this way is with `format' (*note Formatting Strings::)
     or `number-to-string' (*note String Conversion::).

     For other concatenation functions, see `mapconcat' in *Note
     Mapping Functions::, `concat' in *Note Creating Strings::, `append'
     in *Note Building Lists::, and `bvconcat' in *Note Bit Vector
     Functions::.

   The `append' function provides a way to convert a vector into a list
with the same elements (*note Building Lists::):

     (setq avector [1 two (quote (three)) "four" [five]])
          => [1 two (quote (three)) "four" [five]]
     (append avector nil)
          => (1 two (quote (three)) "four" [five])


File: lispref.info,  Node: Bit Vectors,  Next: Bit Vector Functions,  Prev: Vector Functions,  Up: Sequences Arrays Vectors

12.6 Bit Vectors
================

Bit vectors are specialized vectors that can only represent arrays of
1's and 0's.  Bit vectors have a very efficient representation and are
useful for representing sets of boolean (true or false) values.

   There is no limit on the size of a bit vector.  You could, for
example, create a bit vector with 100,000 elements if you really wanted
to.

   Bit vectors have a special printed representation consisting of `#*'
followed by the bits of the vector.  For example, a bit vector whose
elements are 0, 1, 1, 0, and 1, respectively, is printed as

     #*01101

   Bit vectors are considered constants for evaluation, like vectors,
strings, and numbers.  *Note Self-Evaluating Forms::.


File: lispref.info,  Node: Bit Vector Functions,  Prev: Bit Vectors,  Up: Sequences Arrays Vectors

12.7 Functions That Operate on Bit Vectors
==========================================

Here are some functions that relate to bit vectors:

 -- Function: bit-vector-p object
     This function returns `t' if OBJECT is a bit vector.

          (bit-vector-p #*01)
               => t
          (bit-vector-p [0 1])
               => nil
          (bit-vector-p "01")
               => nil

 -- Function: bitp object
     This function returns `t' if OBJECT is either 0 or 1.

 -- Function: bit-vector &rest bits
     This function creates and returns a bit vector whose elements are
     the arguments BITS.  Each argument must be a bit, i.e. one of the
     two integers 0 or 1.

          (bit-vector 0 0 0 1 0 0 0 0 1 0)
               => #*0001000010
          (bit-vector)
               => #*

 -- Function: make-bit-vector length bit
     This function creates and returns a bit vector consisting of
     LENGTH elements, each initialized to BIT, which must be one of the
     two integers 0 or 1.

          (setq picket-fence (make-bit-vector 9 1))
               => #*111111111

 -- Function: bvconcat &rest sequences
     This function returns a new bit vector containing all the elements
     of the SEQUENCES.  The arguments SEQUENCES may be lists, vectors,
     or bit vectors, all of whose elements are the integers 0 or 1.  If
     no SEQUENCES are given, an empty bit vector is returned.

     The value is a newly constructed bit vector that is not `eq' to any
     existing bit vector.

          (setq a (bvconcat '(1 1 0) '(0 0 1)))
               => #*110001
          (eq a (bvconcat a))
               => nil
          (bvconcat)
               => #*
          (bvconcat [1 0 0 0 0] #*111 '(0 0 0 0 1))
               => #*1000011100001

     For other concatenation functions, see `mapconcat' in *Note
     Mapping Functions::, `concat' in *Note Creating Strings::,
     `vconcat' in *Note Vector Functions::, and `append' in *Note
     Building Lists::.

   The `append' function provides a way to convert a bit vector into a
list with the same elements (*note Building Lists::):

     (setq bv #*00001110)
          => #*00001110
     (append bv nil)
          => (0 0 0 0 1 1 1 0)


File: lispref.info,  Node: Symbols,  Next: Evaluation,  Prev: Sequences Arrays Vectors,  Up: Top

13 Symbols
**********

A "symbol" is an object with a unique name.  This chapter describes
symbols, their components, their property lists, and how they are
created and interned.  Separate chapters describe the use of symbols as
variables and as function names; see *Note Variables::, and *Note
Functions and Commands::.  For the precise read syntax for symbols, see
*Note Symbol Type::.

   You can test whether an arbitrary Lisp object is a symbol with
`symbolp':

 -- Function: symbolp object
     This function returns `t' if OBJECT is a symbol, `nil' otherwise.

* Menu:

* Symbol Components::       Symbols have names, values, function definitions
                              and property lists.
* Definitions::             A definition says how a symbol will be used.
* Creating Symbols::        How symbols are kept unique.
* Symbol Properties::       Each symbol has a property list
                              for recording miscellaneous information.


File: lispref.info,  Node: Symbol Components,  Next: Definitions,  Prev: Symbols,  Up: Symbols

13.1 Symbol Components
======================

Each symbol has four components (or "cells"), each of which references
another object:

Print name
     The "print name cell" holds a string that names the symbol for
     reading and printing.  See `symbol-name' in *Note Creating
     Symbols::.

Value
     The "value cell" holds the current value of the symbol as a
     variable.  When a symbol is used as a form, the value of the form
     is the contents of the symbol's value cell.  See `symbol-value' in
     *Note Accessing Variables::.

Function
     The "function cell" holds the function definition of the symbol.
     When a symbol is used as a function, its function definition is
     used in its place.  This cell is also used to make a symbol stand
     for a keymap or a keyboard macro, for editor command execution.
     Because each symbol has separate value and function cells,
     variables and function names do not conflict.  See
     `symbol-function' in *Note Function Cells::.

Property list
     The "property list cell" holds the property list of the symbol.
     See `symbol-plist' in *Note Symbol Properties::.

   The print name cell always holds a string, and cannot be changed.
The other three cells can be set individually to any specified Lisp
object.

   The print name cell holds the string that is the name of the symbol.
Since symbols are represented textually by their names, it is important
not to have two symbols with the same name.  The Lisp reader ensures
this: every time it reads a symbol, it looks for an existing symbol with
the specified name before it creates a new one.  In XEmacs Lisp, this
lookup uses a hash table object; see *Note Creating Symbols::.  In Emacs
Lisp, the symbol with the zero-length name has the special print syntax
`##':

     (intern "")
             => ##

   In normal usage, the function cell usually contains a function or
macro, as that is what the Lisp interpreter expects to see there (*note
Evaluation::).  Keyboard macros (*note Keyboard Macros::), keymaps
(*note Keymaps::) and autoload objects (*note Autoloading::) are also
sometimes stored in the function cell of symbols.  We often refer to
"the function `foo'" when we really mean the function stored in the
function cell of the symbol `foo'.  We make the distinction only when
necessary.

   The property list cell normally should hold a correctly formatted
property list (*note Property Lists::), as a number of functions expect
to see a property list there.

   The function cell or the value cell may be "void", which means that
the cell does not reference any object.  (This is not the same thing as
holding the symbol `void', nor the same as holding the symbol `nil'.)
Examining a cell that is void results in an error, such as `Symbol's
value as variable is void'.

   The four functions `symbol-name', `symbol-value', `symbol-plist',
and `symbol-function' return the contents of the four cells of a
symbol.  Here as an example we show the contents of the four cells of
the symbol `buffer-file-name':

     (symbol-name 'buffer-file-name)
          => "buffer-file-name"
     (symbol-value 'buffer-file-name)
          => "/gnu/elisp/symbols.texi"
     (symbol-plist 'buffer-file-name)
          => (variable-documentation 29529)
     (symbol-function 'buffer-file-name)
          => #<subr buffer-file-name>

Because this symbol is the variable which holds the name of the file
being visited in the current buffer, the value cell contents we see are
the name of the source file of this chapter of the XEmacs Lisp Reference
Manual.  The property list cell contains the list
`(variable-documentation 29529)' which tells the documentation
functions where to find the documentation string for the variable
`buffer-file-name' in the `DOC' file.  (29529 is the offset from the
beginning of the `DOC' file to where that documentation string begins.)
The function cell contains the function for returning the name of the
file.  `buffer-file-name' names a primitive function, which has no read
syntax and prints in hash notation (*note Primitive Function Type::).  A
symbol naming a function written in Lisp would have a lambda expression
(or a byte-code object) in this cell.


File: lispref.info,  Node: Definitions,  Next: Creating Symbols,  Prev: Symbol Components,  Up: Symbols

13.2 Defining Symbols
=====================

A "definition" in Lisp is a special operator that announces your
intention to use a certain symbol in a particular way.  In XEmacs Lisp,
you can define a symbol as a variable, or define it as a function (or
macro), or both independently.

   A definition construct typically specifies a value or meaning for the
symbol for one kind of use, plus documentation for its meaning when used
in this way.  Thus, when you define a symbol as a variable, you can
supply an initial value for the variable, plus documentation for the
variable.

   `defvar' and `defconst' are special operators that define a symbol
as a global variable.  They are documented in detail in *Note Defining
Variables::.

   `defun' defines a symbol as a function, creating a lambda expression
and storing it in the function cell of the symbol.  This lambda
expression thus becomes the function definition of the symbol.  (The
term "function definition", meaning the contents of the function cell,
is derived from the idea that `defun' gives the symbol its definition
as a function.)  `defsubst', `define-function' and `defalias' are other
ways of defining a function.  *Note Functions and Commands::.

   `defmacro' defines a symbol as a macro.  It creates a macro object
and stores it in the function cell of the symbol.  Note that a given
symbol can be a macro or a function, but not both at once, because both
macro and function definitions are kept in the function cell, and that
cell can hold only one Lisp object at any given time.  *Note Macros::.

   In XEmacs Lisp, a definition is not required in order to use a symbol
as a variable or function.  Thus, you can make a symbol a global
variable with `setq', whether you define it first or not.  The real
purpose of definitions is to guide programmers and programming tools.
They inform programmers who read the code that certain symbols are
_intended_ to be used as variables, or as functions.  In addition,
utilities such as `etags' and `make-docfile' recognize definitions, and
add appropriate information to tag tables and the `DOC' file. *Note
Accessing Documentation::.


File: lispref.info,  Node: Creating Symbols,  Next: Symbol Properties,  Prev: Definitions,  Up: Symbols

13.3 Creating and Interning Symbols
===================================

To understand how symbols are created in XEmacs Lisp, you must know how
Lisp reads them.  Lisp must ensure that it finds the same symbol every
time it reads the same set of characters.  Failure to do so would cause
complete confusion.

   When the Lisp reader encounters a symbol, it reads all the characters
of the name.  Then it "hashes" those characters to find an index in a
hash table called "obarray".  Hashing is an efficient method of looking
something up.  For example, instead of searching a telephone book cover
to cover when looking up Jan Jones, you start with the J's and go from
there.  That is a simple version of hashing.

   If a symbol with the desired name is found, the reader uses that
symbol.  If `obarray' does not contain a symbol with that name, the
reader makes a new symbol and adds it to `obarray'.  Finding or adding
a symbol with a certain name is called "interning" it, and the symbol
is then called an "interned symbol".

   Interning ensures that `obarray' has just one symbol with any
particular name.  Other like-named symbols may exist, but not in the
same hash table.  Thus, the reader gets the same symbols for the same
names, as long as you keep reading with the same hash table as the value
of `obarray'.

   No hash table contains all symbols; in fact, some symbols are not in
any hash table.  They are called "uninterned symbols".  An uninterned
symbol has the same four cells as other symbols; however, the only way
to gain access to it is by finding it in some other object or as the
value of a variable.

   In XEmacs Lisp, `obarray' is a normal hash table object describing a
map from strings to symbols; *note Hash Tables::. Current GNU Emacs
implements `obarray' as a Lisp vector and so much Lisp code assumes it
is possible to pass a vector to `intern'; XEmacs has compatibility code
in `obarray.el' to deal with this, which code is called from within
`intern', `intern-soft', `unintern'.

     Common Lisp note: In Common Lisp, a single symbol may be interned
     in several obarrays. There is no barrier to this in XEmacs.

   Most of the functions below take a name and sometimes an obarray as
arguments.  A `wrong-type-argument' error is signaled if the name is
not a string, or if the obarray is not a hash table or (for ugly
compatibility hacks) a Lisp vector.

 -- Function: symbol-name symbol
     This function returns the string that is SYMBOL's name.  For
     example:

          (symbol-name 'foo)
               => "foo"

     Changing the string by substituting characters, etc, does change
     the name of the symbol, but fails to update the obarray, so don't
     do it!

 -- Function: make-symbol name
     This function returns a newly-allocated, uninterned symbol whose
     name is NAME (which must be a string).  Its value and function
     definition are void, and its property list is `nil'.  In the
     example below, the value of `sym' is not `eq' to `foo' because it
     is a distinct uninterned symbol whose name is also `foo'.

          (setq sym (make-symbol "foo"))
               => foo
          (eq sym 'foo)
               => nil

 -- Function: intern name &optional obarray
     This function returns the interned symbol whose name is NAME.  If
     there is no such symbol in OBARRAY, `intern' creates a new one,
     adds it to the obarray, and returns it.  If OBARRAY is omitted,
     the value of the global variable `obarray' is used.

          (setq sym (intern "foo"))
               => foo
          (eq sym 'foo)
               => t

          (setq sym1 (intern "foo" other-obarray))
               => foo
          (eq sym 'foo)
               => nil

 -- Function: intern-soft name &optional obarray
     This function returns the symbol in OBARRAY whose name is NAME, or
     `nil' if OBARRAY has no symbol with that name.  Therefore, you can
     use `intern-soft' to test whether a symbol with a given name is
     already interned.  If OBARRAY is omitted, the value of the global
     variable `obarray' is used.

          (intern-soft "frazzle")        ; No such symbol exists.
               => nil
          (make-symbol "frazzle")        ; Create an uninterned one.
               => frazzle
          (intern-soft "frazzle")        ; That one cannot be found.
               => nil
          (setq sym (intern "frazzle"))  ; Create an interned one.
               => frazzle
          (intern-soft "frazzle")        ; That one can be found!
               => frazzle
          (eq sym 'frazzle)              ; And it is the same one.
               => t

 -- Variable: obarray
     This variable is the standard obarray for use by `intern' and
     `read'.

 -- Function: mapatoms function &optional (package obarray)
     This function calls FUNCTION for each symbol in PACKAGE.  It
     returns `nil'.  If PACKAGE is omitted, it defaults to the value of
     `obarray', the standard package for ordinary symbols.

          (setq count 0)
               => 0
          (defun count-syms (s)
            (setq count (1+ count)))
               => count-syms
          (mapatoms 'count-syms)
               => nil
          count
               => 1871

     See `documentation' in *Note Accessing Documentation::, for another
     example using `mapatoms'.

 -- Function: unintern symbol &optional obarray
     This function deletes SYMBOL from the obarray OBARRAY.  If
     `symbol' is not actually in the obarray, `unintern' does nothing.
     If OBARRAY is `nil', the current obarray is used.

     If you provide a string instead of a symbol as SYMBOL, it stands
     for a symbol name.  Then `unintern' deletes the symbol (if any) in
     the obarray which has that name.  If there is no such symbol,
     `unintern' does nothing.

     If `unintern' does delete a symbol, it returns `t'.  Otherwise it
     returns `nil'.


File: lispref.info,  Node: Symbol Properties,  Prev: Creating Symbols,  Up: Symbols

13.4 Symbol Properties
======================

A "property list" ("plist" for short) is a list of paired elements,
often stored in the property list cell of a symbol.  Each of the pairs
associates a property name (usually a symbol) with a property or value.
Property lists are generally used to record information about a
symbol, such as its documentation as a variable, the name of the file
where it was defined, or perhaps even the grammatical class of the
symbol (representing a word) in a language-understanding system.

   Some objects which are not symbols also have property lists
associated with them, and XEmacs provides a full complement of
functions for working with property lists.  *Note Property Lists::.

   The property names and values in a property list can be any Lisp
objects, but the names are usually symbols.  They are compared using
`eq'.  Here is an example of a property list, found on the symbol
`progn' when the compiler is loaded:

     (lisp-indent-function 0 byte-compile byte-compile-progn)

Here `lisp-indent-function' and `byte-compile' are property names, and
the other two elements are the corresponding values.

* Menu:

* Plists and Alists::           Comparison of the advantages of property
                                  lists and association lists.
* Object Plists::               Functions to access objects' property lists.
* Other Plists::                Accessing property lists stored elsewhere.


File: lispref.info,  Node: Plists and Alists,  Next: Object Plists,  Prev: Symbol Properties,  Up: Symbol Properties

13.4.1 Property Lists and Association Lists
-------------------------------------------

Association lists (*note Association Lists::) are very similar to
property lists.  In contrast to association lists, the order of the
pairs in the property list is not significant since the property names
must be distinct.

   Property lists are better than association lists for attaching
information to various Lisp function names or variables.  If all the
associations are recorded in one association list, the program will need
to search that entire list each time a function or variable is to be
operated on.  By contrast, if the information is recorded in the
property lists of the function names or variables themselves, each
search will scan only the length of one property list, which is usually
short.  This is why the documentation for a variable is recorded in a
property named `variable-documentation'.  The byte compiler likewise
uses properties to record those functions needing special treatment.

   However, association lists have their own advantages.  Depending on
your application, it may be faster to add an association to the front of
an association list than to update a property.  All properties for a
symbol are stored in the same property list, so there is a possibility
of a conflict between different uses of a property name.  (For this
reason, it is a good idea to choose property names that are probably
unique, such as by including the name of the library in the property
name.)  An association list may be used like a stack where associations
are pushed on the front of the list and later discarded; this is not
possible with a property list.


File: lispref.info,  Node: Object Plists,  Next: Other Plists,  Prev: Plists and Alists,  Up: Symbol Properties

13.4.2 Property List Functions for Objects
------------------------------------------

Once upon a time, only symbols had property lists.  Now, several other
object types, including strings, extents, faces and glyphs also have
property lists.

 -- Function: symbol-plist symbol
     This function returns the property list of SYMBOL.

 -- Function: object-plist object
     This function returns the property list of OBJECT.  If OBJECT is a
     symbol, this is identical to `symbol-plist'.

 -- Function: setplist symbol plist
     This function sets SYMBOL's property list to PLIST.  Normally,
     PLIST should be a well-formed property list, but this is not
     enforced.

          (setplist 'foo '(a 1 b (2 3) c nil))
               => (a 1 b (2 3) c nil)
          (symbol-plist 'foo)
               => (a 1 b (2 3) c nil)

     For symbols in special obarrays, which are not used for ordinary
     purposes, it may make sense to use the property list cell in a
     nonstandard fashion; in fact, the abbrev mechanism does so (*note
     Abbrevs::).  But generally, its use is discouraged.  Use `put'
     instead.  `setplist' can only be used with symbols, not other
     object types.

 -- Function: get object property &optional default
     This function finds the value of the property named PROPERTY in
     OBJECT's property list.  If there is no such property, `default'
     (which itself defaults to `nil') is returned.

     PROPERTY is compared with the existing properties using `eq', so
     any object is a legitimate property.

     See `put' for an example.

 -- Function: put object property value
     This function puts VALUE onto OBJECT's property list under the
     property name PROPERTY, replacing any previous property value.
     The `put' function returns VALUE.

          (put 'fly 'verb 'transitive)
               =>'transitive
          (put 'fly 'noun '(a buzzing little bug))
               => (a buzzing little bug)
          (get 'fly 'verb)
               => transitive
          (object-plist 'fly)
               => (verb transitive noun (a buzzing little bug))

 -- Function: remprop object property
     This function removes the entry for PROPERTY from the property
     list of OBJECT.  It returns `t' if the property was indeed found
     and removed, or `nil' if there was no such property.  (This
     function was probably omitted from Emacs originally because, since
     `get' did not allow a DEFAULT, it was very difficult to
     distinguish between a missing property and a property whose value
     was `nil'; thus, setting a property to `nil' was close enough to
     `remprop' for most purposes.)


File: lispref.info,  Node: Other Plists,  Prev: Object Plists,  Up: Symbol Properties

13.4.3 Property Lists Not Associated with Objects
-------------------------------------------------

These functions are useful for manipulating property lists that are
stored in places other than symbols:

 -- Function: getf plist property &optional default
     This returns the value of the PROPERTY property stored in the
     property list PLIST.  For example,

          (getf '(foo 4) 'foo)
               => 4

 -- Macro: putf plist property value
     This stores VALUE as the value of the PROPERTY property in the
     property list PLIST.  It may modify PLIST destructively, or it may
     construct a new list structure without altering the old.  The
     function returns the modified property list, so you can store that
     back in the place where you got PLIST.  For example,

          (setq my-plist '(bar t foo 4))
               => (bar t foo 4)
          (setq my-plist (putf my-plist 'foo 69))
               => (bar t foo 69)
          (setq my-plist (putf my-plist 'quux '(a)))
               => (quux (a) bar t foo 5)

 -- Function: plists-eq a b
     This function returns non-`nil' if property lists A and B are
     `eq'.  This means that the property lists have the same values for
     all the same properties, where comparison between values is done
     using `eq'.

 -- Function: plists-equal a b
     This function returns non-`nil' if property lists A and B are
     `equal'.

   Both of the above functions do order-insensitive comparisons.

     (plists-eq '(a 1 b 2 c nil) '(b 2 a 1))
          => t
     (plists-eq '(foo "hello" bar "goodbye") '(bar "goodbye" foo "hello"))
          => nil
     (plists-equal '(foo "hello" bar "goodbye") '(bar "goodbye" foo "hello"))
          => t


File: lispref.info,  Node: Evaluation,  Next: Control Structures,  Prev: Symbols,  Up: Top

14 Evaluation
*************

The "evaluation" of expressions in XEmacs Lisp is performed by the
"Lisp interpreter"--a program that receives a Lisp object as input and
computes its "value as an expression".  How it does this depends on the
data type of the object, according to rules described in this chapter.
The interpreter runs automatically to evaluate portions of your
program, but can also be called explicitly via the Lisp primitive
function `eval'.

* Menu:

* Intro Eval::  Evaluation in the scheme of things.
* Eval::        How to invoke the Lisp interpreter explicitly.
* Forms::       How various sorts of objects are evaluated.
* Quoting::     Avoiding evaluation (to put constants in the program).
* Multiple values:: Functions may return more than one result.


File: lispref.info,  Node: Intro Eval,  Next: Eval,  Prev: Evaluation,  Up: Evaluation

14.1 Introduction to Evaluation
===============================

The Lisp interpreter, or evaluator, is the program that computes the
value of an expression that is given to it.  When a function written in
Lisp is called, the evaluator computes the value of the function by
evaluating the expressions in the function body.  Thus, running any
Lisp program really means running the Lisp interpreter.

   How the evaluator handles an object depends primarily on the data
type of the object.

   A Lisp object that is intended for evaluation is called an
"expression" or a "form".  The fact that expressions are data objects
and not merely text is one of the fundamental differences between
Lisp-like languages and typical programming languages.  Any object can
be evaluated, but in practice only numbers, symbols, lists and strings
are evaluated very often.

   It is very common to read a Lisp expression and then evaluate the
expression, but reading and evaluation are separate activities, and
either can be performed alone.  Reading per se does not evaluate
anything; it converts the printed representation of a Lisp object to the
object itself.  It is up to the caller of `read' whether this object is
a form to be evaluated, or serves some entirely different purpose.
*Note Input Functions::.

   Do not confuse evaluation with command key interpretation.  The
editor command loop translates keyboard input into a command (an
interactively callable function) using the active keymaps, and then
uses `call-interactively' to invoke the command.  The execution of the
command itself involves evaluation if the command is written in Lisp,
but that is not a part of command key interpretation itself.  *Note
Command Loop::.

   Evaluation is a recursive process.  That is, evaluation of a form may
call `eval' to evaluate parts of the form.  For example, evaluation of
a function call first evaluates each argument of the function call, and
then evaluates each form in the function body.  Consider evaluation of
the form `(car x)': the subform `x' must first be evaluated
recursively, so that its value can be passed as an argument to the
function `car'.

   Evaluation of a function call ultimately calls the function specified
in it.  *Note Functions and Commands::.  The execution of the function
may itself work by evaluating the function definition; or the function
may be a Lisp primitive implemented in C, or it may be a byte-compiled
function (*note Byte Compilation::).

   The evaluation of forms takes place in a context called the
"environment", which consists of the current values and bindings of all
Lisp variables.(1)  Whenever the form refers to a variable without
creating a new binding for it, the value of the binding in the current
environment is used.  *Note Variables::.

   Evaluation of a form may create new environments for recursive
evaluation by binding variables (*note Local Variables::).  These
environments are temporary and vanish by the time evaluation of the form
is complete.  The form may also make changes that persist; these changes
are called "side effects".  An example of a form that produces side
effects is `(setq foo 1)'.

   The details of what evaluation means for each kind of form are
described below (*note Forms::).

   ---------- Footnotes ----------

   (1) This definition of "environment" is specifically not intended to
include all the data that can affect the result of a program.


File: lispref.info,  Node: Eval,  Next: Forms,  Prev: Intro Eval,  Up: Evaluation

14.2 Eval
=========

Most often, forms are evaluated automatically, by virtue of their
occurrence in a program being run.  On rare occasions, you may need to
write code that evaluates a form that is computed at run time, such as
after reading a form from text being edited or getting one from a
property list.  On these occasions, use the `eval' function.

   *Please note:* it is generally cleaner and more flexible to call
functions that are stored in data structures, rather than to evaluate
expressions stored in data structures.  Using functions provides the
ability to pass information to them as arguments.

   The functions and variables described in this section evaluate forms,
specify limits to the evaluation process, or record recently returned
values.  Loading a file also does evaluation (*note Loading::).

 -- Function: eval form
     This is the basic function for performing evaluation.  It evaluates
     FORM in the current environment and returns the result.  How the
     evaluation proceeds depends on the type of the object (*note
     Forms::).

     Since `eval' is a function, the argument expression that appears
     in a call to `eval' is evaluated twice: once as preparation before
     `eval' is called, and again by the `eval' function itself.  Here
     is an example:

          (setq foo 'bar)
               => bar
          (setq bar 'baz)
               => baz
          ;; `eval' receives argument `bar', which is the value of `foo'
          (eval foo)
               => baz
          (eval 'foo)
               => bar

     The number of currently active calls to `eval' is limited to
     `max-lisp-eval-depth' (see below).

 -- Command: eval-region start end &optional stream
     This function evaluates the forms in the current buffer in the
     region defined by the positions START and END.  It reads forms from
     the region and calls `eval' on them until the end of the region is
     reached, or until an error is signaled and not handled.

     If STREAM is supplied, `standard-output' is bound to it during the
     evaluation.

     You can use the variable `load-read-function' to specify a function
     for `eval-region' to use instead of `read' for reading
     expressions.  *Note How Programs Do Loading::.

     `eval-region' always returns `nil'.

 -- Command: eval-buffer buffer &optional stream
     This is like `eval-region' except that it operates on the whole
     contents of BUFFER.

 -- Variable: max-lisp-eval-depth
     This variable defines the maximum depth allowed in calls to `eval',
     `apply', and `funcall' before an error is signaled (with error
     message `"Lisp nesting exceeds max-lisp-eval-depth"').  This counts
     internal uses of those functions, such as for calling the functions
     mentioned in Lisp expressions, and recursive evaluation of
     function call arguments and function body forms.

     This limit, with the associated error when it is exceeded, is one
     way that Lisp avoids infinite recursion on an ill-defined function.  

     The default value of this variable is 1000.  If you set it to a
     value less than 100, Lisp will reset it to 100 if the given value
     is reached.

     `max-specpdl-size' provides another limit on nesting.  *Note Local
     Variables::.

 -- Variable: values
     The value of this variable is a list of the values returned by all
     the expressions that were read from buffers (including the
     minibuffer), evaluated, and printed.  The elements are ordered
     most recent first.

          (setq x 1)
               => 1
          (list 'A (1+ 2) auto-save-default)
               => (A 3 t)
          values
               => ((A 3 t) 1 ...)

     This variable is useful for referring back to values of forms
     recently evaluated.  It is generally a bad idea to print the value
     of `values' itself, since this may be very long.  Instead, examine
     particular elements, like this:

          ;; Refer to the most recent evaluation result.
          (nth 0 values)
               => (A 3 t)
          ;; That put a new element on,
          ;;   so all elements move back one.
          (nth 1 values)
               => (A 3 t)
          ;; This gets the element that was next-to-most-recent
          ;;   before this example.
          (nth 3 values)
               => 1


File: lispref.info,  Node: Forms,  Next: Quoting,  Prev: Eval,  Up: Evaluation

14.3 Kinds of Forms
===================

A Lisp object that is intended to be evaluated is called a "form".  How
XEmacs evaluates a form depends on its data type.  XEmacs has three
different kinds of form that are evaluated differently: symbols, lists,
and "all other types".  This section describes all three kinds,
starting with "all other types" which are self-evaluating forms.

* Menu:

* Self-Evaluating Forms::   Forms that evaluate to themselves.
* Symbol Forms::            Symbols evaluate as variables.
* Classifying Lists::       How to distinguish various sorts of list forms.
* Function Indirection::    When a symbol appears as the car of a list,
			      we find the real function via the symbol.
* Function Forms::          Forms that call functions.
* Macro Forms::             Forms that call macros.
* Special Operators::       ``Special operators'' are idiosyncratic primitives,
                              most of them extremely important.
                              Also known as special forms.
* Autoloading::             Functions set up to load files
                              containing their real definitions.


File: lispref.info,  Node: Self-Evaluating Forms,  Next: Symbol Forms,  Prev: Forms,  Up: Forms

14.3.1 Self-Evaluating Forms
----------------------------

A "self-evaluating form" is any form that is not a list or symbol.
Self-evaluating forms evaluate to themselves: the result of evaluation
is the same object that was evaluated.  Thus, the number 25 evaluates to
25, and the string `"foo"' evaluates to the string `"foo"'.  Likewise,
evaluation of a vector does not cause evaluation of the elements of the
vector--it returns the same vector with its contents unchanged.

     '123               ; An object, shown without evaluation.
          => 123
     123                ; Evaluated as usual--result is the same.
          => 123
     (eval '123)        ; Evaluated "by hand"--result is the same.
          => 123
     (eval (eval '123)) ; Evaluating twice changes nothing.
          => 123

   It is common to write numbers, characters, strings, and even vectors
in Lisp code, taking advantage of the fact that they self-evaluate.
However, it is quite unusual to do this for types that lack a read
syntax, because there's no way to write them textually.  It is possible
to construct Lisp expressions containing these types by means of a Lisp
program.  Here is an example:

     ;; Build an expression containing a buffer object.
     (setq buffer (list 'print (current-buffer)))
          => (print #<buffer eval.texi>)
     ;; Evaluate it.
     (eval buffer)
          -| #<buffer eval.texi>
          => #<buffer eval.texi>


File: lispref.info,  Node: Symbol Forms,  Next: Classifying Lists,  Prev: Self-Evaluating Forms,  Up: Forms

14.3.2 Symbol Forms
-------------------

When a symbol is evaluated, it is treated as a variable.  The result is
the variable's value, if it has one.  If it has none (if its value cell
is void), an error is signaled.  For more information on the use of
variables, see *Note Variables::.

   In the following example, we set the value of a symbol with `setq'.
Then we evaluate the symbol, and get back the value that `setq' stored.

     (setq a 123)
          => 123
     (eval 'a)
          => 123
     a
          => 123

   The symbols `nil' and `t' are treated specially, so that the value
of `nil' is always `nil', and the value of `t' is always `t'; you
cannot set or bind them to any other values.  Thus, these two symbols
act like self-evaluating forms, even though `eval' treats them like any
other symbol.


File: lispref.info,  Node: Classifying Lists,  Next: Function Indirection,  Prev: Symbol Forms,  Up: Forms

14.3.3 Classification of List Forms
-----------------------------------

A form that is a nonempty list is either a function call, a macro call,
or a special form, according to its first element.  These three kinds
of forms are evaluated in different ways, described below.  The
remaining list elements constitute the "arguments" for the function,
macro, or special operator.

   The first step in evaluating a nonempty list is to examine its first
element.  This element alone determines what kind of form the list is
and how the rest of the list is to be processed.  The first element is
_not_ evaluated, as it would be in some Lisp dialects such as Scheme.


File: lispref.info,  Node: Function Indirection,  Next: Function Forms,  Prev: Classifying Lists,  Up: Forms

14.3.4 Symbol Function Indirection
----------------------------------

If the first element of the list is a symbol then evaluation examines
the symbol's function cell, and uses its contents instead of the
original symbol.  If the contents are another symbol, this process,
called "symbol function indirection", is repeated until it obtains a
non-symbol.  *Note Function Names::, for more information about using a
symbol as a name for a function stored in the function cell of the
symbol.

   One possible consequence of this process is an infinite loop, in the
event that a symbol's function cell refers to the same symbol.  Or a
symbol may have a void function cell, in which case the subroutine
`symbol-function' signals a `void-function' error.  But if neither of
these things happens, we eventually obtain a non-symbol, which ought to
be a function or other suitable object.

   More precisely, we should now have a Lisp function (a lambda
expression), a byte-code function, a primitive function, a Lisp macro, a
special operator, or an autoload object.  Each of these types is a case
described in one of the following sections.  If the object is not one of
these types, the error `invalid-function' is signaled.

   The following example illustrates the symbol indirection process.  We
use `fset' to set the function cell of a symbol and `symbol-function'
to get the function cell contents (*note Function Cells::).
Specifically, we store the symbol `car' into the function cell of
`first', and the symbol `first' into the function cell of `erste'.

     ;; Build this function cell linkage:
     ;;   -------------       -----        -------        -------
     ;;  | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
     ;;   -------------       -----        -------        -------

     (symbol-function 'car)
          => #<subr car>
     (fset 'first 'car)
          => car
     (fset 'erste 'first)
          => first
     (erste '(1 2 3))   ; Call the function referenced by `erste'.
          => 1

   By contrast, the following example calls a function without any
symbol function indirection, because the first element is an anonymous
Lisp function, not a symbol.

     ((lambda (arg) (erste arg))
      '(1 2 3))
          => 1

Executing the function itself evaluates its body; this does involve
symbol function indirection when calling `erste'.

   The built-in function `indirect-function' provides an easy way to
perform symbol function indirection explicitly.

 -- Function: indirect-function object
     This function returns the meaning of OBJECT as a function.  If
     OBJECT is a symbol, then it finds OBJECT's function definition and
     starts over with that value.  If OBJECT is not a symbol, then it
     returns OBJECT itself.

     Here is how you could define `indirect-function' in Lisp:

          (defun indirect-function (function)
            (if (symbolp function)
                (indirect-function (symbol-function function))
              function))


File: lispref.info,  Node: Function Forms,  Next: Macro Forms,  Prev: Function Indirection,  Up: Forms

14.3.5 Evaluation of Function Forms
-----------------------------------

If the first element of a list being evaluated is a Lisp function
object, byte-code object or primitive function object, then that list is
a "function call".  For example, here is a call to the function `+':

     (+ 1 x)

   The first step in evaluating a function call is to evaluate the
remaining elements of the list from left to right.  The results are the
actual argument values, one value for each list element.  The next step
is to call the function with this list of arguments, effectively using
the function `apply' (*note Calling Functions::).  If the function is
written in Lisp, the arguments are used to bind the argument variables
of the function (*note Lambda Expressions::); then the forms in the
function body are evaluated in order, and the value of the last body
form becomes the value of the function call.


File: lispref.info,  Node: Macro Forms,  Next: Special Operators,  Prev: Function Forms,  Up: Forms

14.3.6 Lisp Macro Evaluation
----------------------------

If the first element of a list being evaluated is a macro object, then
the list is a "macro call".  When a macro call is evaluated, the
elements of the rest of the list are _not_ initially evaluated.
Instead, these elements themselves are used as the arguments of the
macro.  The macro definition computes a replacement form, called the
"expansion" of the macro, to be evaluated in place of the original
form.  The expansion may be any sort of form: a self-evaluating
constant, a symbol, or a list.  If the expansion is itself a macro call,
this process of expansion repeats until some other sort of form results.

   Ordinary evaluation of a macro call finishes by evaluating the
expansion.  However, the macro expansion is not necessarily evaluated
right away, or at all, because other programs also expand macro calls,
and they may or may not evaluate the expansions.

   Normally, the argument expressions are not evaluated as part of
computing the macro expansion, but instead appear as part of the
expansion, so they are computed when the expansion is computed.

   For example, given a macro defined as follows:

     (defmacro cadr (x)
       (list 'car (list 'cdr x)))

an expression such as `(cadr (assq 'handler list))' is a macro call,
and its expansion is:

     (car (cdr (assq 'handler list)))

Note that the argument `(assq 'handler list)' appears in the expansion.

   *Note Macros::, for a complete description of XEmacs Lisp macros.


File: lispref.info,  Node: Special Operators,  Next: Autoloading,  Prev: Macro Forms,  Up: Forms

14.3.7 Special Operators
------------------------

A "special operator" (historically, and less logically, a "special
form") is a primitive function specially marked so that its arguments
are not all evaluated.  Most special operators define control
structures or perform variable bindings--things which functions cannot
do.

   Each special operator has its own rules for which arguments are
evaluated and which are used without evaluation.  Whether a particular
argument is evaluated may depend on the results of evaluating other
arguments.

   Here is a list, in alphabetical order, of all of the special
operators in XEmacs Lisp with a reference to where each is described.

`and'
     *note Combining Conditions::

`catch'
     *note Catch and Throw::

`cond'
     *note Conditionals::

`condition-case'
     *note Handling Errors::

`defconst'
     *note Defining Variables::

`defmacro'
     *note Defining Macros::

`defun'
     *note Defining Functions::

`defvar'
     *note Defining Variables::

`function'
     *note Anonymous Functions::

`if'
     *note Conditionals::

`interactive'
     *note Interactive Call::

`let'
`let*'
     *note Local Variables::

`or'
     *note Combining Conditions::

`prog1'
`prog2'
`progn'
     *note Sequencing::

`quote'
     *note Quoting::

`save-current-buffer'
     *note Excursions::

`save-excursion'
     *note Excursions::

`save-restriction'
     *note Narrowing::

`save-selected-window'
     *note Excursions::

`save-window-excursion'
     *note Window Configurations::

`setq'
     *note Setting Variables::

`setq-default'
     *note Creating Buffer-Local::

`unwind-protect'
     *note Nonlocal Exits::

`while'
     *note Iteration::

`with-output-to-temp-buffer'
     *note Temporary Displays::

     Common Lisp note: here are some comparisons of special operators in
     XEmacs Lisp and Common Lisp.  `setq', `if', and `catch' are
     special operators in both XEmacs Lisp and Common Lisp.  `defun' is
     a special operator in XEmacs Lisp, but a macro in Common Lisp.
     `save-excursion' is a special operator in XEmacs Lisp, but doesn't
     exist in Common Lisp.  `throw' is a special operator in both
     Common Lisp and XEmacs Lisp (because it must be able to throw
     multiple values).


File: lispref.info,  Node: Autoloading,  Prev: Special Operators,  Up: Forms

14.3.8 Autoloading
------------------

The "autoload" feature allows you to call a function or macro whose
function definition has not yet been loaded into XEmacs.  It specifies
which file contains the definition.  When an autoload object appears as
a symbol's function definition, calling that symbol as a function
automatically loads the specified file; then it calls the real
definition loaded from that file.  *Note Autoload::.


File: lispref.info,  Node: Quoting,  Next: Multiple values,  Prev: Forms,  Up: Evaluation

14.4 Quoting
============

The special operator `quote' returns its single argument, as written,
without evaluating it.  This provides a way to include constant symbols
and lists, which are not self-evaluating objects, in a program.  (It is
not necessary to quote self-evaluating objects such as numbers, strings,
and vectors.)

 -- Special Operator: quote object
     This special operator returns OBJECT, without evaluating it.

   Because `quote' is used so often in programs, Lisp provides a
convenient read syntax for it.  An apostrophe character (`'') followed
by a Lisp object (in read syntax) expands to a list whose first element
is `quote', and whose second element is the object.  Thus, the read
syntax `'x' is an abbreviation for `(quote x)'.

   Here are some examples of expressions that use `quote':

     (quote (+ 1 2))
          => (+ 1 2)
     (quote foo)
          => foo
     'foo
          => foo
     ''foo
          => (quote foo)
     '(quote foo)
          => (quote foo)
     ['foo]
          => [(quote foo)]

   Other quoting constructs include `function' (*note Anonymous
Functions::), which causes an anonymous lambda expression written in
Lisp to be compiled, and ``' (*note Backquote::), which is used to quote
only part of a list, while computing and substituting other parts.


File: lispref.info,  Node: Multiple values,  Prev: Quoting,  Up: Evaluation

14.5 Multiple values
====================

Under XEmacs, expressions can return zero or more results, using the
`values' and `values-list' functions. Results other than the first are
typically discarded, but special operators are provided to access them.

 -- Function: values arguments...
     This function returns ARGUMENTS as multiple values. Callers will
     always receive the first element of ARGUMENTS, but must use
     various special operators, described below, to access other
     elements of ARGUMENTS.

     The idiom `(values (function-call argument))', with one argument,
     is the normal mechanism to avoid passing multiple values to the
     calling form where that is not desired.

     XEmacs implements the Common Lisp specification when it comes to
     the exact details of when to discard and when to preserve multiple
     values; see Common Lisp the Language or the Common Lisp hyperspec
     for more details.  The most important thing to keep in mind is
     when multiple values are passed as an argument to a function, all
     but the first are discarded.

 -- Function: values-list argument
     This function returns the elements of the lst ARGUMENT as multiple
     values.

 -- Macro: multiple-value-bind (var...) values-form forms...
     This macro evaluates VALUES-FORM, which may return multiple
     values.  It then binds the VARs to these respective values, as if
     by `let', and then executes the body FORMS.  If there are more
     VARs than values, the extra VARs are bound to `nil'.  If there are
     fewer VARs than values, the excess values are ignored.

 -- Macro: multiple-value-setq (var...) form
     This macro evaluates FORM, which may return multiple values. It
     then sets the VARs to these respective values, as if by `setq'.
     Extra VARs or values are treated the same as in
     `multiple-value-bind'.

 -- Special Operator: multiple-value-call function forms...
     This special operator evaluates function, discarding any multiple
     values.  It then evaluates FORMS, preserving any multiple values,
     and calls FUNCTION as a function with the results.  Conceptually,
     this function is a version of `apply''that by-passes the multiple
     values infrastructure, treating multiple values as intercalated
     lists.

 -- Macro: multiple-value-list form
     This macro evaluates FORM and returns a list of the multiple
     values given by it.

 -- Special Operator: multiple-value-prog1 first body...
     This special operator evaluates the form FIRST, then the forms
     BODY.  It returns the value given by FIRST, preserving any
     multiple values.  This is identical to `prog1', except that
     `prog1' always discards multiple values.

 -- Macro: nth-value n form
     This macro evaluates FORM and returns the Nth value it gave.  N
     must be an integer of value zero or more.  If FORM gave
     insufficient multiple values, `nth-value' returns `nil'.

 -- Variable: multiple-values-limit
     This constant describes the exclusive upper bound on the number of
     multiple values that `values' accepts and that
     `multiple-value-bind', etc. will consume.

   To take full advantage of multiple values, Emacs Lisp code must have
been compiled by XEmacs 21.5 or later, which is not yet true of the
XEmacs packages.  Matched `values' and `multiple-value-bind' calls will
work in code included in the XEmacs packages when run on 21.5, though
the following incantation may be necessary at the start of your file,
until appropriate code is included in XEmacs 21.4:

     (eval-when-compile (when (eq 'list (symbol-function 'values))
                          (define-compiler-macro values (&rest args)
                            (cons 'list args))
                          (define-compiler-macro values-list (list) list)))

   Such code cannot, unfortunately, rely on XEmacs to discard multiple
values where that is appropriate.


File: lispref.info,  Node: Control Structures,  Next: Variables,  Prev: Evaluation,  Up: Top

15 Control Structures
*********************

A Lisp program consists of expressions or "forms" (*note Forms::).  We
control the order of execution of the forms by enclosing them in
"control structures".  Control structures are special operators which
control when, whether, or how many times to execute the subforms of
their containing forms.

   The simplest order of execution is sequential execution: first form
A, then form B, and so on.  This is what happens when you write several
forms in succession in the body of a function, or at top level in a
file of Lisp code--the forms are executed in the order written.  We
call this "textual order".  For example, if a function body consists of
two forms A and B, evaluation of the function evaluates first A and
then B, and the function's value is the value of B.

   Explicit control structures make possible an order of execution other
than sequential.

   XEmacs Lisp provides several kinds of control structure, including
other varieties of sequencing, conditionals, iteration, and (controlled)
jumps--all discussed below.  The built-in control structures are
special operators since their enclosing forms' subforms are not
necessarily evaluated or not evaluated sequentially.  You can use macros
to define your own control structure constructs (*note Macros::).

* Menu:

* Sequencing::             Evaluation in textual order.
* Conditionals::           `if', `cond'.
* Combining Conditions::   `and', `or', `not'.
* Iteration::              `while' loops.
* Nonlocal Exits::         Jumping out of a sequence.


File: lispref.info,  Node: Sequencing,  Next: Conditionals,  Prev: Control Structures,  Up: Control Structures

15.1 Sequencing
===============

Evaluating forms in the order they appear is the most common way
control passes from one form to another.  In some contexts, such as in a
function body, this happens automatically.  Elsewhere you must use a
control structure construct to do this: `progn', the simplest control
construct of Lisp.

   A `progn' special form looks like this:

     (progn A B C ...)

and it says to execute the forms A, B, C and so on, in that order.
These forms are called the body of the `progn' form.  The value of the
last form in the body becomes the value of the entire `progn'.

   In the early days of Lisp, `progn' was the only way to execute two
or more forms in succession and use the value of the last of them.  But
programmers found they often needed to use a `progn' in the body of a
function, where (at that time) only one form was allowed.  So the body
of a function was made into an "implicit `progn'": several forms are
allowed just as in the body of an actual `progn'.  Many other control
structures likewise contain an implicit `progn'.  As a result, `progn'
is not used as often as it used to be.  It is needed now most often
inside an `unwind-protect', `and', `or', or in the THEN-part of an `if'.

 -- Special Operator: progn forms...
     This special operator evaluates all of the FORMS, in textual
     order, returning the result of the final form.

          (progn (print "The first form")
                 (print "The second form")
                 (print "The third form"))
               -| "The first form"
               -| "The second form"
               -| "The third form"
          => "The third form"

   Two other control constructs likewise evaluate a series of forms but
return a different value:

 -- Special Operator: prog1 form1 forms...
     This special operator evaluates FORM1 and all of the FORMS, in
     textual order, returning the result of FORM1.

          (prog1 (print "The first form")
                 (print "The second form")
                 (print "The third form"))
               -| "The first form"
               -| "The second form"
               -| "The third form"
          => "The first form"

     Here is a way to remove the first element from a list in the
     variable `x', then return the value of that former element:

          (prog1 (car x) (setq x (cdr x)))

 -- Special Operator: prog2 form1 form2 forms...
     This special operator evaluates FORM1, FORM2, and all of the
     following FORMS, in textual order, returning the result of FORM2.

          (prog2 (print "The first form")
                 (print "The second form")
                 (print "The third form"))
               -| "The first form"
               -| "The second form"
               -| "The third form"
          => "The second form"


File: lispref.info,  Node: Conditionals,  Next: Combining Conditions,  Prev: Sequencing,  Up: Control Structures

15.2 Conditionals
=================

Conditional control structures choose among alternatives.  XEmacs Lisp
has two conditional forms: `if', which is much the same as in other
languages, and `cond', which is a generalized case statement.

 -- Special Operator: if condition then-form else-forms...
     `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
     value of CONDITION.  If the evaluated CONDITION is non-`nil',
     THEN-FORM is evaluated and the result returned.  Otherwise, the
     ELSE-FORMS are evaluated in textual order, and the value of the
     last one is returned.  (The ELSE part of `if' is an example of an
     implicit `progn'.  *Note Sequencing::.)

     If CONDITION has the value `nil', and no ELSE-FORMS are given,
     `if' returns `nil'.

     `if' is a special operator because the branch that is not selected
     is never evaluated--it is ignored.  Thus, in the example below,
     `true' is not printed because `print' is never called.

          (if nil
              (print 'true)
            'very-false)
          => very-false

 -- Special Operator: cond clause...
     `cond' chooses among an arbitrary number of alternatives.  Each
     CLAUSE in the `cond' must be a list.  The CAR of this list is the
     CONDITION; the remaining elements, if any, the BODY-FORMS.  Thus,
     a clause looks like this:

          (CONDITION BODY-FORMS...)

     `cond' tries the clauses in textual order, by evaluating the
     CONDITION of each clause.  If the value of CONDITION is non-`nil',
     the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and
     the value of the last of BODY-FORMS becomes the value of the
     `cond'.  The remaining clauses are ignored.

     If the value of CONDITION is `nil', the clause "fails", so the
     `cond' moves on to the following clause, trying its CONDITION.

     If every CONDITION evaluates to `nil', so that every clause fails,
     `cond' returns `nil'.

     A clause may also look like this:

          (CONDITION)

     Then, if CONDITION is non-`nil' when tested, the value of
     CONDITION becomes the value of the `cond' form.

     The following example has four clauses, which test for the cases
     where the value of `x' is a number, string, buffer and symbol,
     respectively:

          (cond ((numberp x) x)
                ((stringp x) x)
                ((bufferp x)
                 (setq temporary-hack x) ; multiple body-forms
                 (buffer-name x))        ; in one clause
                ((symbolp x) (symbol-value x)))

     Often we want to execute the last clause whenever none of the
     previous clauses was successful.  To do this, we use `t' as the
     CONDITION of the last clause, like this: `(t BODY-FORMS)'.  The
     form `t' evaluates to `t', which is never `nil', so this clause
     never fails, provided the `cond' gets to it at all.

     For example,

          (cond ((eq a 'hack) 'foo)
                (t "default"))
          => "default"

     This expression is a `cond' which returns `foo' if the value of
     `a' is 1, and returns the string `"default"' otherwise.

   Any conditional construct can be expressed with `cond' or with `if'.
Therefore, the choice between them is a matter of style.  For example:

     (if A B C)
     ==
     (cond (A B) (t C))


File: lispref.info,  Node: Combining Conditions,  Next: Iteration,  Prev: Conditionals,  Up: Control Structures

15.3 Constructs for Combining Conditions
========================================

This section describes three constructs that are often used together
with `if' and `cond' to express complicated conditions.  The constructs
`and' and `or' can also be used individually as kinds of multiple
conditional constructs.

 -- Function: not condition
     This function tests for the falsehood of CONDITION.  It returns
     `t' if CONDITION is `nil', and `nil' otherwise.  The function
     `not' is identical to `null', and we recommend using the name
     `null' if you are testing for an empty list.

 -- Special Operator: and conditions...
     The `and' special operator tests whether all the CONDITIONS are
     true.  It works by evaluating the CONDITIONS one by one in the
     order written.

     If any of the CONDITIONS evaluates to `nil', then the result of
     the `and' must be `nil' regardless of the remaining CONDITIONS; so
     `and' returns right away, ignoring the remaining CONDITIONS.

     If all the CONDITIONS turn out non-`nil', then the value of the
     last of them becomes the value of the `and' form.

     Here is an example.  The first condition returns the integer 1,
     which is not `nil'.  Similarly, the second condition returns the
     integer 2, which is not `nil'.  The third condition is `nil', so
     the remaining condition is never evaluated.

          (and (print 1) (print 2) nil (print 3))
               -| 1
               -| 2
          => nil

     Here is a more realistic example of using `and':

          (if (and (consp foo) (eq (car foo) 'x))
              (message "foo is a list starting with x"))

     Note that `(car foo)' is not executed if `(consp foo)' returns
     `nil', thus avoiding an error.

     `and' can be expressed in terms of either `if' or `cond'.  For
     example:

          (and ARG1 ARG2 ARG3)
          ==
          (if ARG1 (if ARG2 ARG3))
          ==
          (cond (ARG1 (cond (ARG2 ARG3))))

 -- Special Operator: or conditions...
     The `or' special operator tests whether at least one of the
     CONDITIONS is true.  It works by evaluating all the CONDITIONS one
     by one in the order written.

     If any of the CONDITIONS evaluates to a non-`nil' value, then the
     result of the `or' must be non-`nil'; so `or' returns right away,
     ignoring the remaining CONDITIONS.  The value it returns is the
     non-`nil' value of the condition just evaluated.

     If all the CONDITIONS turn out `nil', then the `or' expression
     returns `nil'.

     For example, this expression tests whether `x' is either 0 or
     `nil':

          (or (eq x nil) (eq x 0))

     Like the `and' construct, `or' can be written in terms of `cond'.
     For example:

          (or ARG1 ARG2 ARG3)
          ==
          (cond (ARG1)
                (ARG2)
                (ARG3))

     You could almost write `or' in terms of `if', but not quite:

          (if ARG1 ARG1
            (if ARG2 ARG2
              ARG3))

     This is not completely equivalent because it can evaluate ARG1 or
     ARG2 twice.  By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
     any argument more than once.


File: lispref.info,  Node: Iteration,  Next: Nonlocal Exits,  Prev: Combining Conditions,  Up: Control Structures

15.4 Iteration
==============

Iteration means executing part of a program repetitively.  For example,
you might want to repeat some computation once for each element of a
list, or once for each integer from 0 to N.  You can do this in XEmacs
Lisp with the special operator `while':

 -- Special Operator: while condition forms...
     `while' first evaluates CONDITION.  If the result is non-`nil', it
     evaluates FORMS in textual order.  Then it reevaluates CONDITION,
     and if the result is non-`nil', it evaluates FORMS again.  This
     process repeats until CONDITION evaluates to `nil'.

     There is no limit on the number of iterations that may occur.  The
     loop will continue until either CONDITION evaluates to `nil' or
     until an error or `throw' jumps out of it (*note Nonlocal Exits::).

     The value of a `while' form is always `nil'.

          (setq num 0)
               => 0
          (while (< num 4)
            (princ (format "Iteration %d." num))
            (setq num (1+ num)))
               -| Iteration 0.
               -| Iteration 1.
               -| Iteration 2.
               -| Iteration 3.
               => nil

     If you would like to execute something on each iteration before the
     end-test, put it together with the end-test in a `progn' as the
     first argument of `while', as shown here:

          (while (progn
                   (forward-line 1)
                   (not (looking-at "^$"))))

     This moves forward one line and continues moving by lines until it
     reaches an empty.  It is unusual in that the `while' has no body,
     just the end test (which also does the real work of moving point).


File: lispref.info,  Node: Nonlocal Exits,  Prev: Iteration,  Up: Control Structures

15.5 Nonlocal Exits
===================

A "nonlocal exit" is a transfer of control from one point in a program
to another remote point.  Nonlocal exits can occur in XEmacs Lisp as a
result of errors; you can also use them under explicit control.
Nonlocal exits unbind all variable bindings made by the constructs being
exited.

* Menu:

* Catch and Throw::     Nonlocal exits for the program's own purposes.
* Examples of Catch::   Showing how such nonlocal exits can be written.
* Errors::              How errors are signaled and handled.
* Cleanups::            Arranging to run a cleanup form if an error happens.


File: lispref.info,  Node: Catch and Throw,  Next: Examples of Catch,  Prev: Nonlocal Exits,  Up: Nonlocal Exits

15.5.1 Explicit Nonlocal Exits: `catch' and `throw'
---------------------------------------------------

Most control constructs affect only the flow of control within the
construct itself.  The function `throw' is the exception to this rule
of normal program execution: it performs a nonlocal exit on request.
(There are other exceptions, but they are for error handling only.)
`throw' is used inside a `catch', and jumps back to that `catch'.  For
example:

     (catch 'foo
       (progn
         ...
         (throw 'foo t)
         ...))

The `throw' transfers control straight back to the corresponding
`catch', which returns immediately.  The code following the `throw' is
not executed.  The second argument of `throw' is used as the return
value of the `catch'.

   The `throw' and the `catch' are matched through the first argument:
`throw' searches for a `catch' whose first argument is `eq' to the one
specified.  Thus, in the above example, the `throw' specifies `foo',
and the `catch' specifies the same symbol, so that `catch' is
applicable.  If there is more than one applicable `catch', the
innermost one takes precedence.

   Executing `throw' exits all Lisp constructs up to the matching
`catch', including function calls.  When binding constructs such as
`let' or function calls are exited in this way, the bindings are
unbound, just as they are when these constructs exit normally (*note
Local Variables::).  Likewise, `throw' restores the buffer and position
saved by `save-excursion' (*note Excursions::), and the narrowing
status saved by `save-restriction' and the window selection saved by
`save-window-excursion' (*note Window Configurations::).  It also runs
any cleanups established with the `unwind-protect' special operator
when it exits that form (*note Cleanups::).

   The `throw' need not appear lexically within the `catch' that it
jumps to.  It can equally well be called from another function called
within the `catch'.  As long as the `throw' takes place chronologically
after entry to the `catch', and chronologically before exit from it, it
has access to that `catch'.  This is why `throw' can be used in
commands such as `exit-recursive-edit' that throw back to the editor
command loop (*note Recursive Editing::).

 -- Special Operator: catch tag body...
     `catch' establishes a return point for the `throw' function.  The
     return point is distinguished from other such return points by TAG,
     which may be any Lisp object.  The argument TAG is evaluated
     normally before the return point is established.

     With the return point in effect, `catch' evaluates the forms of the
     BODY in textual order.  If the forms execute normally, without
     error or nonlocal exit, the value of the last body form is
     returned from the `catch'.

     If a `throw' is done within BODY specifying the same value TAG,
     the `catch' exits immediately; the value it returns is whatever
     was specified as the second argument of `throw'.

 -- Function: throw tag value
     The purpose of `throw' is to return from a return point previously
     established with `catch'.  The argument TAG is used to choose
     among the various existing return points; it must be `eq' to the
     value specified in the `catch'.  If multiple return points match
     TAG, the innermost one is used.

     The argument VALUE is used as the value to return from that
     `catch'.

     If no return point is in effect with tag TAG, then a `no-catch'
     error is signaled with data `(TAG VALUE)'.


File: lispref.info,  Node: Examples of Catch,  Next: Errors,  Prev: Catch and Throw,  Up: Nonlocal Exits

15.5.2 Examples of `catch' and `throw'
--------------------------------------

One way to use `catch' and `throw' is to exit from a doubly nested
loop.  (In most languages, this would be done with a "go to".)  Here we
compute `(foo I J)' for I and J varying from 0 to 9:

     (defun search-foo ()
       (catch 'loop
         (let ((i 0))
           (while (< i 10)
             (let ((j 0))
               (while (< j 10)
                 (if (foo i j)
                     (throw 'loop (list i j)))
                 (setq j (1+ j))))
             (setq i (1+ i))))))

If `foo' ever returns non-`nil', we stop immediately and return a list
of I and J.  If `foo' always returns `nil', the `catch' returns
normally, and the value is `nil', since that is the result of the
`while'.

   Here are two tricky examples, slightly different, showing two return
points at once.  First, two return points with the same tag, `hack':

     (defun catch2 (tag)
       (catch tag
         (throw 'hack 'yes)))
     => catch2

     (catch 'hack
       (print (catch2 'hack))
       'no)
     -| yes
     => no

Since both return points have tags that match the `throw', it goes to
the inner one, the one established in `catch2'.  Therefore, `catch2'
returns normally with value `yes', and this value is printed.  Finally
the second body form in the outer `catch', which is `'no', is evaluated
and returned from the outer `catch'.

   Now let's change the argument given to `catch2':

     (defun catch2 (tag)
       (catch tag
         (throw 'hack 'yes)))
     => catch2

     (catch 'hack
       (print (catch2 'quux))
       'no)
     => yes

We still have two return points, but this time only the outer one has
the tag `hack'; the inner one has the tag `quux' instead.  Therefore,
`throw' makes the outer `catch' return the value `yes'.  The function
`print' is never called, and the body-form `'no' is never evaluated.

   In most cases the formal tag for a catch is a quoted symbol or a
variable whose value is a symbol.  Both styles are demonstrated above.
In definitions of derived control structures, an anonymous tag may be
desired.  A gensym could be used, but since catch tags are compared
using `eq', any Lisp object can be used.  An occasionally encountered
idiom is to bind a local variable to `(cons nil nil)', and use the
variable as the formal tag.


File: lispref.info,  Node: Errors,  Next: Cleanups,  Prev: Examples of Catch,  Up: Nonlocal Exits

15.5.3 Errors
-------------

When XEmacs Lisp attempts to evaluate a form that, for some reason,
cannot be evaluated, it "signals" an "error".

   When an error is signaled, XEmacs's default reaction is to print an
error message and terminate execution of the current command.  This is
the right thing to do in most cases, such as if you type `C-f' at the
end of the buffer.

   In complicated programs, simple termination may not be what you want.
For example, the program may have made temporary changes in data
structures, or created temporary buffers that should be deleted before
the program is finished.  In such cases, you would use `unwind-protect'
to establish "cleanup expressions" to be evaluated in case of error.
(*Note Cleanups::.)  Occasionally, you may wish the program to continue
execution despite an error in a subroutine.  In these cases, you would
use `condition-case' to establish "error handlers" to recover control
in case of error.

   Resist the temptation to use error handling to transfer control from
one part of the program to another; use `catch' and `throw' instead.
*Note Catch and Throw::.

* Menu:

* Signaling Errors::      How to report an error.
* Processing of Errors::  What XEmacs does when you report an error.
* Handling Errors::       How you can trap errors and continue execution.
* Error Symbols::         How errors are classified for trapping them.


File: lispref.info,  Node: Signaling Errors,  Next: Processing of Errors,  Prev: Errors,  Up: Errors

15.5.3.1 How to Signal an Error
...............................

Most errors are signaled "automatically" within Lisp primitives which
you call for other purposes, such as if you try to take the CAR of an
integer or move forward a character at the end of the buffer; you can
also signal errors explicitly with the functions `error', `signal', and
others.

   Quitting, which happens when the user types `C-g', is not considered
an error, but it is handled almost like an error.  *Note Quitting::.

   XEmacs has a rich hierarchy of error symbols predefined via
`deferror'.

     error
       syntax-error
         invalid-read-syntax
         list-formation-error
           malformed-list
             malformed-property-list
           circular-list
             circular-property-list

       invalid-argument
         wrong-type-argument
         args-out-of-range
         wrong-number-of-arguments
         invalid-function
         no-catch

       invalid-state
         void-function
         cyclic-function-indirection
         void-variable
         cyclic-variable-indirection

       invalid-operation
         invalid-change
           setting-constant
         editing-error
           beginning-of-buffer
           end-of-buffer
           buffer-read-only
         io-error
           end-of-file
         arith-error
           range-error
           domain-error
           singularity-error
           overflow-error
           underflow-error

   The five most common errors you will probably use or base your new
errors off of are `syntax-error', `invalid-argument', `invalid-state',
`invalid-operation', and `invalid-change'.  Note the semantic
differences:

   * `syntax-error' is for errors in complex structures: parsed strings,
     lists, and the like.

   * `invalid-argument' is for errors in a simple value.  Typically, the
     entire value, not just one part of it, is wrong.

   * `invalid-state' means that some settings have been changed in such
     a way that their current state is unallowable.  More and more,
     code is being written more carefully, and catches the error when
     the settings are being changed, rather than afterwards.  This
     leads us to the next error:

   * `invalid-change' means that an attempt is being made to change some
     settings into an invalid state.  `invalid-change' is a type of
     `invalid-operation'.

   * `invalid-operation' refers to all cases where code is trying to do
     something that's disallowed.  This includes file errors, buffer
     errors (e.g. running off the end of a buffer), `invalid-change' as
     just mentioned, and arithmetic errors.

 -- Function: error datum &rest args
     This function signals a non-continuable error.

     DATUM should normally be an error symbol, i.e. a symbol defined
     using `define-error'.  ARGS will be made into a list, and DATUM
     and ARGS passed as the two arguments to `signal', the most basic
     error handling function.

     This error is not continuable: you cannot continue execution after
     the error using the debugger `r' command.  See also `cerror'.

     The correct semantics of ARGS varies from error to error, but for
     most errors that need to be generated in Lisp code, the first
     argument should be a string describing the *context* of the error
     (i.e. the exact operation being performed and what went wrong),
     and the remaining arguments or \"frobs\" (most often, there is
     one) specify the offending object(s) and/or provide additional
     details such as the exact error when a file error occurred, e.g.:

        * the buffer in which an editing error occurred.

        * an invalid value that was encountered. (In such cases, the
          string should describe the purpose or \"semantics\" of the
          value [e.g. if the value is an argument to a function, the
          name of the argument; if the value is the value corresponding
          to a keyword, the name of the keyword; if the value is
          supposed to be a list length, say this and say what the
          purpose of the list is; etc.] as well as specifying why the
          value is invalid, if that's not self-evident.)

        * the file in which an error occurred. (In such cases, there
          should be a second frob, probably a string, specifying the
          exact error that occurred.  This does not occur in the string
          that precedes the first frob, because that frob describes the
          exact operation that was happening.

     For historical compatibility, DATUM can also be a string.  In this
     case, DATUM and ARGS are passed together as the arguments to
     `format', and then an error is signalled using the error symbol
     `error' and formatted string.  Although this usage of `error' is
     very common, it is deprecated because it totally defeats the
     purpose of having structured errors.  There is now a rich set of
     defined errors to use.

     See also `cerror', `signal', and `signal-error'."

     These examples show typical uses of `error':

          (error 'syntax-error
                 "Dialog descriptor must supply at least one button"
          	descriptor)

          (error "You have committed an error.
                  Try something else.")
               error--> You have committed an error.
                  Try something else.

          (error "You have committed %d errors." 10)
               error--> You have committed 10 errors.

     If you want to use your own string as an error message verbatim,
     don't just write `(error STRING)'.  If STRING contains `%', it
     will be interpreted as a format specifier, with undesirable
     results.  Instead, use `(error "%s" STRING)'.

 -- Function: cerror datum &rest args
     This function behaves like `error', except that the error it
     signals is continuable.  That means that debugger commands `c' and
     `r' can resume execution.

 -- Function: signal error-symbol data
     This function signals a continuable error named by ERROR-SYMBOL.
     The argument DATA is a list of additional Lisp objects relevant to
     the circumstances of the error.

     The argument ERROR-SYMBOL must be an "error symbol"--a symbol
     bearing a property `error-conditions' whose value is a list of
     condition names.  This is how XEmacs Lisp classifies different
     sorts of errors.

     The number and significance of the objects in DATA depends on
     ERROR-SYMBOL.  For example, with a `wrong-type-argument' error,
     there are two objects in the list: a predicate that describes the
     type that was expected, and the object that failed to fit that
     type.  *Note Error Symbols::, for a description of error symbols.

     Both ERROR-SYMBOL and DATA are available to any error handlers
     that handle the error: `condition-case' binds a local variable to
     a list of the form `(ERROR-SYMBOL .  DATA)' (*note Handling
     Errors::).  If the error is not handled, these two values are used
     in printing the error message.

     The function `signal' can return, if the debugger is invoked and
     the user invokes the "return from signal" option.  If you want the
     error not to be continuable, use `signal-error' instead.  Note that
     in FSF Emacs `signal' never returns.

          (signal 'wrong-number-of-arguments '(x y))
               error--> Wrong number of arguments: x, y

          (signal 'no-such-error '("My unknown error condition"))
               error--> Peculiar error (no-such-error "My unknown error condition")

 -- Function: signal-error error-symbol data
     This function behaves like `signal', except that the error it
     signals is not continuable.

 -- Macro: check-argument-type predicate argument
     This macro checks that ARGUMENT satisfies PREDICATE.  If that is
     not the case, it signals a continuable `wrong-type-argument' error
     until the returned value satisfies PREDICATE, and assigns the
     returned value to ARGUMENT.  In other words, execution of the
     program will not continue until PREDICATE is met.

     ARGUMENT is not evaluated, and should be a symbol.  PREDICATE is
     evaluated, and should name a function.

     As shown in the following example, `check-argument-type' is useful
     in low-level code that attempts to ensure the sanity of its data
     before proceeding.

          (defun cache-object-internal (object wlist)
            ;; Before doing anything, make sure that WLIST is indeed
            ;; a weak list, which is what we expect.
            (check-argument-type 'weak-list-p wlist)
            ...)


File: lispref.info,  Node: Processing of Errors,  Next: Handling Errors,  Prev: Signaling Errors,  Up: Errors

15.5.3.2 How XEmacs Processes Errors
....................................

When an error is signaled, `signal' searches for an active "handler"
for the error.  A handler is a sequence of Lisp expressions designated
to be executed if an error happens in part of the Lisp program.  If the
error has an applicable handler, the handler is executed, and control
resumes following the handler.  The handler executes in the environment
of the `condition-case' that established it; all functions called
within that `condition-case' have already been exited, and the handler
cannot return to them.

   If there is no applicable handler for the error, the current command
is terminated and control returns to the editor command loop, because
the command loop has an implicit handler for all kinds of errors.  The
command loop's handler uses the error symbol and associated data to
print an error message.

   Errors in command loop are processed using the `command-error'
function, which takes care of some necessary cleanup, and prints a
formatted error message to the echo area.  The functions that do the
formatting are explained below.

 -- Function: display-error error-object stream
     This function displays ERROR-OBJECT on STREAM.  ERROR-OBJECT is a
     cons of error type, a symbol, and error arguments, a list.  If the
     error type symbol of one of its error condition superclasses has a
     `display-error' property, that function is invoked for printing
     the actual error message.  Otherwise, the error is printed as
     `Error: arg1, arg2, ...'.

 -- Function: error-message-string error-object
     This function converts ERROR-OBJECT to an error message string,
     and returns it.  The message is equivalent to the one that would be
     printed by `display-error', except that it is conveniently returned
     in string form.

   An error that has no explicit handler may call the Lisp debugger.
The debugger is enabled if the variable `debug-on-error' (*note Error
Debugging::) is non-`nil'.  Unlike error handlers, the debugger runs in
the environment of the error, so that you can examine values of
variables precisely as they were at the time of the error.


File: lispref.info,  Node: Handling Errors,  Next: Error Symbols,  Prev: Processing of Errors,  Up: Errors

15.5.3.3 Writing Code to Handle Errors
......................................

The usual effect of signaling an error is to terminate the command that
is running and return immediately to the XEmacs editor command loop.
You can arrange to trap errors occurring in a part of your program by
establishing an error handler, with the special operator
`condition-case'.  A simple example looks like this:

     (condition-case nil
         (delete-file filename)
       (error nil))

This deletes the file named FILENAME, catching any error and returning
`nil' if an error occurs.

   The second argument of `condition-case' is called the "protected
form".  (In the example above, the protected form is a call to
`delete-file'.)  The error handlers go into effect when this form
begins execution and are deactivated when this form returns.  They
remain in effect for all the intervening time.  In particular, they are
in effect during the execution of functions called by this form, in
their subroutines, and so on.  This is a good thing, since, strictly
speaking, errors can be signaled only by Lisp primitives (including
`signal' and `error') called by the protected form, not by the
protected form itself.

   The arguments after the protected form are handlers.  Each handler
lists one or more "condition names" (which are symbols) to specify
which errors it will handle.  The error symbol specified when an error
is signaled also defines a list of condition names.  A handler applies
to an error if they have any condition names in common.  In the example
above, there is one handler, and it specifies one condition name,
`error', which covers all errors.

   The search for an applicable handler checks all the established
handlers starting with the most recently established one.  Thus, if two
nested `condition-case' forms offer to handle the same error, the inner
of the two will actually handle it.

   When an error is handled, control returns to the handler.  Before
this happens, XEmacs unbinds all variable bindings made by binding
constructs that are being exited and executes the cleanups of all
`unwind-protect' forms that are exited.  Once control arrives at the
handler, the body of the handler is executed.

   After execution of the handler body, execution continues by returning
from the `condition-case' form.  Because the protected form is exited
completely before execution of the handler, the handler cannot resume
execution at the point of the error, nor can it examine variable
bindings that were made within the protected form.  All it can do is
clean up and proceed.

   `condition-case' is often used to trap errors that are predictable,
such as failure to open a file in a call to `insert-file-contents'.  It
is also used to trap errors that are totally unpredictable, such as
when the program evaluates an expression read from the user.

   Even when an error is handled, the debugger may still be called if
the variable `debug-on-signal' (*note Error Debugging::) is non-`nil'.
Note that this may yield unpredictable results with code that traps
expected errors as normal part of its operation.  Do not set
`debug-on-signal' unless you know what you are doing.

   Error signaling and handling have some resemblance to `throw' and
`catch', but they are entirely separate facilities.  An error cannot be
caught by a `catch', and a `throw' cannot be handled by an error
handler (though using `throw' when there is no suitable `catch' signals
an error that can be handled).

 -- Special Operator: condition-case var protected-form handlers...
     This special operator establishes the error handlers HANDLERS
     around the execution of PROTECTED-FORM.  If PROTECTED-FORM executes
     without error, the value it returns becomes the value of the
     `condition-case' form; in this case, the `condition-case' has no
     effect.  The `condition-case' form makes a difference when an
     error occurs during PROTECTED-FORM.

     Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
     Here CONDITIONS is an error condition name to be handled, or a
     list of condition names; BODY is one or more Lisp expressions to
     be executed when this handler handles an error.  Here are examples
     of handlers:

          (error nil)

          (arith-error (message "Division by zero"))

          ((arith-error file-error)
           (message
            "Either division by zero or failure to open a file"))

     Each error that occurs has an "error symbol" that describes what
     kind of error it is.  The `error-conditions' property of this
     symbol is a list of condition names (*note Error Symbols::).  Emacs
     searches all the active `condition-case' forms for a handler that
     specifies one or more of these condition names; the innermost
     matching `condition-case' handles the error.  Within this
     `condition-case', the first applicable handler handles the error.

     After executing the body of the handler, the `condition-case'
     returns normally, using the value of the last form in the handler
     body as the overall value.

     The argument VAR is a variable.  `condition-case' does not bind
     this variable when executing the PROTECTED-FORM, only when it
     handles an error.  At that time, it binds VAR locally to a list of
     the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
     error.  The handler can refer to this list to decide what to do.
     For example, if the error is for failure opening a file, the file
     name is the second element of DATA--the third element of VAR.

     If VAR is `nil', that means no variable is bound.  Then the error
     symbol and associated data are not available to the handler.

   Here is an example of using `condition-case' to handle the error
that results from dividing by zero.  The handler prints out a warning
message and returns a very large number.

     (defun safe-divide (dividend divisor)
       (condition-case err
           ;; Protected form.
           (/ dividend divisor)
         ;; The handler.
         (arith-error                        ; Condition.
          (princ (format "Arithmetic error: %s" err))
          1000000)))
     => safe-divide

     (safe-divide 5 0)
          -| Arithmetic error: (arith-error)
     => 1000000

The handler specifies condition name `arith-error' so that it will
handle only division-by-zero errors.  Other kinds of errors will not be
handled, at least not by this `condition-case'.  Thus,

     (safe-divide nil 3)
          error--> Wrong type argument: integer-or-marker-p, nil

   Here is a `condition-case' that catches all kinds of errors,
including those signaled with `error':

     (setq baz 34)
          => 34

     (condition-case err
         (if (eq baz 35)
             t
           ;; This is a call to the function `error'.
           (error "Rats!  The variable %s was %s, not 35" 'baz baz))
       ;; This is the handler; it is not a form.
       (error (princ (format "The error was: %s" err))
              2))
     -| The error was: (error "Rats!  The variable baz was 34, not 35")
     => 2


File: lispref.info,  Node: Error Symbols,  Prev: Handling Errors,  Up: Errors

15.5.3.4 Error Symbols and Condition Names
..........................................

When you signal an error, you specify an "error symbol" to specify the
kind of error you have in mind.  Each error has one and only one error
symbol to categorize it.  This is the finest classification of errors
defined by the XEmacs Lisp language.

   These narrow classifications are grouped into a hierarchy of wider
classes called "error conditions", identified by "condition names".
The narrowest such classes belong to the error symbols themselves: each
error symbol is also a condition name.  There are also condition names
for more extensive classes, up to the condition name `error' which
takes in all kinds of errors.  Thus, each error has one or more
condition names: `error', the error symbol if that is distinct from
`error', and perhaps some intermediate classifications.

   In other words, each error condition "inherits" from another error
condition, with `error' sitting at the top of the inheritance hierarchy.

 -- Function: define-error error-symbol error-message &optional
          inherits-from
     This function defines a new error, denoted by ERROR-SYMBOL.
     ERROR-MESSAGE is an informative message explaining the error, and
     will be printed out when an unhandled error occurs.  ERROR-SYMBOL
     is a sub-error of INHERITS-FROM (which defaults to `error').

     `define-error' internally works by putting on ERROR-SYMBOL an
     `error-message' property whose value is ERROR-MESSAGE, and an
     `error-conditions' property that is a list of ERROR-SYMBOL
     followed by each of its super-errors, up to and including `error'.
     You will sometimes see code that sets this up directly rather than
     calling `define-error', but you should _not_ do this yourself,
     unless you wish to maintain compatibility with FSF Emacs, which
     does not provide `define-error'.

   Here is how we define a new error symbol, `new-error', that belongs
to a range of errors called `my-own-errors':

     (define-error 'my-own-errors "A whole range of errors" 'error)
     (define-error 'new-error "A new error" 'my-own-errors)

`new-error' has three condition names: `new-error', the narrowest
classification; `my-own-errors', which we imagine is a wider
classification; and `error', which is the widest of all.

   Note that it is not legal to try to define an error unless its
super-error is also defined.  For instance, attempting to define
`new-error' before `my-own-errors' are defined will signal an error.

   The error string should start with a capital letter but it should
not end with a period.  This is for consistency with the rest of Emacs.

   Naturally, XEmacs will never signal `new-error' on its own; only an
explicit call to `signal' (*note Signaling Errors::) in your code can
do this:

     (signal 'new-error '(x y))
          error--> A new error: x, y

   This error can be handled through any of the three condition names.
This example handles `new-error' and any other errors in the class
`my-own-errors':

     (condition-case foo
         (bar nil t)
       (my-own-errors nil))

   The significant way that errors are classified is by their condition
names--the names used to match errors with handlers.  An error symbol
serves only as a convenient way to specify the intended error message
and list of condition names.  It would be cumbersome to give `signal' a
list of condition names rather than one error symbol.

   By contrast, using only error symbols without condition names would
seriously decrease the power of `condition-case'.  Condition names make
it possible to categorize errors at various levels of generality when
you write an error handler.  Using error symbols alone would eliminate
all but the narrowest level of classification.

   *Note Standard Errors::, for a list of all the standard error symbols
and their conditions.


File: lispref.info,  Node: Cleanups,  Prev: Errors,  Up: Nonlocal Exits

15.5.4 Cleaning Up from Nonlocal Exits
--------------------------------------

The `unwind-protect' construct is essential whenever you temporarily
put a data structure in an inconsistent state; it permits you to ensure
the data are consistent in the event of an error or throw.

 -- Special Operator: unwind-protect body cleanup-forms...
     `unwind-protect' executes the BODY with a guarantee that the
     CLEANUP-FORMS will be evaluated if control leaves BODY, no matter
     how that happens.  The BODY may complete normally, or execute a
     `throw' out of the `unwind-protect', or cause an error; in all
     cases, the CLEANUP-FORMS will be evaluated.

     If the BODY forms finish normally, `unwind-protect' returns the
     value of the last BODY form, after it evaluates the CLEANUP-FORMS.
     If the BODY forms do not finish, `unwind-protect' does not return
     any value in the normal sense.

     Only the BODY is actually protected by the `unwind-protect'.  If
     any of the CLEANUP-FORMS themselves exits nonlocally (e.g., via a
     `throw' or an error), `unwind-protect' is _not_ guaranteed to
     evaluate the rest of them.  If the failure of one of the
     CLEANUP-FORMS has the potential to cause trouble, then protect it
     with another `unwind-protect' around that form.

     The number of currently active `unwind-protect' forms counts,
     together with the number of local variable bindings, against the
     limit `max-specpdl-size' (*note Local Variables::).

   For example, here we make an invisible buffer for temporary use, and
make sure to kill it before finishing:

     (save-excursion
       (let ((buffer (get-buffer-create " *temp*")))
         (set-buffer buffer)
         (unwind-protect
             BODY
           (kill-buffer buffer))))

You might think that we could just as well write `(kill-buffer
(current-buffer))' and dispense with the variable `buffer'.  However,
the way shown above is safer, if BODY happens to get an error after
switching to a different buffer!  (Alternatively, you could write
another `save-excursion' around the body, to ensure that the temporary
buffer becomes current in time to kill it.)

   Here is an actual example taken from the file `ftp.el'.  It creates
a process (*note Processes::) to try to establish a connection to a
remote machine.  As the function `ftp-login' is highly susceptible to
numerous problems that the writer of the function cannot anticipate, it
is protected with a form that guarantees deletion of the process in the
event of failure.  Otherwise, XEmacs might fill up with useless
subprocesses.

     (let ((win nil))
       (unwind-protect
           (progn
             (setq process (ftp-setup-buffer host file))
             (if (setq win (ftp-login process host user password))
                 (message "Logged in")
               (error "Ftp login failed")))
         (or win (and process (delete-process process)))))

   This example actually has a small bug: if the user types `C-g' to
quit, and the quit happens immediately after the function
`ftp-setup-buffer' returns but before the variable `process' is set,
the process will not be killed.  There is no easy way to fix this bug,
but at least it is very unlikely.

   Here is another example which uses `unwind-protect' to make sure to
kill a temporary buffer.  In this example, the value returned by
`unwind-protect' is used.

     (defun shell-command-string (cmd)
       "Return the output of the shell command CMD, as a string."
       (save-excursion
         (set-buffer (generate-new-buffer " OS*cmd"))
         (shell-command cmd t)
         (unwind-protect
             (buffer-string)
           (kill-buffer (current-buffer)))))


File: lispref.info,  Node: Variables,  Next: Functions and Commands,  Prev: Control Structures,  Up: Top

16 Variables
************

A "variable" is a name used in a program to stand for a value.  Nearly
all programming languages have variables of some sort.  In the text of
a Lisp program, variables are written using the syntax for symbols.

   In Lisp, unlike most programming languages, programs are represented
primarily as Lisp objects and only secondarily as text.  The Lisp
objects used for variables are symbols: the symbol name is the variable
name, and the variable's value is stored in the value cell of the
symbol.  The use of a symbol as a variable is independent of its use as
a function name.  *Note Symbol Components::.

   The Lisp objects that constitute a Lisp program determine the textual
form of the program--it is simply the read syntax for those Lisp
objects.  This is why, for example, a variable in a textual Lisp program
is written using the read syntax for the symbol that represents the
variable.

* Menu:

* Global Variables::      Variable values that exist permanently, everywhere.
* Constant Variables::    Certain "variables" have values that never change.
* Local Variables::       Variable values that exist only temporarily.
* Void Variables::        Symbols that lack values.
* Defining Variables::    A definition says a symbol is used as a variable.
* Accessing Variables::   Examining values of variables whose names
                            are known only at run time.
* Setting Variables::     Storing new values in variables.
* Variable Scoping::      How Lisp chooses among local and global values.
* Buffer-Local Variables::  Variable values in effect only in one buffer.
* Variable Aliases::	  Making one variable point to another.


File: lispref.info,  Node: Global Variables,  Next: Constant Variables,  Prev: Variables,  Up: Variables

16.1 Global Variables
=====================

The simplest way to use a variable is "globally".  This means that the
variable has just one value at a time, and this value is in effect (at
least for the moment) throughout the Lisp system.  The value remains in
effect until you specify a new one.  When a new value replaces the old
one, no trace of the old value remains in the variable.

   You specify a value for a symbol with `setq'.  For example,

     (setq x '(a b))

gives the variable `x' the value `(a b)'.  Note that `setq' does not
evaluate its first argument, the name of the variable, but it does
evaluate the second argument, the new value.

   Once the variable has a value, you can refer to it by using the
symbol by itself as an expression.  Thus,

     x => (a b)

assuming the `setq' form shown above has already been executed.

   If you do another `setq', the new value replaces the old one:

     x
          => (a b)
     (setq x 4)
          => 4
     x
          => 4


File: lispref.info,  Node: Constant Variables,  Next: Local Variables,  Prev: Global Variables,  Up: Variables

16.2 Variables That Never Change
================================

In XEmacs Lisp, some symbols always evaluate to themselves: the two
special symbols `nil' and `t', as well as "keyword symbols", that is,
symbols whose name begins with the character ``:''.  These symbols
cannot be rebound, nor can their value cells be changed.  An attempt to
change the value of `nil' or `t' signals a `setting-constant' error.

     nil == 'nil
          => nil
     (setq nil 500)
     error--> Attempt to set constant symbol: nil


File: lispref.info,  Node: Local Variables,  Next: Void Variables,  Prev: Constant Variables,  Up: Variables

16.3 Local Variables
====================

Global variables have values that last until explicitly superseded with
new values.  Sometimes it is useful to create variable values that
exist temporarily--only while within a certain part of the program.
These values are called "local", and the variables so used are called
"local variables".

   For example, when a function is called, its argument variables
receive new local values that last until the function exits.  The `let'
special operator explicitly establishes new local values for specified
variables; these last until exit from the `let' form.

   Establishing a local value saves away the previous value (or lack of
one) of the variable.  When the life span of the local value is over,
the previous value is restored.  In the mean time, we say that the
previous value is "shadowed" and "not visible".  Both global and local
values may be shadowed (*note Scope::).

   If you set a variable (such as with `setq') while it is local, this
replaces the local value; it does not alter the global value, or
previous local values that are shadowed.  To model this behavior, we
speak of a "local binding" of the variable as well as a local value.

   The local binding is a conceptual place that holds a local value.
Entry to a function, or a special operator such as `let', creates the
local binding; exit from the function or from the `let' removes the
local binding.  As long as the local binding lasts, the variable's value
is stored within it.  Use of `setq' or `set' while there is a local
binding stores a different value into the local binding; it does not
create a new binding.

   We also speak of the "global binding", which is where (conceptually)
the global value is kept.

   A variable can have more than one local binding at a time (for
example, if there are nested `let' forms that bind it).  In such a
case, the most recently created local binding that still exists is the
"current binding" of the variable.  (This is called "dynamic scoping";
see *Note Variable Scoping::.)  If there are no local bindings, the
variable's global binding is its current binding.  We also call the
current binding the "most-local existing binding", for emphasis.
Ordinary evaluation of a symbol always returns the value of its current
binding.

   The special operators `let' and `let*' exist to create local
bindings.

 -- Special Operator: let (bindings...) forms...
     This special operator binds variables according to BINDINGS and
     then evaluates all of the FORMS in textual order.  The `let'-form
     returns the value of the last form in FORMS.

     Each of the BINDINGS is either (i) a symbol, in which case that
     symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL
     VALUE-FORM)', in which case SYMBOL is bound to the result of
     evaluating VALUE-FORM.  If VALUE-FORM is omitted, `nil' is used.

     All of the VALUE-FORMs in BINDINGS are evaluated in the order they
     appear and _before_ any of the symbols are bound.  Here is an
     example of this: `Z' is bound to the old value of `Y', which is 2,
     not the new value, 1.

          (setq Y 2)
               => 2
          (let ((Y 1)
                (Z Y))
            (list Y Z))
               => (1 2)

 -- Special Operator: let* (bindings...) forms...
     This special operator is like `let', but it binds each variable
     right after computing its local value, before computing the local
     value for the next variable.  Therefore, an expression in BINDINGS
     can reasonably refer to the preceding symbols bound in this `let*'
     form.  Compare the following example with the example above for
     `let'.

          (setq Y 2)
               => 2
          (let* ((Y 1)
                 (Z Y))    ; Use the just-established value of `Y'.
            (list Y Z))
               => (1 1)

   Here is a complete list of the other facilities that create local
bindings:

   * Function calls (*note Functions and Commands::).

   * Macro calls (*note Macros::).

   * `condition-case' (*note Errors::).

   Variables can also have buffer-local bindings (*note Buffer-Local
Variables::).  These kinds of bindings work somewhat like ordinary local
bindings, but they are localized depending on "where" you are in Emacs,
rather than localized in time.

 -- Variable: max-specpdl-size
     This variable defines the limit on the total number of local
     variable bindings and `unwind-protect' cleanups (*note Nonlocal
     Exits::) that are allowed before signaling an error (with data
     `"Variable binding depth exceeds max-specpdl-size"').

     This limit, with the associated error when it is exceeded, is one
     way that Lisp avoids infinite recursion on an ill-defined function.

     The default value is 3000.

     `max-lisp-eval-depth' provides another limit on depth of nesting.
     *Note Eval::.


File: lispref.info,  Node: Void Variables,  Next: Defining Variables,  Prev: Local Variables,  Up: Variables

16.4 When a Variable is "Void"
==============================

If you have never given a symbol any value as a global variable, we say
that that symbol's global value is "void".  In other words, the
symbol's value cell does not have any Lisp object in it.  If you try to
evaluate the symbol, you get a `void-variable' error rather than a
value.

   Note that a value of `nil' is not the same as void.  The symbol
`nil' is a Lisp object and can be the value of a variable just as any
other object can be; but it is _a value_.  A void variable does not
have any value.

   After you have given a variable a value, you can make it void once
more using `makunbound'.

 -- Function: makunbound symbol
     This function makes the current binding of SYMBOL void.
     Subsequent attempts to use this symbol's value as a variable will
     signal the error `void-variable', unless or until you set it again.

     `makunbound' returns SYMBOL.

          (makunbound 'x)      ; Make the global value
                               ;   of `x' void.
               => x
          x
          error--> Symbol's value as variable is void: x

     If SYMBOL is locally bound, `makunbound' affects the most local
     existing binding.  This is the only way a symbol can have a void
     local binding, since all the constructs that create local bindings
     create them with values.  In this case, the voidness lasts at most
     as long as the binding does; when the binding is removed due to
     exit from the construct that made it, the previous or global
     binding is reexposed as usual, and the variable is no longer void
     unless the newly reexposed binding was void all along.

          (setq x 1)               ; Put a value in the global binding.
               => 1
          (let ((x 2))             ; Locally bind it.
            (makunbound 'x)        ; Void the local binding.
            x)
          error--> Symbol's value as variable is void: x
          x                        ; The global binding is unchanged.
               => 1

          (let ((x 2))             ; Locally bind it.
            (let ((x 3))           ; And again.
              (makunbound 'x)      ; Void the innermost-local binding.
              x))                  ; And refer: it's void.
          error--> Symbol's value as variable is void: x

          (let ((x 2))
            (let ((x 3))
              (makunbound 'x))     ; Void inner binding, then remove it.
            x)                     ; Now outer `let' binding is visible.
               => 2

   A variable that has been made void with `makunbound' is
indistinguishable from one that has never received a value and has
always been void.

   You can use the function `boundp' to test whether a variable is
currently void.

 -- Function: boundp variable
     `boundp' returns `t' if VARIABLE (a symbol) is not void; more
     precisely, if its current binding is not void.  It returns `nil'
     otherwise.

          (boundp 'abracadabra)          ; Starts out void.
               => nil
          (let ((abracadabra 5))         ; Locally bind it.
            (boundp 'abracadabra))
               => t
          (boundp 'abracadabra)          ; Still globally void.
               => nil
          (setq abracadabra 5)           ; Make it globally nonvoid.
               => 5
          (boundp 'abracadabra)
               => t


File: lispref.info,  Node: Defining Variables,  Next: Accessing Variables,  Prev: Void Variables,  Up: Variables

16.5 Defining Global Variables
==============================

You may announce your intention to use a symbol as a global variable
with a "variable definition": a special operator, either `defconst' or
`defvar'.

   In XEmacs Lisp, definitions serve three purposes.  First, they inform
people who read the code that certain symbols are _intended_ to be used
a certain way (as variables).  Second, they inform the Lisp system of
these things, supplying a value and documentation.  Third, they provide
information to utilities such as `etags' and `make-docfile', which
create data bases of the functions and variables in a program.

   The difference between `defconst' and `defvar' is primarily a matter
of intent, serving to inform human readers of whether programs will
change the variable.  XEmacs Lisp does not restrict the ways in which a
variable can be used based on `defconst' or `defvar' declarations.
However, it does make a difference for initialization: `defconst'
unconditionally initializes the variable, while `defvar' initializes it
only if it is void.

   One would expect user option variables to be defined with
`defconst', since programs do not change them.  Unfortunately, this has
bad results if the definition is in a library that is not preloaded:
`defconst' would override any prior value when the library is loaded.
Users would like to be able to set user options in their init files,
and override the default values given in the definitions.  For this
reason, user options must be defined with `defvar'.

 -- Special Operator: defvar symbol [value [doc-string]]
     This special operator defines SYMBOL as a value and initializes it.
     The definition informs a person reading your code that SYMBOL is
     used as a variable that programs are likely to set or change.  It
     is also used for all user option variables except in the preloaded
     parts of XEmacs.  Note that SYMBOL is not evaluated; the symbol to
     be defined must appear explicitly in the `defvar'.

     If SYMBOL already has a value (i.e., it is not void), VALUE is not
     even evaluated, and SYMBOL's value remains unchanged.  If SYMBOL
     is void and VALUE is specified, `defvar' evaluates it and sets
     SYMBOL to the result.  (If VALUE is omitted, the value of SYMBOL
     is not changed in any case.)

     When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
     Lisp mode (`eval-defun'), a special feature of `eval-defun'
     evaluates it as a `defconst'.  The purpose of this is to make sure
     the variable's value is reinitialized, when you ask for it
     specifically.

     If SYMBOL has a buffer-local binding in the current buffer,
     `defvar' sets the default value, not the local value.  *Note
     Buffer-Local Variables::.

     If the DOC-STRING argument appears, it specifies the documentation
     for the variable.  (This opportunity to specify documentation is
     one of the main benefits of defining the variable.)  The
     documentation is stored in the symbol's `variable-documentation'
     property.  The XEmacs help functions (*note Documentation::) look
     for this property.

     If the first character of DOC-STRING is `*', it means that this
     variable is considered a user option.  This lets users set the
     variable conveniently using the commands `set-variable' and
     `edit-options'.

     For example, this form defines `foo' but does not set its value:

          (defvar foo)
               => foo

     The following example sets the value of `bar' to `23', and gives
     it a documentation string:

          (defvar bar 23
            "The normal weight of a bar.")
               => bar

     The following form changes the documentation string for `bar',
     making it a user option, but does not change the value, since `bar'
     already has a value.  (The addition `(1+ 23)' is not even
     performed.)

          (defvar bar (1+ 23)
            "*The normal weight of a bar.")
               => bar
          bar
               => 23

     Here is an equivalent expression for the `defvar' special operator:

          (defvar SYMBOL VALUE DOC-STRING)
          ==
          (progn
            (if (not (boundp 'SYMBOL))
                (setq SYMBOL VALUE))
            (put 'SYMBOL 'variable-documentation 'DOC-STRING)
            'SYMBOL)

     The `defvar' form returns SYMBOL, but it is normally used at top
     level in a file where its value does not matter.

 -- Special Operator: defconst symbol [value [doc-string]]
     This special operator defines SYMBOL as a value and initializes it.
     It informs a person reading your code that SYMBOL has a global
     value, established here, that will not normally be changed or
     locally bound by the execution of the program.  The user, however,
     may be welcome to change it.  Note that SYMBOL is not evaluated;
     the symbol to be defined must appear explicitly in the `defconst'.

     `defconst' always evaluates VALUE and sets the global value of
     SYMBOL to the result, provided VALUE is given.  If SYMBOL has a
     buffer-local binding in the current buffer, `defconst' sets the
     default value, not the local value.

     *Please note:* Don't use `defconst' for user option variables in
     libraries that are not standardly preloaded.  The user should be
     able to specify a value for such a variable in the `.emacs' file,
     so that it will be in effect if and when the library is loaded
     later.

     Here, `pi' is a constant that presumably ought not to be changed
     by anyone (attempts by the Indiana State Legislature
     notwithstanding).  As the second form illustrates, however, this
     is only advisory.

          (defconst pi 3.1415 "Pi to five places.")
               => pi
          (setq pi 3)
               => pi
          pi
               => 3

 -- Function: user-variable-p variable
     This function returns `t' if VARIABLE is a user option--a variable
     intended to be set by the user for customization--and `nil'
     otherwise.  (Variables other than user options exist for the
     internal purposes of Lisp programs, and users need not know about
     them.)

     User option variables are distinguished from other variables by the
     first character of the `variable-documentation' property.  If the
     property exists and is a string, and its first character is `*',
     then the variable is a user option.

   If a user option variable has a `variable-interactive' property, the
`set-variable' command uses that value to control reading the new value
for the variable.  The property's value is used as if it were the
argument to `interactive'.

   *Warning:* If the `defconst' and `defvar' special forms are used
while the variable has a local binding, they set the local binding's
value; the global binding is not changed.  This is not what we really
want.  To prevent it, use these special operators at top level in a
file, where normally no local binding is in effect, and make sure to
load the file before making a local binding for the variable.


File: lispref.info,  Node: Accessing Variables,  Next: Setting Variables,  Prev: Defining Variables,  Up: Variables

16.6 Accessing Variable Values
==============================

The usual way to reference a variable is to write the symbol which
names it (*note Symbol Forms::).  This requires you to specify the
variable name when you write the program.  Usually that is exactly what
you want to do.  Occasionally you need to choose at run time which
variable to reference; then you can use `symbol-value'.

 -- Function: symbol-value symbol
     This function returns the value of SYMBOL.  This is the value in
     the innermost local binding of the symbol, or its global value if
     it has no local bindings.

          (setq abracadabra 5)
               => 5
          (setq foo 9)
               => 9

          ;; Here the symbol `abracadabra'
          ;;   is the symbol whose value is examined.
          (let ((abracadabra 'foo))
            (symbol-value 'abracadabra))
               => foo

          ;; Here the value of `abracadabra',
          ;;   which is `foo',
          ;;   is the symbol whose value is examined.
          (let ((abracadabra 'foo))
            (symbol-value abracadabra))
               => 9

          (symbol-value 'abracadabra)
               => 5

     A `void-variable' error is signaled if SYMBOL has neither a local
     binding nor a global value.


File: lispref.info,  Node: Setting Variables,  Next: Variable Scoping,  Prev: Accessing Variables,  Up: Variables

16.7 How to Alter a Variable Value
==================================

The usual way to change the value of a variable is with the special
form `setq'.  When you need to compute the choice of variable at run
time, use the function `set'.

 -- Special Operator: setq [symbol form]...
     This special operator is the most common method of changing a
     variable's value.  Each SYMBOL is given a new value, which is the
     result of evaluating the corresponding FORM.  The most-local
     existing binding of the symbol is changed.

     `setq' does not evaluate SYMBOL; it sets the symbol that you
     write.  We say that this argument is "automatically quoted".  The
     `q' in `setq' stands for "quoted."

     The value of the `setq' form is the value of the last FORM.

          (setq x (1+ 2))
               => 3
          x                   ; `x' now has a global value.
               => 3
          (let ((x 5))
            (setq x 6)        ; The local binding of `x' is set.
            x)
               => 6
          x                   ; The global value is unchanged.
               => 3

     Note that the first FORM is evaluated, then the first SYMBOL is
     set, then the second FORM is evaluated, then the second SYMBOL is
     set, and so on:

          (setq x 10          ; Notice that `x' is set before
                y (1+ x))     ;   the value of `y' is computed.
               => 11

 -- Function: set symbol value
     This function sets SYMBOL's value to VALUE, then returns VALUE.
     Since `set' is a function, the expression written for SYMBOL is
     evaluated to obtain the symbol to set.

     The most-local existing binding of the variable is the binding
     that is set; shadowed bindings are not affected.

          (set one 1)
          error--> Symbol's value as variable is void: one
          (set 'one 1)
               => 1
          (set 'two 'one)
               => one
          (set two 2)         ; `two' evaluates to symbol `one'.
               => 2
          one                 ; So it is `one' that was set.
               => 2
          (let ((one 1))      ; This binding of `one' is set,
            (set 'one 3)      ;   not the global value.
            one)
               => 3
          one
               => 2

     If SYMBOL is not actually a symbol, a `wrong-type-argument' error
     is signaled.

          (set '(x y) 'z)
          error--> Wrong type argument: symbolp, (x y)

     Logically speaking, `set' is a more fundamental primitive than
     `setq'.  Any use of `setq' can be trivially rewritten to use
     `set'; `setq' could even be defined as a macro, given the
     availability of `set'.  However, `set' itself is rarely used;
     beginners hardly need to know about it.  It is useful only for
     choosing at run time which variable to set.  For example, the
     command `set-variable', which reads a variable name from the user
     and then sets the variable, needs to use `set'.

          Common Lisp note: In Common Lisp, `set' always changes the
          symbol's special value, ignoring any lexical bindings.  In
          XEmacs Lisp, all variables and all bindings are (in effect)
          special, so `set' always affects the most local existing
          binding.

   One other function for setting a variable is designed to add an
element to a list if it is not already present in the list.

 -- Function: add-to-list symbol element &optional append
     This function sets the variable SYMBOL by consing ELEMENT onto the
     old value, if ELEMENT is not already a member of that value.  It
     returns the resulting list, whether updated or not.  The value of
     SYMBOL had better be a list already before the call.

     If the optional argument APPEND is non-`nil', ELEMENT is added at
     the end of the list.

     The argument SYMBOL is not implicitly quoted; `add-to-list' is an
     ordinary function, like `set' and unlike `setq'.  Quote the
     argument yourself if that is what you want.

     Here's a scenario showing how to use `add-to-list':

          (setq foo '(a b))
               => (a b)

          (add-to-list 'foo 'c)     ;; Add `c'.
               => (c a b)

          (add-to-list 'foo 'b)     ;; No effect.
               => (c a b)

          foo                       ;; `foo' was changed.
               => (c a b)

   An equivalent expression for `(add-to-list 'VAR VALUE)' is this:

     (or (member VALUE VAR)
         (setq VAR (cons VALUE VAR)))


File: lispref.info,  Node: Variable Scoping,  Next: Buffer-Local Variables,  Prev: Setting Variables,  Up: Variables

16.8 Scoping Rules for Variable Bindings
========================================

A given symbol `foo' may have several local variable bindings,
established at different places in the Lisp program, as well as a global
binding.  The most recently established binding takes precedence over
the others.

   Local bindings in XEmacs Lisp have "indefinite scope" and "dynamic
extent".  "Scope" refers to _where_ textually in the source code the
binding can be accessed.  Indefinite scope means that any part of the
program can potentially access the variable binding.  "Extent" refers
to _when_, as the program is executing, the binding exists.  Dynamic
extent means that the binding lasts as long as the activation of the
construct that established it.

   The combination of dynamic extent and indefinite scope is called
"dynamic scoping".  By contrast, most programming languages use
"lexical scoping", in which references to a local variable must be
located textually within the function or block that binds the variable.

     Common Lisp note: Variables declared "special" in Common Lisp are
     dynamically scoped, like variables in XEmacs Lisp.

* Menu:

* Scope::          Scope means where in the program a value is visible.
                     Comparison with other languages.
* Extent::         Extent means how long in time a value exists.
* Impl of Scope::  Two ways to implement dynamic scoping.
* Using Scoping::  How to use dynamic scoping carefully and avoid problems.


File: lispref.info,  Node: Scope,  Next: Extent,  Prev: Variable Scoping,  Up: Variable Scoping

16.8.1 Scope
------------

XEmacs Lisp uses "indefinite scope" for local variable bindings.  This
means that any function anywhere in the program text might access a
given binding of a variable.  Consider the following function
definitions:

     (defun binder (x)   ; `x' is bound in `binder'.
        (foo 5))         ; `foo' is some other function.

     (defun user ()      ; `x' is used in `user'.
       (list x))

   In a lexically scoped language, the binding of `x' in `binder' would
never be accessible in `user', because `user' is not textually
contained within the function `binder'.  However, in dynamically scoped
XEmacs Lisp, `user' may or may not refer to the binding of `x'
established in `binder', depending on circumstances:

   * If we call `user' directly without calling `binder' at all, then
     whatever binding of `x' is found, it cannot come from `binder'.

   * If we define `foo' as follows and call `binder', then the binding
     made in `binder' will be seen in `user':

          (defun foo (lose)
            (user))

   * If we define `foo' as follows and call `binder', then the binding
     made in `binder' _will not_ be seen in `user':

          (defun foo (x)
            (user))

     Here, when `foo' is called by `binder', it binds `x'.  (The
     binding in `foo' is said to "shadow" the one made in `binder'.)
     Therefore, `user' will access the `x' bound by `foo' instead of
     the one bound by `binder'.


File: lispref.info,  Node: Extent,  Next: Impl of Scope,  Prev: Scope,  Up: Variable Scoping

16.8.2 Extent
-------------

"Extent" refers to the time during program execution that a variable
name is valid.  In XEmacs Lisp, a variable is valid only while the form
that bound it is executing.  This is called "dynamic extent".  "Local"
or "automatic" variables in most languages, including C and Pascal,
have dynamic extent.

   One alternative to dynamic extent is "indefinite extent".  This
means that a variable binding can live on past the exit from the form
that made the binding.  Common Lisp and Scheme, for example, support
this, but XEmacs Lisp does not.

   To illustrate this, the function below, `make-add', returns a
function that purports to add N to its own argument M.  This would work
in Common Lisp, but it does not work as intended in XEmacs Lisp,
because after the call to `make-add' exits, the variable `n' is no
longer bound to the actual argument 2.

     (defun make-add (n)
         (function (lambda (m) (+ n m))))  ; Return a function.
          => make-add
     (fset 'add2 (make-add 2))  ; Define function `add2'
                                ;   with `(make-add 2)'.
          => (lambda (m) (+ n m))
     (add2 4)                   ; Try to add 2 to 4.
     error--> Symbol's value as variable is void: n

   Some Lisp dialects have "closures", objects that are like functions
but record additional variable bindings.  Closures are available in
XEmacs Lisp using the `lexical-let' and `lexical-let*' macros, which
are autoloaded from `cl-macs'.  *Note (cl)Lexical Bindings::.  Note
that function arguments cannot be closed around using these macros, and
that any lambda expressions returned will not be byte-compiled.


File: lispref.info,  Node: Impl of Scope,  Next: Using Scoping,  Prev: Extent,  Up: Variable Scoping

16.8.3 Implementation of Dynamic Scoping
----------------------------------------

A simple sample implementation (which is not how XEmacs Lisp actually
works) may help you understand dynamic binding.  This technique is
called "deep binding" and was used in early Lisp systems.

   Suppose there is a stack of bindings: variable-value pairs.  At entry
to a function or to a `let' form, we can push bindings on the stack for
the arguments or local variables created there.  We can pop those
bindings from the stack at exit from the binding construct.

   We can find the value of a variable by searching the stack from top
to bottom for a binding for that variable; the value from that binding
is the value of the variable.  To set the variable, we search for the
current binding, then store the new value into that binding.

   As you can see, a function's bindings remain in effect as long as it
continues execution, even during its calls to other functions.  That is
why we say the extent of the binding is dynamic.  And any other function
can refer to the bindings, if it uses the same variables while the
bindings are in effect.  That is why we say the scope is indefinite.

   The actual implementation of variable scoping in XEmacs Lisp uses a
technique called "shallow binding".  Each variable has a standard place
in which its current value is always found--the value cell of the
symbol.

   In shallow binding, setting the variable works by storing a value in
the value cell.  Creating a new binding works by pushing the old value
(belonging to a previous binding) on a stack, and storing the local
value in the value cell.  Eliminating a binding works by popping the
old value off the stack, into the value cell.

   We use shallow binding because it has the same results as deep
binding, but runs faster, since there is never a need to search for a
binding.


File: lispref.info,  Node: Using Scoping,  Prev: Impl of Scope,  Up: Variable Scoping

16.8.4 Proper Use of Dynamic Scoping
------------------------------------

Binding a variable in one function and using it in another is a
powerful technique, but if used without restraint, it can make programs
hard to understand.  There are two clean ways to use this technique:

   * Use or bind the variable only in a few related functions, written
     close together in one file.  Such a variable is used for
     communication within one program.

     You should write comments to inform other programmers that they
     can see all uses of the variable before them, and to advise them
     not to add uses elsewhere.

   * Give the variable a well-defined, documented meaning, and make all
     appropriate functions refer to it (but not bind it or set it)
     wherever that meaning is relevant.  For example, the variable
     `case-fold-search' is defined as "non-`nil' means ignore case when
     searching"; various search and replace functions refer to it
     directly or through their subroutines, but do not bind or set it.

     Then you can bind the variable in other programs, knowing reliably
     what the effect will be.

   In either case, you should define the variable with `defvar'.  This
helps other people understand your program by telling them to look for
inter-function usage.  It also avoids a warning from the byte compiler.
Choose the variable's name to avoid name conflicts--don't use short
names like `x'.


File: lispref.info,  Node: Buffer-Local Variables,  Next: Variable Aliases,  Prev: Variable Scoping,  Up: Variables

16.9 Buffer-Local Variables
===========================

Global and local variable bindings are found in most programming
languages in one form or another.  XEmacs also supports another, unusual
kind of variable binding: "buffer-local" bindings, which apply only to
one buffer.  XEmacs Lisp is meant for programming editing commands, and
having different values for a variable in different buffers is an
important customization method.

* Menu:

* Intro to Buffer-Local::      Introduction and concepts.
* Creating Buffer-Local::      Creating and destroying buffer-local bindings.
* Default Value::              The default value is seen in buffers
                                 that don't have their own local values.


File: lispref.info,  Node: Intro to Buffer-Local,  Next: Creating Buffer-Local,  Prev: Buffer-Local Variables,  Up: Buffer-Local Variables

16.9.1 Introduction to Buffer-Local Variables
---------------------------------------------

A buffer-local variable has a buffer-local binding associated with a
particular buffer.  The binding is in effect when that buffer is
current; otherwise, it is not in effect.  If you set the variable while
a buffer-local binding is in effect, the new value goes in that binding,
so the global binding is unchanged; this means that the change is
visible in that buffer alone.

   A variable may have buffer-local bindings in some buffers but not in
others.  The global binding is shared by all the buffers that don't have
their own bindings.  Thus, if you set the variable in a buffer that does
not have a buffer-local binding for it, the new value is visible in all
buffers except those with buffer-local bindings.  (Here we are assuming
that there are no `let'-style local bindings to complicate the issue.)

   The most common use of buffer-local bindings is for major modes to
change variables that control the behavior of commands.  For example, C
mode and Lisp mode both set the variable `paragraph-start' to specify
that only blank lines separate paragraphs.  They do this by making the
variable buffer-local in the buffer that is being put into C mode or
Lisp mode, and then setting it to the new value for that mode.

   The usual way to make a buffer-local binding is with
`make-local-variable', which is what major mode commands use.  This
affects just the current buffer; all other buffers (including those yet
to be created) continue to share the global value.

   A more powerful operation is to mark the variable as "automatically
buffer-local" by calling `make-variable-buffer-local'.  You can think
of this as making the variable local in all buffers, even those yet to
be created.  More precisely, the effect is that setting the variable
automatically makes the variable local to the current buffer if it is
not already so.  All buffers start out by sharing the global value of
the variable as usual, but any `setq' creates a buffer-local binding
for the current buffer.  The new value is stored in the buffer-local
binding, leaving the (default) global binding untouched.  The global
value can no longer be changed with `setq'; you need to use
`setq-default' to do that.

   Local variables in a file you edit are also represented by
buffer-local bindings for the buffer that holds the file within XEmacs.
*Note Auto Major Mode::.


File: lispref.info,  Node: Creating Buffer-Local,  Next: Default Value,  Prev: Intro to Buffer-Local,  Up: Buffer-Local Variables

16.9.2 Creating and Deleting Buffer-Local Bindings
--------------------------------------------------

Besides the functions mentioned here, buffer-local variables are also
created when file-local variables are set.  *Note Auto Major Mode::.  .
There is no way (outside of `eval' lines, which are normally disabled)
to set the global value of a variable from the file local variable
specifications.

 -- Command: make-local-variable variable
     This function creates a buffer-local binding in the current buffer
     for VARIABLE (a symbol).  Other buffers are not affected.  The
     value returned is VARIABLE.

     The buffer-local value of VARIABLE starts out as the same value
     VARIABLE previously had.  If VARIABLE was void, it remains void.

          ;; In buffer `b1':
          (setq foo 5)                ; Affects all buffers.
               => 5
          (make-local-variable 'foo)  ; Now it is local in `b1'.
               => foo
          foo                         ; That did not change
               => 5                   ;   the value.
          (setq foo 6)                ; Change the value
               => 6                   ;   in `b1'.
          foo
               => 6

          ;; In buffer `b2', the value hasn't changed.
          (save-excursion
            (set-buffer "b2")
            foo)
               => 5

     Making a variable buffer-local within a `let'-binding for that
     variable does not work.  This is because `let' does not distinguish
     between different kinds of bindings; it knows only which variable
     the binding was made for.

     *Please note:* do not use `make-local-variable' for a hook
     variable.  Instead, use `make-local-hook'.  *Note Hooks::.

 -- Command: make-variable-buffer-local variable
     This function marks VARIABLE (a symbol) automatically
     buffer-local, so that any subsequent attempt to set it will make it
     local to the current buffer at the time.

     The value returned is VARIABLE.

 -- Function: local-variable-p variable buffer &optional after-set
     This returns `t' if VARIABLE is buffer-local in buffer BUFFER;
     else `nil'.

     If optional third arg AFTER-SET is non-`nil', return `t' if SYMBOL
     would be buffer-local after it is set, regardless of whether it is
     so presently.

     A `nil' value for BUFFER is _not_ the same as `(current-buffer)',
     but means "no buffer".  Specifically:

     If BUFFER is `nil' and AFTER-SET is `nil', a return value of `t'
     indicates that the variable is one of the special built-in
     variables that is always buffer-local. (This includes
     `buffer-file-name', `buffer-read-only', `buffer-undo-list', and
     others.)

     If BUFFER is `nil' and AFTER-SET is `t', a return value of `t'
     indicates that the variable has had `make-variable-buffer-local'
     applied to it.

 -- Function: buffer-local-variables &optional buffer
     This function returns a list describing the buffer-local variables
     in buffer BUFFER.  It returns an association list (*note
     Association Lists::) in which each association contains one
     buffer-local variable and its value.  When a buffer-local variable
     is void in BUFFER, then it appears directly in the resulting list.
     If BUFFER is omitted, the current buffer is used.

          (make-local-variable 'foobar)
          (makunbound 'foobar)
          (make-local-variable 'bind-me)
          (setq bind-me 69)
          (setq lcl (buffer-local-variables))
              ;; First, built-in variables local in all buffers:
          => ((mark-active . nil)
              (buffer-undo-list nil)
              (mode-name . "Fundamental")
              ...
              ;; Next, non-built-in local variables.
              ;; This one is local and void:
              foobar
              ;; This one is local and nonvoid:
              (bind-me . 69))

     Note that storing new values into the CDRs of cons cells in this
     list does _not_ change the local values of the variables.

 -- Command: kill-local-variable variable
     This function deletes the buffer-local binding (if any) for
     VARIABLE (a symbol) in the current buffer.  As a result, the
     global (default) binding of VARIABLE becomes visible in this
     buffer.  Usually this results in a change in the value of
     VARIABLE, since the global value is usually different from the
     buffer-local value just eliminated.

     If you kill the local binding of a variable that automatically
     becomes local when set, this makes the global value visible in the
     current buffer.  However, if you set the variable again, that will
     once again create a local binding for it.

     `kill-local-variable' returns VARIABLE.

     This function is a command because it is sometimes useful to kill
     one buffer-local variable interactively, just as it is useful to
     create buffer-local variables interactively.

 -- Function: kill-all-local-variables
     This function eliminates all the buffer-local variable bindings of
     the current buffer except for variables marked as "permanent".  As
     a result, the buffer will see the default values of most variables.

     This function also resets certain other information pertaining to
     the buffer: it sets the local keymap to `nil', the syntax table to
     the value of `standard-syntax-table', and the abbrev table to the
     value of `fundamental-mode-abbrev-table'.

     Every major mode command begins by calling this function, which
     has the effect of switching to Fundamental mode and erasing most
     of the effects of the previous major mode.  To ensure that this
     does its job, the variables that major modes set should not be
     marked permanent.

     `kill-all-local-variables' returns `nil'.

   A local variable is "permanent" if the variable name (a symbol) has a
`permanent-local' property that is non-`nil'.  Permanent locals are
appropriate for data pertaining to where the file came from or how to
save it, rather than with how to edit the contents.


File: lispref.info,  Node: Default Value,  Prev: Creating Buffer-Local,  Up: Buffer-Local Variables

16.9.3 The Default Value of a Buffer-Local Variable
---------------------------------------------------

The global value of a variable with buffer-local bindings is also
called the "default" value, because it is the value that is in effect
except when specifically overridden.

   The functions `default-value' and `setq-default' access and change a
variable's default value regardless of whether the current buffer has a
buffer-local binding.  For example, you could use `setq-default' to
change the default setting of `paragraph-start' for most buffers; and
this would work even when you are in a C or Lisp mode buffer that has a
buffer-local value for this variable.

   The special operators `defvar' and `defconst' also set the default
value (if they set the variable at all), rather than any local value.

 -- Function: default-value symbol
     This function returns SYMBOL's default value.  This is the value
     that is seen in buffers that do not have their own values for this
     variable.  If SYMBOL is not buffer-local, this is equivalent to
     `symbol-value' (*note Accessing Variables::).

 -- Function: default-boundp symbol
     The function `default-boundp' tells you whether SYMBOL's default
     value is nonvoid.  If `(default-boundp 'foo)' returns `nil', then
     `(default-value 'foo)' would get an error.

     `default-boundp' is to `default-value' as `boundp' is to
     `symbol-value'.

 -- Special Operator: setq-default symbol value
     This sets the default value of SYMBOL to VALUE.  It does not
     evaluate SYMBOL, but does evaluate VALUE.  The value of the
     `setq-default' form is VALUE.

     If a SYMBOL is not buffer-local for the current buffer, and is not
     marked automatically buffer-local, `setq-default' has the same
     effect as `setq'.  If SYMBOL is buffer-local for the current
     buffer, then this changes the value that other buffers will see
     (as long as they don't have a buffer-local value), but not the
     value that the current buffer sees.

          ;; In buffer `foo':
          (make-local-variable 'local)
               => local
          (setq local 'value-in-foo)
               => value-in-foo
          (setq-default local 'new-default)
               => new-default
          local
               => value-in-foo
          (default-value 'local)
               => new-default

          ;; In (the new) buffer `bar':
          local
               => new-default
          (default-value 'local)
               => new-default
          (setq local 'another-default)
               => another-default
          (default-value 'local)
               => another-default

          ;; Back in buffer `foo':
          local
               => value-in-foo
          (default-value 'local)
               => another-default

 -- Function: set-default symbol value
     This function is like `setq-default', except that SYMBOL is
     evaluated.

          (set-default (car '(a b c)) 23)
               => 23
          (default-value 'a)
               => 23


File: lispref.info,  Node: Variable Aliases,  Prev: Buffer-Local Variables,  Up: Variables

16.10 Variable Aliases
======================

You can define a variable as an "alias" for another.  Any time you
reference the former variable, the current value of the latter is
returned.  Any time you change the value of the former variable, the
value of the latter is actually changed.  This is useful in cases where
you want to rename a variable but still make old code work (*note
Obsoleteness::).

 -- Function: defvaralias variable alias
     This function defines VARIABLE as an alias for ALIAS.
     Thenceforth, any operations performed on VARIABLE will actually be
     performed on ALIAS.  Both VARIABLE and ALIAS should be symbols.
     If ALIAS is `nil', remove any aliases for VARIABLE.  ALIAS can
     itself be aliased, and the chain of variable aliases will be
     followed appropriately.  If VARIABLE already has a value, this
     value will be shadowed until the alias is removed, at which point
     it will be restored.  Currently VARIABLE cannot be a built-in
     variable, a variable that has a buffer-local value in any buffer,
     or the symbols `nil' or `t'.

 -- Function: variable-alias variable &optional follow-past-lisp-magic
     If VARIABLE is aliased to another variable, this function returns
     that variable.  VARIABLE should be a symbol.  If VARIABLE is not
     aliased, this function returns `nil'.

 -- Function: indirect-variable object &optional follow-past-lisp-magic
     This function returns the variable at the end of OBJECT's
     variable-alias chain.  If OBJECT is a symbol, follow all variable
     aliases and return the final (non-aliased) symbol.  If OBJECT is
     not a symbol, just return it.  Signal a
     `cyclic-variable-indirection' error if there is a loop in the
     variable chain of symbols.


File: lispref.info,  Node: Functions and Commands,  Next: Macros,  Prev: Variables,  Up: Top

17 Functions and Commands
*************************

A Lisp program is composed mainly of Lisp functions.  This chapter
explains what functions are, how they accept arguments, and how to
define them.

* Menu:

* What Is a Function::    Lisp functions vs. primitives; terminology.
* Lambda Expressions::    How functions are expressed as Lisp objects.
* Function Names::        A symbol can serve as the name of a function.
* Defining Functions::    Lisp expressions for defining functions.
* Calling Functions::     How to use an existing function.
* Mapping Functions::     Applying a function to each element of a list, etc.
* Anonymous Functions::   Lambda expressions are functions with no names.
* Function Cells::        Accessing or setting the function definition
                            of a symbol.
* Inline Functions::	  Defining functions that the compiler will open code.
* Related Topics::        Cross-references to specific Lisp primitives
                            that have a special bearing on how functions work.


File: lispref.info,  Node: What Is a Function,  Next: Lambda Expressions,  Prev: Functions and Commands,  Up: Functions and Commands

17.1 What Is a Function?
========================

In a general sense, a function is a rule for carrying on a computation
given several values called "arguments".  The result of the computation
is called the value of the function.  The computation can also have
side effects: lasting changes in the values of variables or the
contents of data structures.

   Here are important terms for functions in XEmacs Lisp and for other
function-like objects.

"function"
     In XEmacs Lisp, a "function" is anything that can be applied to
     arguments in a Lisp program.  In some cases, we use it more
     specifically to mean a function written in Lisp.  Special
     operators and macros are not functions.

"command"
     A "command" is a possible definition for a key sequence--we count
     mouse events and menu accesses as key sequences for this purpose.
     More formally, within XEmacs lisp, a command is something that
     `command-execute' can invoke.

     Some functions are commands; a function written in Lisp is a
     command if it contains an interactive declaration. A trivial
     interactive declaration is a line `(interactive)' immediately
     after the documentation string. For more complex examples, with
     prompting and completion, see *Note Defining Commands::. Such a
     function can be called from Lisp expressions like other functions;
     in this case, the fact that the function is a command makes no
     difference.

     Keyboard macros (strings and vectors) are commands also, even
     though they are not functions.  A symbol is a command if its
     function definition is a command; such symbols can be invoked with
     `M-x'.  The symbol is a function as well if the definition is a
     function.

     In the case where you want to call a command in reaction to a
     user-generated event, you'll need to bind it to that event.  For
     how to do this, see *Note Key Binding Commands::.  *Note Command
     Overview::.

"keystroke command"
     A "keystroke command" is a command that is bound to a key sequence
     (typically one to three keystrokes).  The distinction is made here
     merely to avoid confusion with the meaning of "command" in
     non-Emacs editors; for Lisp programs, the distinction is normally
     unimportant.

"primitive"
     A "primitive" is a function callable from Lisp that is written in
     C, such as `car' or `append'.  These functions are also called
     "built-in" functions or "subrs".  (Special operators are also
     considered primitives.)

     Usually the reason that a function is a primitives is because it is
     fundamental, because it provides a low-level interface to operating
     system services, or because it needs to run fast.  Primitives can
     be modified or added only by changing the C sources and
     recompiling the editor.  See *Note Writing Lisp Primitives:
     (internals)Writing Lisp Primitives.

"lambda expression"
     A "lambda expression" is a function written in Lisp.  These are
     described in the following section.  *Note Lambda Expressions::.

"special operator"
     A "special operator" is a primitive that is like a function but
     does not evaluate all of its arguments in the usual way.  It may
     evaluate only some of the arguments, or may evaluate them in an
     unusual order, or several times.  Many special operators are
     described in *Note Control Structures::.

"macro"
     A "macro" is a construct defined in Lisp by the programmer.  It
     differs from a function in that it translates a Lisp expression
     that you write into an equivalent expression to be evaluated
     instead of the original expression.  Macros enable Lisp
     programmers to do the sorts of things that special operators can
     do.  *Note Macros::, for how to define and use macros.

"compiled function"
     A "compiled function" is a function that has been compiled by the
     byte compiler.  *Note Compiled-Function Type::.

 -- Function: subrp object
     This function returns `t' if OBJECT is a built-in function (i.e.,
     a Lisp primitive).

          (subrp 'message)            ; `message' is a symbol,
               => nil                 ;   not a subr object.
          (subrp (symbol-function 'message))
               => t

 -- Function: compiled-function-p object
     This function returns `t' if OBJECT is a compiled function.  For
     example:

          (compiled-function-p (symbol-function 'next-line))
               => t


File: lispref.info,  Node: Lambda Expressions,  Next: Function Names,  Prev: What Is a Function,  Up: Functions and Commands

17.2 Lambda Expressions
=======================

A function written in Lisp is a list that looks like this:

     (lambda (ARG-VARIABLES...)
       [DOCUMENTATION-STRING]
       [INTERACTIVE-DECLARATION]
       BODY-FORMS...)

Such a list is called a "lambda expression".  In XEmacs Lisp, it
actually is valid as an expression--it evaluates to itself.  In some
other Lisp dialects, a lambda expression is not a valid expression at
all.  In either case, its main use is not to be evaluated as an
expression, but to be called as a function.

* Menu:

* Lambda Components::       The parts of a lambda expression.
* Simple Lambda::           A simple example.
* Argument List::           Details and special features of argument lists.
* Function Documentation::  How to put documentation in a function.


File: lispref.info,  Node: Lambda Components,  Next: Simple Lambda,  Prev: Lambda Expressions,  Up: Lambda Expressions

17.2.1 Components of a Lambda Expression
----------------------------------------

A function written in Lisp (a "lambda expression") is a list that looks
like this:

     (lambda (ARG-VARIABLES...)
       [DOCUMENTATION-STRING]
       [INTERACTIVE-DECLARATION]
       BODY-FORMS...)

The first element of a lambda expression is always the symbol `lambda'.
This indicates that the list represents a function.  The reason
functions are defined to start with `lambda' is so that other lists,
intended for other uses, will not accidentally be valid as functions.

   The second element is a list of symbols-the argument variable names.
This is called the "lambda list".  When a Lisp function is called, the
argument values are matched up against the variables in the lambda
list, which are given local bindings with the values provided.  *Note
Local Variables::.

   The documentation string is a Lisp string object placed within the
function definition to describe the function for the XEmacs help
facilities.  *Note Function Documentation::.

   The interactive declaration is a list of the form `(interactive
CODE-STRING)'.  This declares how to provide arguments if the function
is used interactively.  Functions with this declaration are called
"commands"; they can be called using `M-x' or bound to a key.
Functions not intended to be called in this way should not have
interactive declarations.  *Note Defining Commands::, for how to write
an interactive declaration.

   The rest of the elements are the "body" of the function: the Lisp
code to do the work of the function (or, as a Lisp programmer would say,
"a list of Lisp forms to evaluate").  The value returned by the
function is the value returned by the last element of the body.


File: lispref.info,  Node: Simple Lambda,  Next: Argument List,  Prev: Lambda Components,  Up: Lambda Expressions

17.2.2 A Simple Lambda-Expression Example
-----------------------------------------

Consider for example the following function:

     (lambda (a b c) (+ a b c))

We can call this function by writing it as the CAR of an expression,
like this:

     ((lambda (a b c) (+ a b c))
      1 2 3)

This call evaluates the body of the lambda expression  with the variable
`a' bound to 1, `b' bound to 2, and `c' bound to 3.  Evaluation of the
body adds these three numbers, producing the result 6; therefore, this
call to the function returns the value 6.

   Note that the arguments can be the results of other function calls,
as in this example:

     ((lambda (a b c) (+ a b c))
      1 (* 2 3) (- 5 4))

This evaluates the arguments `1', `(* 2 3)', and `(- 5 4)' from left to
right.  Then it applies the lambda expression to the argument values 1,
6 and 1 to produce the value 8.

   It is not often useful to write a lambda expression as the CAR of a
form in this way.  You can get the same result, of making local
variables and giving them values, using the special operator `let'
(*note Local Variables::).  And `let' is clearer and easier to use.  In
practice, lambda expressions are either stored as the function
definitions of symbols, to produce named functions, or passed as
arguments to other functions (*note Anonymous Functions::).

   However, calls to explicit lambda expressions were very useful in the
old days of Lisp, before the special operator `let' was invented.  At
that time, they were the only way to bind and initialize local
variables.


File: lispref.info,  Node: Argument List,  Next: Function Documentation,  Prev: Simple Lambda,  Up: Lambda Expressions

17.2.3 Advanced Features of Argument Lists
------------------------------------------

Our simple sample function, `(lambda (a b c) (+ a b c))', specifies
three argument variables, so it must be called with three arguments: if
you try to call it with only two arguments or four arguments, you get a
`wrong-number-of-arguments' error.

   It is often convenient to write a function that allows certain
arguments to be omitted.  For example, the function `subseq' accepts
three arguments--a sequence, the start index and the end index--but the
third argument defaults to the LENGTH of the sequence if you omit it.
It is also convenient for certain functions to accept an indefinite
number of arguments, as the functions `list' and `+' do.

   To specify optional arguments that may be omitted when a function is
called, simply include the keyword `&optional' before the optional
arguments.  To specify a list of zero or more extra arguments, include
the keyword `&rest' before one final argument.

   Thus, the complete syntax for an argument list is as follows:

     (REQUIRED-VARS...
      [&optional OPTIONAL-VARS...]
      [&rest REST-VAR])

The square brackets indicate that the `&optional' and `&rest' clauses,
and the variables that follow them, are optional.

   A call to the function requires one actual argument for each of the
REQUIRED-VARS.  There may be actual arguments for zero or more of the
OPTIONAL-VARS, and there cannot be any actual arguments beyond that
unless the lambda list uses `&rest'.  In that case, there may be any
number of extra actual arguments.

   If actual arguments for the optional and rest variables are omitted,
then they always default to `nil'.  There is no way for the function to
distinguish between an explicit argument of `nil' and an omitted
argument.  However, the body of the function is free to consider `nil'
an abbreviation for some other meaningful value.  This is what `subseq'
does; `nil' as the third argument to `subseq' means to use the length
of the sequence supplied.

     Common Lisp note: Common Lisp allows the function to specify what
     default value to use when an optional argument is omitted; this is
     available in XEmacs Lisp with the `defun*' macro, an alternative to
     `defun'.

   For example, an argument list that looks like this:

     (a b &optional c d &rest e)

binds `a' and `b' to the first two actual arguments, which are
required.  If one or two more arguments are provided, `c' and `d' are
bound to them respectively; any arguments after the first four are
collected into a list and `e' is bound to that list.  If there are only
two arguments, `c' is `nil'; if two or three arguments, `d' is `nil';
if four arguments or fewer, `e' is `nil'.

   There is no way to have required arguments following optional
ones--it would not make sense.  To see why this must be so, suppose
that `c' in the example were optional and `d' were required.  Suppose
three actual arguments are given; which variable would the third
argument be for?  Similarly, it makes no sense to have any more
arguments (either required or optional) after a `&rest' argument.

   Here are some examples of argument lists and proper calls:

     ((lambda (n) (1+ n))                ; One required:
      1)                                 ; requires exactly one argument.
          => 2
     ((lambda (n &optional n1)           ; One required and one optional:
              (if n1 (+ n n1) (1+ n)))   ; 1 or 2 arguments.
      1 2)
          => 3
     ((lambda (n &rest ns)               ; One required and one rest:
              (+ n (apply '+ ns)))       ; 1 or more arguments.
      1 2 3 4 5)
          => 15


File: lispref.info,  Node: Function Documentation,  Prev: Argument List,  Up: Lambda Expressions

17.2.4 Documentation Strings of Functions
-----------------------------------------

A lambda expression may optionally have a "documentation string" just
after the lambda list.  This string does not affect execution of the
function; it is a kind of comment, but a systematized comment which
actually appears inside the Lisp world and can be used by the XEmacs
help facilities.  *Note Documentation::, for how the
DOCUMENTATION-STRING is accessed.

   It is a good idea to provide documentation strings for all the
functions in your program, even those that are only called from within
your program.  Documentation strings are like comments, except that they
are easier to access.

   The first line of the documentation string should stand on its own,
because `apropos' displays just this first line.  It should consist of
one or two complete sentences that summarize the function's purpose.

   The start of the documentation string is usually indented in the
source file, but since these spaces come before the starting
double-quote, they are not part of the string.  Some people make a
practice of indenting any additional lines of the string so that the
text lines up in the program source.  _This is a mistake._  The
indentation of the following lines is inside the string; what looks
nice in the source code will look ugly when displayed by the help
commands.

   You may wonder how the documentation string could be optional, since
there are required components of the function that follow it (the body).
Since evaluation of a string returns that string, without any side
effects, it has no effect if it is not the last form in the body.
Thus, in practice, there is no confusion between the first form of the
body and the documentation string; if the only body form is a string
then it serves both as the return value and as the documentation.


File: lispref.info,  Node: Function Names,  Next: Defining Functions,  Prev: Lambda Expressions,  Up: Functions and Commands

17.3 Naming a Function
======================

In most computer languages, every function has a name; the idea of a
function without a name is nonsensical.  In Lisp, a function in the
strictest sense has no name.  It is simply a list whose first element is
`lambda', or a primitive subr-object.

   However, a symbol can serve as the name of a function.  This happens
when you put the function in the symbol's "function cell" (*note Symbol
Components::).  Then the symbol itself becomes a valid, callable
function, equivalent to the list or subr-object that its function cell
refers to.  The contents of the function cell are also called the
symbol's "function definition".  The procedure of using a symbol's
function definition in place of the symbol is called "symbol function
indirection"; see *Note Function Indirection::.

   In practice, nearly all functions are given names in this way and
referred to through their names.  For example, the symbol `car' works
as a function and does what it does because the primitive subr-object
`#<subr car>' is stored in its function cell.

   We give functions names because it is convenient to refer to them by
their names in Lisp expressions.  For primitive subr-objects such as
`#<subr car>', names are the only way you can refer to them: there is
no read syntax for such objects.  For functions written in Lisp, the
name is more convenient to use in a call than an explicit lambda
expression.  Also, a function with a name can refer to itself--it can
be recursive.  Writing the function's name in its own definition is much
more convenient than making the function definition point to itself
(something that is not impossible but that has various disadvantages in
practice).

   We often identify functions with the symbols used to name them.  For
example, we often speak of "the function `car'", not distinguishing
between the symbol `car' and the primitive subr-object that is its
function definition.  For most purposes, there is no need to
distinguish.

   Even so, keep in mind that a function need not have a unique name.
While a given function object _usually_ appears in the function cell of
only one symbol, this is just a matter of convenience.  It is easy to
store it in several symbols using `fset'; then each of the symbols is
equally well a name for the same function.

   A symbol used as a function name may also be used as a variable;
these two uses of a symbol are independent and do not conflict.


File: lispref.info,  Node: Defining Functions,  Next: Calling Functions,  Prev: Function Names,  Up: Functions and Commands

17.4 Defining Functions
=======================

We usually give a name to a function when it is first created.  This is
called "defining a function", and it is done with the `defun' special
operator.

 -- Special Operator: defun name argument-list body-forms
     `defun' is the usual way to define new Lisp functions.  It defines
     the symbol NAME as a function that looks like this:

          (lambda ARGUMENT-LIST . BODY-FORMS)

     `defun' stores this lambda expression in the function cell of
     NAME.  It returns the value NAME, but usually we ignore this value.

     As described previously (*note Lambda Expressions::),
     ARGUMENT-LIST is a list of argument names and may include the
     keywords `&optional' and `&rest'.  Also, the first two forms in
     BODY-FORMS may be a documentation string and an interactive
     declaration.

     There is no conflict if the same symbol NAME is also used as a
     variable, since the symbol's value cell is independent of the
     function cell.  *Note Symbol Components::.

     Here are some examples:

          (defun foo () 5)
               => foo
          (foo)
               => 5

          (defun bar (a &optional b &rest c)
              (list a b c))
               => bar
          (bar 1 2 3 4 5)
               => (1 2 (3 4 5))
          (bar 1)
               => (1 nil nil)
          (bar)
          error--> Wrong number of arguments.

          (defun capitalize-backwards ()
            "Upcase the last letter of a word."
            (interactive)
            (backward-word 1)
            (forward-word 1)
            (backward-char 1)
            (capitalize-word 1))
               => capitalize-backwards

     Be careful not to redefine existing functions unintentionally.
     `defun' redefines even primitive functions such as `car' without
     any hesitation or notification.  Redefining a function already
     defined is often done deliberately, and there is no way to
     distinguish deliberate redefinition from unintentional
     redefinition.

 -- Function: define-function name definition
 -- Function: defalias name definition
     These equivalent primitives define the symbol NAME as a function,
     with definition DEFINITION (which can be any valid Lisp function).

     The proper place to use `define-function' or `defalias' is where a
     specific function name is being defined--especially where that
     name appears explicitly in the source file being loaded.  This is
     because `define-function' and `defalias' record which file defined
     the function, just like `defun'.  (*note Unloading::).

     By contrast, in programs that manipulate function definitions for
     other purposes, it is better to use `fset', which does not keep
     such records.

   See also `defsubst', which defines a function like `defun' and tells
the Lisp compiler to open-code it.  *Note Inline Functions::.


File: lispref.info,  Node: Calling Functions,  Next: Mapping Functions,  Prev: Defining Functions,  Up: Functions and Commands

17.5 Calling Functions
======================

Defining functions is only half the battle.  Functions don't do
anything until you "call" them, i.e., tell them to run.  Calling a
function is also known as "invocation".

   The most common way of invoking a function is by evaluating a list.
For example, evaluating the list `(concat "a" "b")' calls the function
`concat' with arguments `"a"' and `"b"'.  *Note Evaluation::, for a
description of evaluation.

   When you write a list as an expression in your program, the function
name is part of the program.  This means that you choose which function
to call, and how many arguments to give it, when you write the program.
Usually that's just what you want.  Occasionally you need to decide at
run time which function to call.  To do that, use the functions
`funcall' and `apply'.

 -- Function: funcall function &rest arguments
     `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
     FUNCTION returns.

     Since `funcall' is a function, all of its arguments, including
     FUNCTION, are evaluated before `funcall' is called.  This means
     that you can use any expression to obtain the function to be
     called.  It also means that `funcall' does not see the expressions
     you write for the ARGUMENTS, only their values.  These values are
     _not_ evaluated a second time in the act of calling FUNCTION;
     `funcall' enters the normal procedure for calling a function at the
     place where the arguments have already been evaluated.

     The argument FUNCTION must be either a Lisp function or a
     primitive function.  Special operators and macros are not allowed,
     because they make sense only when given the "unevaluated" argument
     expressions.  `funcall' cannot provide these because, as we saw
     above, it never knows them in the first place.

          (setq f 'list)
               => list
          (funcall f 'x 'y 'z)
               => (x y z)
          (funcall f 'x 'y '(z))
               => (x y (z))
          (funcall 'and t nil)
          error--> Invalid function: #<subr and>

     Compare these example with the examples of `apply'.

 -- Function: apply function &rest arguments
     `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but
     with one difference: the last of ARGUMENTS is a list of arguments
     to give to FUNCTION, rather than a single argument.  We also say
     that `apply' "spreads" this list so that each individual element
     becomes an argument.

     `apply' returns the result of calling FUNCTION.  As with
     `funcall', FUNCTION must either be a Lisp function or a primitive
     function; special operators and macros do not make sense in
     `apply'.

          (setq f 'list)
               => list
          (apply f 'x 'y 'z)
          error--> Wrong type argument: listp, z
          (apply '+ 1 2 '(3 4))
               => 10
          (apply '+ '(1 2 3 4))
               => 10

          (apply 'append '((a b c) nil (x y z) nil))
               => (a b c x y z)

     For an interesting example of using `apply', see the description of
     `mapcar', in *Note Mapping Functions::.

   It is common for Lisp functions to accept functions as arguments or
find them in data structures (especially in hook variables and property
lists) and call them using `funcall' or `apply'.  Functions that accept
function arguments are often called "functionals".

   Sometimes, when you call a functional, it is useful to supply a no-op
function as the argument.  Here are two different kinds of no-op
function:

 -- Function: identity arg
     This function returns ARG and has no side effects.

 -- Command: ignore &rest args
     This function ignores any arguments and returns `nil'.


File: lispref.info,  Node: Mapping Functions,  Next: Anonymous Functions,  Prev: Calling Functions,  Up: Functions and Commands

17.6 Mapping Functions
======================

A "mapping function" applies a given function to each element of a list
or other collection.  XEmacs Lisp has several such functions; `mapcar'
and `mapconcat', which scan a list, are described here.   *Note
Creating Symbols::, for the function `mapatoms' which maps over the
symbols in an obarray.

   Mapping functions should never modify the sequence being mapped over.
The results are unpredictable.

 -- Function: mapcar function sequence
     `mapcar' applies FUNCTION to each element of SEQUENCE in turn, and
     returns a list of the results.

     The argument SEQUENCE can be any kind of sequence; that is, a
     list, a vector, a bit vector, or a string.  The result is always a
     list.  The length of the result is the same as the length of
     SEQUENCE.

     For example:

          (mapcar 'car '((a b) (c d) (e f)))
               => (a c e)
          (mapcar '1+ [1 2 3])
               => (2 3 4)
          (mapcar 'char-to-string "abc")
               => ("a" "b" "c")

          ;; Call each function in `my-hooks'.
          (mapcar 'funcall my-hooks)

          (defun mapcar* (f &rest args)
            "Apply FUNCTION to successive cars of all ARGS.
          Return the list of results."
            ;; If no list is exhausted,
            (if (not (memq 'nil args))
                ;; apply function to CARs.
                (cons (apply f (mapcar 'car args))
                      (apply 'mapcar* f
                             ;; Recurse for rest of elements.
                             (mapcar 'cdr args)))))

          (mapcar* 'cons '(a b c) '(1 2 3 4))
               => ((a . 1) (b . 2) (c . 3))

 -- Function: mapconcat function sequence separator
     `mapconcat' applies FUNCTION to each element of SEQUENCE: the
     results, which must be strings, are concatenated.  Between each
     pair of result strings, `mapconcat' inserts the string SEPARATOR.
     Usually SEPARATOR contains a space or comma or other suitable
     punctuation.

     The argument FUNCTION must be a function that can take one
     argument and return a string.  The argument SEQUENCE can be any
     kind of sequence; that is, a list, a vector, a bit vector, or a
     string.

          (mapconcat 'symbol-name
                     '(The cat in the hat)
                     " ")
               => "The cat in the hat"

          (mapconcat (function (lambda (x) (format "%c" (1+ x))))
                     "HAL-8000"
                     "")
               => "IBM.9111"


File: lispref.info,  Node: Anonymous Functions,  Next: Function Cells,  Prev: Mapping Functions,  Up: Functions and Commands

17.7 Anonymous Functions
========================

In Lisp, a function is a list that starts with `lambda', a byte-code
function compiled from such a list, or alternatively a primitive
subr-object; names are "extra".  Although usually functions are defined
with `defun' and given names at the same time, it is occasionally more
concise to use an explicit lambda expression--an anonymous function.
Such a list is valid wherever a function name is.

   Any method of creating such a list makes a valid function.  Even
this:

     (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
     => (lambda (x) (+ 12 x))

This computes a list that looks like `(lambda (x) (+ 12 x))' and makes
it the value (_not_ the function definition!) of `silly'.

   Here is how we might call this function:

     (funcall silly 1)
     => 13

(It does _not_ work to write `(silly 1)', because this function is not
the _function definition_ of `silly'.  We have not given `silly' any
function definition, just a value as a variable.)

   Most of the time, anonymous functions are constants that appear in
your program.  For example, you might want to pass one as an argument
to the function `mapcar', which applies any given function to each
element of a list.  Here we pass an anonymous function that multiplies
a number by two:

     (defun double-each (list)
       (mapcar '(lambda (x) (* 2 x)) list))
     => double-each
     (double-each '(2 11))
     => (4 22)

In such cases, we usually use the special operator `function' instead
of simple quotation to quote the anonymous function.

 -- Special Operator: function function-object
     This special operator returns FUNCTION-OBJECT without evaluating
     it.  In this, it is equivalent to `quote'.  However, it serves as a
     note to the XEmacs Lisp compiler that FUNCTION-OBJECT is intended
     to be used only as a function, and therefore can safely be
     compiled.  Contrast this with `quote', in *Note Quoting::.

   Using `function' instead of `quote' makes a difference inside a
function or macro that you are going to compile.  For example:

     (defun double-each (list)
       (mapcar (function (lambda (x) (* 2 x))) list))
     => double-each
     (double-each '(2 11))
     => (4 22)

If this definition of `double-each' is compiled, the anonymous function
is compiled as well.  By contrast, in the previous definition where
ordinary `quote' is used, the argument passed to `mapcar' is the
precise list shown:

     (lambda (x) (* x 2))

The Lisp compiler cannot assume this list is a function, even though it
looks like one, since it does not know what `mapcar' does with the
list.  Perhaps `mapcar' will check that the CAR of the third element is
the symbol `*'!  The advantage of `function' is that it tells the
compiler to go ahead and compile the constant function.

   We sometimes write `function' instead of `quote' when quoting the
name of a function, but this usage is just a sort of comment.

     (function SYMBOL) == (quote SYMBOL) == 'SYMBOL

   See `documentation' in *Note Accessing Documentation::, for a
realistic example using `function' and an anonymous function.


File: lispref.info,  Node: Function Cells,  Next: Inline Functions,  Prev: Anonymous Functions,  Up: Functions and Commands

17.8 Accessing Function Cell Contents
=====================================

The "function definition" of a symbol is the object stored in the
function cell of the symbol.  The functions described here access, test,
and set the function cell of symbols.

   See also the function `indirect-function' in *Note Function
Indirection::.

 -- Function: symbol-function symbol
     This returns the object in the function cell of SYMBOL.  If the
     symbol's function cell is void, a `void-function' error is
     signaled.

     This function does not check that the returned object is a
     legitimate function.

          (defun bar (n) (+ n 2))
               => bar
          (symbol-function 'bar)
               => (lambda (n) (+ n 2))
          (fset 'baz 'bar)
               => bar
          (symbol-function 'baz)
               => bar

   If you have never given a symbol any function definition, we say that
that symbol's function cell is "void".  In other words, the function
cell does not have any Lisp object in it.  If you try to call such a
symbol as a function, it signals a `void-function' error.

   Note that void is not the same as `nil' or the symbol `void'.  The
symbols `nil' and `void' are Lisp objects, and can be stored into a
function cell just as any other object can be (and they can be valid
functions if you define them in turn with `defun').  A void function
cell contains no object whatsoever.

   You can test the voidness of a symbol's function definition with
`fboundp'.  After you have given a symbol a function definition, you
can make it void once more using `fmakunbound'.

 -- Function: fboundp symbol
     This function returns `t' if SYMBOL has an object in its function
     cell, `nil' otherwise.  It does not check that the object is a
     legitimate function.

 -- Function: fmakunbound symbol
     This function makes SYMBOL's function cell void, so that a
     subsequent attempt to access this cell will cause a `void-function'
     error.  (See also `makunbound', in *Note Local Variables::.)

          (defun foo (x) x)
               => x
          (foo 1)
               =>1
          (fmakunbound 'foo)
               => x
          (foo 1)
          error--> Symbol's function definition is void: foo

 -- Function: fset symbol object
     This function stores OBJECT in the function cell of SYMBOL.  The
     result is OBJECT.  Normally OBJECT should be a function or the
     name of a function, but this is not checked.

     There are three normal uses of this function:

        * Copying one symbol's function definition to another.  (In
          other words, making an alternate name for a function.)

        * Giving a symbol a function definition that is not a list and
          therefore cannot be made with `defun'.  For example, you can
          use `fset' to give a symbol SYMBOL1 a function definition
          which is another symbol SYMBOL2; then SYMBOL1 serves as an
          alias for whatever definition SYMBOL2 presently has.

        * In constructs for defining or altering functions.  If `defun'
          were not a primitive, it could be written in Lisp (as a
          macro) using `fset'.

     Here are examples of the first two uses:

          ;; Give `first' the same definition `car' has.
          (fset 'first (symbol-function 'car))
               => #<subr car>
          (first '(1 2 3))
               => 1

          ;; Make the symbol `car' the function definition of `xfirst'.
          (fset 'xfirst 'car)
               => car
          (xfirst '(1 2 3))
               => 1
          (symbol-function 'xfirst)
               => car
          (symbol-function (symbol-function 'xfirst))
               => #<subr car>

          ;; Define a named keyboard macro.
          (fset 'kill-two-lines "\^u2\^k")
               => "\^u2\^k"

     See also the related functions `define-function' and `defalias',
     in *Note Defining Functions::.

   When writing a function that extends a previously defined function,
the following idiom is sometimes used:

     (fset 'old-foo (symbol-function 'foo))
     (defun foo ()
       "Just like old-foo, except more so."
       (old-foo)
       (more-so))

This does not work properly if `foo' has been defined to autoload.  In
such a case, when `foo' calls `old-foo', Lisp attempts to define
`old-foo' by loading a file.  Since this presumably defines `foo'
rather than `old-foo', it does not produce the proper results.  The
only way to avoid this problem is to make sure the file is loaded
before moving aside the old definition of `foo'.

   But it is unmodular and unclean, in any case, for a Lisp file to
redefine a function defined elsewhere.


File: lispref.info,  Node: Inline Functions,  Next: Related Topics,  Prev: Function Cells,  Up: Functions and Commands

17.9 Inline Functions
=====================

You can define an "inline function" by using `defsubst' instead of
`defun'.  An inline function works just like an ordinary function
except for one thing: when you compile a call to the function, the
function's definition is open-coded into the caller.

   Making a function inline makes explicit calls run faster.  But it
also has disadvantages.  For one thing, it reduces flexibility; if you
change the definition of the function, calls already inlined still use
the old definition until you recompile them.  Since the flexibility of
redefining functions is an important feature of XEmacs, you should not
make a function inline unless its speed is really crucial.

   Another disadvantage is that making a large function inline can
increase the size of compiled code both in files and in memory.  Since
the speed advantage of inline functions is greatest for small
functions, you generally should not make large functions inline.

   It's possible to define a macro to expand into the same code that an
inline function would execute.  But the macro would have a limitation:
you can use it only explicitly--a macro cannot be called with `apply',
`mapcar' and so on.  Also, it takes some work to convert an ordinary
function into a macro.  (*Note Macros::.)  To convert it into an inline
function is very easy; simply replace `defun' with `defsubst'.  Since
each argument of an inline function is evaluated exactly once, you
needn't worry about how many times the body uses the arguments, as you
do for macros.  (*Note Argument Evaluation::.)

   Inline functions can be used and open-coded later on in the same
file, following the definition, just like macros.


File: lispref.info,  Node: Related Topics,  Prev: Inline Functions,  Up: Functions and Commands

17.10 Other Topics Related to Functions
=======================================

Here is a table of several functions that do things related to function
calling and function definitions.  They are documented elsewhere, but
we provide cross references here.

`apply'
     See *Note Calling Functions::.

`autoload'
     See *Note Autoload::.

`call-interactively'
     See *Note Interactive Call::.

`commandp'
     See *Note Interactive Call::.

`documentation'
     See *Note Accessing Documentation::.

`eval'
     See *Note Eval::.

`funcall'
     See *Note Calling Functions::.

`ignore'
     See *Note Calling Functions::.

`indirect-function'
     See *Note Function Indirection::.

`interactive'
     See *Note Using Interactive::.

`interactive-p'
     See *Note Interactive Call::.

`mapatoms'
     See *Note Creating Symbols::.

`mapcar'
     See *Note Mapping Functions::.

`mapconcat'
     See *Note Mapping Functions::.

`undefined'
     See *Note Key Lookup::.


File: lispref.info,  Node: Macros,  Next: Customization,  Prev: Functions and Commands,  Up: Top

18 Macros
*********

"Macros" enable you to define new control constructs and other language
features.  A macro is defined much like a function, but instead of
telling how to compute a value, it tells how to compute another Lisp
expression which will in turn compute the value.  We call this
expression the "expansion" of the macro.

   Macros can do this because they operate on the unevaluated
expressions for the arguments, not on the argument values as functions
do.  They can therefore construct an expansion containing these
argument expressions or parts of them.

   If you are using a macro to do something an ordinary function could
do, just for the sake of speed, consider using an inline function
instead.  *Note Inline Functions::.

* Menu:

* Simple Macro::            A basic example.
* Expansion::               How, when and why macros are expanded.
* Compiling Macros::        How macros are expanded by the compiler.
* Defining Macros::         How to write a macro definition.
* Backquote::               Easier construction of list structure.
* Problems with Macros::    Don't evaluate the macro arguments too many times.
                              Don't hide the user's variables.


File: lispref.info,  Node: Simple Macro,  Next: Expansion,  Prev: Macros,  Up: Macros

18.1 A Simple Example of a Macro
================================

Suppose we would like to define a Lisp construct to increment a
variable value, much like the `++' operator in C.  We would like to
write `(inc x)' and have the effect of `(setq x (1+ x))'.  Here's a
macro definition that does the job:

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

   When this is called with `(inc x)', the argument `var' has the value
`x'--_not_ the _value_ of `x'.  The body of the macro uses this to
construct the expansion, which is `(setq x (1+ x))'.  Once the macro
definition returns this expansion, Lisp proceeds to evaluate it, thus
incrementing `x'.


File: lispref.info,  Node: Expansion,  Next: Compiling Macros,  Prev: Simple Macro,  Up: Macros

18.2 Expansion of a Macro Call
==============================

A macro call looks just like a function call in that it is a list which
starts with the name of the macro.  The rest of the elements of the list
are the arguments of the macro.

   Evaluation of the macro call begins like evaluation of a function
call except for one crucial difference: the macro arguments are the
actual expressions appearing in the macro call.  They are not evaluated
before they are given to the macro definition.  By contrast, the
arguments of a function are results of evaluating the elements of the
function call list.

   Having obtained the arguments, Lisp invokes the macro definition just
as a function is invoked.  The argument variables of the macro are bound
to the argument values from the macro call, or to a list of them in the
case of a `&rest' argument.  And the macro body executes and returns
its value just as a function body does.

   The second crucial difference between macros and functions is that
the value returned by the macro body is not the value of the macro call.
Instead, it is an alternate expression for computing that value, also
known as the "expansion" of the macro.  The Lisp interpreter proceeds
to evaluate the expansion as soon as it comes back from the macro.

   Since the expansion is evaluated in the normal manner, it may contain
calls to other macros.  It may even be a call to the same macro, though
this is unusual.

   You can see the expansion of a given macro call by calling
`macroexpand'.  However, in normal use, `cl-prettyexpand' will be more
helpful, since it expands _all_ the macros in the form, and prints the
output with more readable indentation. *note (cl)Efficiency Concerns::.

 -- Function: macroexpand form &optional environment
     This function expands FORM, if it is a macro call.  If the result
     is another macro call, it is expanded in turn, until something
     which is not a macro call results.  That is the value returned by
     `macroexpand'.  If FORM is not a macro call to begin with, it is
     returned as given.

     Note that `macroexpand' does not look at the subexpressions of
     FORM (although some macro definitions may do so).  Even if they
     are macro calls themselves, `macroexpand' does not expand them.

     The function `macroexpand' does not expand calls to inline
     functions.  Normally there is no need for that, since a call to an
     inline function is no harder to understand than a call to an
     ordinary function.

     If ENVIRONMENT is provided, it specifies an alist of macro
     definitions that shadow the currently defined macros.  Byte
     compilation uses this feature.

     To access ENVIRONMENT within the body of a macro, define the macro
     using `defmacro*' or `macrolet', and use the `&environment' lambda
     list keyword.  This may be necessary if you need to force macro
     expansion of the body of a form at the same time as top-level
     macro expansion.  *note (cl)Argument Lists::.

     Macro expansion examples:

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

          (macroexpand '(inc r))
               => (setq r (1+ r))

          (defmacro inc2 (var1 var2)
              (list 'progn (list 'inc var1) (list 'inc var2)))
               => inc2

          (macroexpand '(inc2 r s))
               => (progn (inc r) (inc s))  ; `inc' not expanded here.


File: lispref.info,  Node: Compiling Macros,  Next: Defining Macros,  Prev: Expansion,  Up: Macros

18.3 Macros and Byte Compilation
================================

You might ask why we take the trouble to compute an expansion for a
macro and then evaluate the expansion.  Why not have the macro body
produce the desired results directly?  The reason has to do with
compilation.

   When a macro call appears in a Lisp program being compiled, the Lisp
compiler calls the macro definition just as the interpreter would, and
receives an expansion.  But instead of evaluating this expansion, it
compiles the expansion as if it had appeared directly in the program.
As a result, the compiled code produces the value and side effects
intended for the macro, but executes at full compiled speed.  This would
not work if the macro body computed the value and side effects
itself--they would be computed at compile time, which is not useful.

   In order for compilation of macro calls to work, the macros must be
defined in Lisp when the calls to them are compiled.  The compiler has a
special feature to help you do this: if a file being compiled contains a
`defmacro' form, the macro is defined temporarily for the rest of the
compilation of that file.  To use this feature, you must define the
macro in the same file where it is used and before its first use.

   Byte-compiling a file executes any `require' calls at top-level in
the file.  This is in case the file needs the required packages for
proper compilation.  One way to ensure that necessary macro definitions
are available during compilation is to require the files that define
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::).


File: lispref.info,  Node: Defining Macros,  Next: Backquote,  Prev: Compiling Macros,  Up: Macros

18.4 Defining Macros
====================

A Lisp macro is a list whose CAR is `macro'.  Its CDR should be a
function; expansion of the macro works by applying the function (with
`apply') to the list of unevaluated argument-expressions from the macro
call.

   It is possible to use an anonymous Lisp macro just like an anonymous
function.  It doesn't make sense to pass an anonymous macro to
functionals such as `mapcar', and it is usually more readable to use
`macrolet' to make a local macro definition, and call that.  But if,
for whatever reason, `macrolet' is not available, code like the
following may be useful:

     ((macro . (lambda (&rest arguments)
     	    (let (res)
     	      (while (consp arguments)
     		(setq res (cons (cons 'put
     				      (cons (list 'quote (car arguments))
     					    '((quote my-property) t)))
     				res)
     		      arguments (cdr arguments)))
     	      (cons 'progn res))))
      + - = floor ceiling round)

   This expands to:

     (progn
       (put 'round 'my-property t)
       (put 'ceiling 'my-property t)
       (put 'floor 'my-property t)
       (put '= 'my-property t)
       (put '- 'my-property t)
       (put '+ 'my-property t))

   In practice, almost all Lisp macros have names, and they are usually
defined with the special operator `defmacro'.

 -- Special Operator: defmacro name argument-list body-forms...
     `defmacro' defines the symbol NAME as a macro that looks like this:

          (macro lambda ARGUMENT-LIST . BODY-FORMS)

     This macro object is stored in the function cell of NAME.  The
     value returned by evaluating the `defmacro' form is NAME, but
     usually we ignore this value.

     The shape and meaning of ARGUMENT-LIST is the same as in a
     function, and the keywords `&rest' and `&optional' may be used
     (*note Argument List::).  Macros may have a documentation string,
     but any `interactive' declaration is ignored since macros cannot be
     called interactively.


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

18.5 Backquote
==============

Macros often need to construct large list structures from a mixture of
constants and nonconstant parts.  To make this easier, use the macro
``' (often called "backquote").

   Backquote allows you to quote a list, but selectively evaluate
elements of that list.  In the simplest case, it is identical to the
special operator `quote' (*note Quoting::).  For example, these two
forms yield identical results:

     `(a list of (+ 2 3) elements)
          => (a list of (+ 2 3) elements)
     '(a list of (+ 2 3) elements)
          => (a list of (+ 2 3) elements)

   The special marker `,' inside of the argument to backquote indicates
a value that isn't constant.  Backquote evaluates the argument of `,'
and puts the value in the list structure:

     (list 'a 'list 'of (+ 2 3) 'elements)
          => (a list of 5 elements)
     `(a list of ,(+ 2 3) elements)
          => (a list of 5 elements)

   You can also "splice" an evaluated value into the resulting list,
using the special marker `,@'.  The elements of the spliced list become
elements at the same level as the other elements of the resulting list.
The equivalent code without using ``' is often unreadable.  Here are
some examples:

     (setq some-list '(2 3))
          => (2 3)
     (cons 1 (append some-list '(4) some-list))
          => (1 2 3 4 2 3)
     `(1 ,@some-list 4 ,@some-list)
          => (1 2 3 4 2 3)

     (setq list '(hack foo bar))
          => (hack foo bar)
     (cons 'use
       (cons 'the
         (cons 'words (append (cdr list) '(as elements)))))
          => (use the words foo bar as elements)
     `(use the words ,@(cdr list) as elements)
          => (use the words foo bar as elements)

     In older versions of Emacs (before XEmacs 19.12 or FSF Emacs
     version 19.29), ``' used a different syntax which required an
     extra level of parentheses around the entire backquote construct.
     Likewise, each `,' or `,@' substitution required an extra level of
     parentheses surrounding both the `,' or `,@' and the following
     expression.  The old syntax required whitespace between the ``',
     `,' or `,@' and the following expression.

     This syntax is still accepted, but no longer recommended except for
     compatibility with old Emacs versions.

