-This is ../info/lispref.info, produced by makeinfo version 4.0 from
+This is ../info/lispref.info, produced by makeinfo version 4.6 from
lispref/lispref.texi.
INFO-DIR-SECTION XEmacs Editor
Foundation instead of in the original English.
\1f
-File: lispref.info, Node: Copying, Next: Introduction, Prev: Top, Up: Top
+File: lispref.info, Node: List Elements, Next: Building Lists, Prev: List-related Predicates, Up: Lists
+
+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.
+
+\1f
+File: lispref.info, Node: Building Lists, Next: Modifying Lists, Prev: List Elements, Up: Lists
+
+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 list
+ This function creates a new list whose elements are the elements of
+ LIST, but in reverse order. The original argument LIST is _not_
+ altered.
+
+ (setq x '(1 2 3 4))
+ => (1 2 3 4)
+ (reverse x)
+ => (4 3 2 1)
+ x
+ => (1 2 3 4)
+
+\1f
+File: lispref.info, Node: Modifying Lists, Next: Sets And Lists, Prev: Building Lists, Up: Lists
+
+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.
+
+\1f
+File: lispref.info, Node: Setcar, Next: Setcdr, Up: Modifying Lists
+
+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----
+ | | |
+ --------------
+
+\1f
+File: lispref.info, Node: Setcdr, Next: Rearrangement, Prev: Setcar, Up: Modifying Lists
+
+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------
+ | | |
+ ---------------
+
+\1f
+File: lispref.info, Node: Rearrangement, Prev: Setcdr, Up: Modifying Lists
+
+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 list
+ This function reverses the order of the elements of LIST. Unlike
+ `reverse', `nreverse' alters its argument by reversing the CDRs in
+ the cons cells forming the list. The cons cell that used to be
+ the last one in LIST 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 list:
+
+ (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 list predicate
+ This function sorts LIST stably, though destructively, and returns
+ the sorted list. 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.
+
+ The argument PREDICATE must be a function that accepts two
+ arguments. It is called with two elements of LIST. 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 destructive aspect of `sort' is that it rearranges the cons
+ cells forming LIST by changing CDRs. A nondestructive sort
+ function would create new cons cells to store the elements in their
+ sorted order. If you wish to make a sorted copy without
+ destroying the original, copy it first with `copy-sequence' and
+ then sort.
+
+ Sorting does not change the CARs of the cons cells in LIST; the
+ cons cell that originally contained the element `a' in LIST still
+ has `a' in its CAR after sorting, but it now appears in a
+ different position in the list 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 list:
+
+ (setq nums (sort nums '<))
+
+ *Note Sorting::, for more functions that perform sorting. See
+ `documentation' in *Note Accessing Documentation::, for a useful
+ example of `sort'.
+
+\1f
+File: lispref.info, Node: Sets And Lists, Next: Association Lists, Prev: Modifying Lists, Up: Lists
+
+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. To form the union of two sets, use `append' (as
+long as you don't mind having duplicate elements). Other useful
+functions for sets include `memq' and `delq', and their `equal'
+versions, `member' and `delete'.
+
+ Common Lisp note: Common Lisp has functions `union' (which avoids
+ duplicate elements) and `intersection' for set operations, but
+ XEmacs Lisp does not have them. You can write them in Lisp if you
+ wish.
+
+ - Function: memq object list
+ This function tests to see whether OBJECT is a member of LIST. If
+ it is, `memq' returns a list starting with the first occurrence of
+ OBJECT. Otherwise, it returns `nil'. The letter `q' in `memq'
+ says that it uses `eq' to compare OBJECT against the elements of
+ the list. For example:
+
+ (memq 'b '(a b c b a))
+ => (b c b a)
+ (memq '(2) '((1) (2))) ; `(2)' and `(2)' are not `eq'.
+ => nil
+
+ - Function: delq object list
+ This function destructively removes all elements `eq' to OBJECT
+ from LIST. The letter `q' in `delq' says that it uses `eq' to
+ compare OBJECT against the elements of the list, like `memq'.
+
+ When `delq' deletes elements from the front of the list, it does so
+simply by advancing down the list and returning a sublist that starts
+after those elements:
+
+ (delq 'a '(a b c)) == (cdr '(a b c))
+
+ When an element to be deleted appears in the middle of the list,
+removing it involves changing the CDRs (*note Setcdr::).
+
+ (setq sample-list '(a b c (4)))
+ => (a b c (4))
+ (delq 'a sample-list)
+ => (b c (4))
+ sample-list
+ => (a b c (4))
+ (delq 'c sample-list)
+ => (a b (4))
+ sample-list
+ => (a b (4))
+
+ Note that `(delq 'c sample-list)' modifies `sample-list' to splice
+out the third element, but `(delq 'a sample-list)' does not splice
+anything--it just returns a shorter list. 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 `delq'
+and use that. Most often we store the result back into the variable
+that held the original list:
+
+ (setq flowers (delq 'rose flowers))
+
+ In the following example, the `(4)' that `delq' attempts to match
+and the `(4)' in the `sample-list' are not `eq':
+
+ (delq '(4) sample-list)
+ => (a c (4))
+
+ The following two functions are like `memq' and `delq' but use
+`equal' rather than `eq' to compare elements. They are new in Emacs 19.
+
+ - Function: member object list
+ The function `member' tests to see whether OBJECT is a member of
+ LIST, comparing members with OBJECT using `equal'. If OBJECT is a
+ member, `member' returns a list starting with its first occurrence
+ in LIST. Otherwise, it returns `nil'.
+
+ Compare this with `memq':
+
+ (member '(2) '((1) (2))) ; `(2)' and `(2)' are `equal'.
+ => ((2))
+ (memq '(2) '((1) (2))) ; `(2)' and `(2)' are not `eq'.
+ => nil
+ ;; Two strings with the same contents are `equal'.
+ (member "foo" '("foo" "bar"))
+ => ("foo" "bar")
+
+ - Function: delete object list
+ This function destructively removes all elements `equal' to OBJECT
+ from LIST. It is to `delq' as `member' is to `memq': it uses
+ `equal' to compare elements with OBJECT, like `member'; when it
+ finds an element that matches, it removes the element just as
+ `delq' would. For example:
+
+ (delete '(2) '((2) (1) (2)))
+ => '((1))
+
+ Common Lisp note: The functions `member' and `delete' in XEmacs
+ Lisp are derived from Maclisp, not Common Lisp. The Common Lisp
+ versions do not use `equal' to compare elements.
+
+ 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.
+
+\1f
+File: lispref.info, Node: Association Lists, Next: Property Lists, Prev: Sets And Lists, Up: Lists
+
+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.
+
+ 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
+ This function returns the first association for KEY in ALIST. It
+ compares KEY against the alist elements using `equal' (*note
+ Equality Predicates::). 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")
+
+ - Function: rassoc value alist
+ This function returns the first association with value VALUE in
+ ALIST. It returns `nil' if no association in ALIST has a CDR
+ `equal' 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.
+
+ - Function: assq key alist
+ This function is like `assoc' in that it returns the first
+ association for KEY in ALIST, but it makes the comparison using
+ `eq' instead of `equal'. `assq' returns `nil' if no association
+ in ALIST has a CAR `eq' to KEY. This function is used more often
+ than `assoc', since `eq' is faster than `equal' and most alists
+ use symbols as keys. *Note Equality Predicates::.
+
+ (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
+ => ((pine . cones) (oak . acorns) (maple . seeds))
+ (assq 'pine trees)
+ => (pine . cones)
+
+ On the other hand, `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: rassq value alist
+ This function returns the first association with value VALUE in
+ ALIST. It returns `nil' if no association in ALIST has a CDR `eq'
+ to VALUE.
+
+ `rassq' is like `assq' except that it compares the CDR of each
+ ALIST association instead of the CAR. You can think of this as
+ "reverse `assq'", finding the key for a given value.
+
+ 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: remassoc key alist
+ This function deletes by side effect any associations with key KEY
+ in ALIST--i.e. it removes any elements from ALIST whose `car' is
+ `equal' to KEY. The modified ALIST is returned.
+
+ If the first member of ALIST has a `car' that is `equal' to KEY,
+ there is no way to remove it by side effect; therefore, write
+ `(setq foo (remassoc key foo))' to be sure of changing the value
+ of `foo'.
+
+ - Function: remassq key alist
+ This function deletes by side effect any associations with key KEY
+ in ALIST--i.e. it removes any elements from ALIST whose `car' is
+ `eq' to KEY. The modified ALIST is returned.
+
+ This function is exactly like `remassoc', but comparisons between
+ KEY and keys in ALIST are done using `eq' instead of `equal'.
+
+ - Function: remrassoc value alist
+ This function deletes by side effect any associations with value
+ VALUE in ALIST--i.e. it removes any elements from ALIST whose
+ `cdr' is `equal' to VALUE. The modified ALIST is returned.
+
+ If the first member of ALIST has a `car' that is `equal' to VALUE,
+ there is no way to remove it by side effect; therefore, write
+ `(setq foo (remassoc value foo))' to be sure of changing the value
+ of `foo'.
+
+ `remrassoc' is like `remassoc' except that it compares the CDR of
+ each ALIST association instead of the CAR. You can think of this
+ as "reverse `remassoc'", removing an association based on its
+ value instead of its key.
+
+ - Function: remrassq value alist
+ This function deletes by side effect any associations with value
+ VALUE in ALIST--i.e. it removes any elements from ALIST whose
+ `cdr' is `eq' to VALUE. The modified ALIST is returned.
+
+ This function is exactly like `remrassoc', but comparisons between
+ VALUE and values in ALIST are done using `eq' instead of `equal'.
+
+ - 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")
+
+ ---------- 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.
+
+\1f
+File: lispref.info, Node: Property Lists, Next: Weak Lists, Prev: Association Lists, Up: Lists
+
+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.
+
+\1f
+File: lispref.info, Node: Working With Normal Plists, Next: Working With Lax Plists, Up: Property Lists
+
+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.
+
+\1f
+File: lispref.info, Node: Working With Lax Plists, Next: Converting Plists To/From Alists, Prev: Working With Normal Plists, Up: Property Lists
+
+Working With Lax Plists
+-----------------------
-GNU GENERAL PUBLIC LICENSE
-**************************
+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.
+
+\1f
+File: lispref.info, Node: Converting Plists To/From Alists, Prev: Working With Lax Plists, Up: Property Lists
+
+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.
+
+\1f
+File: lispref.info, Node: Weak Lists, Prev: Property Lists, Up: Lists
+
+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.
+
+\1f
+File: lispref.info, Node: Sequences Arrays Vectors, Next: Symbols, Prev: Lists, Up: Top
+
+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.
+
+\1f
+File: lispref.info, Node: Sequence Functions, Next: Arrays, Up: Sequences Arrays Vectors
+
+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::).
+
+\1f
+File: lispref.info, Node: Arrays, Next: Array Functions, Prev: Sequence Functions, Up: Sequences Arrays Vectors
+
+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.
+
+\1f
+File: lispref.info, Node: Array Functions, Next: Vectors, Prev: Arrays, Up: Sequences Arrays Vectors
+
+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.
+
+ - Function: fillarray array object
+ This function fills the array ARRAY with OBJECT, so that each
+ element of ARRAY is OBJECT. It returns ARRAY.
+
+ (setq a [a b c d e f g])
+ => [a b c d e f g]
+ (fillarray 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"
+ (fillarray s ?-)
+ => "------------------"
+
+ (setq bv #*1101)
+ => #*1101
+ (fillarray bv 0)
+ => #*0000
+
+ 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::.
+
+\1f
+File: lispref.info, Node: Vectors, Next: Vector Functions, Prev: Array Functions, Up: Sequences Arrays Vectors
+
+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
+
+\1f
+File: lispref.info, Node: Vector Functions, Next: Bit Vectors, Prev: Vectors, Up: Sequences Arrays Vectors
+
+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])
+
+\1f
+File: lispref.info, Node: Bit Vectors, Next: Bit Vector Functions, Prev: Vector Functions, Up: Sequences Arrays Vectors
+
+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::.
+
+\1f
+File: lispref.info, Node: Bit Vector Functions, Prev: Bit Vectors, Up: Sequences Arrays Vectors
+
+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)
+
+\1f
+File: lispref.info, Node: Symbols, Next: Evaluation, Prev: Sequences Arrays Vectors, Up: Top
+
+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::. 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.
+
+\1f
+File: lispref.info, Node: Symbol Components, Next: Definitions, Up: Symbols
+
+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 hashing algorithm and an obarray; see *Note Creating
+Symbols::.)
+
+ 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.
+
+\1f
+File: lispref.info, Node: Definitions, Next: Creating Symbols, Prev: Symbol Components, Up: Symbols
+
+Defining Symbols
+================
+
+A "definition" in Lisp is a special form 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 forms 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::.
+
+ `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::.
+
+\1f
+File: lispref.info, Node: Creating Symbols, Next: Symbol Properties, Prev: Definitions, Up: Symbols
+
+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
+table called an "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. Each element of the
+obarray is a "bucket" which holds all the symbols with a given hash
+code; to look for a given name, it is sufficient to look through all
+the symbols in the bucket for that name's hash code.
+
+ If a symbol with the desired name is found, the reader uses that
+symbol. If the obarray does not contain a symbol with that name, the
+reader makes a new symbol and adds it to the 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 each obarray has just one symbol with any
+particular name. Other like-named symbols may exist, but not in the
+same obarray. Thus, the reader gets the same symbols for the same
+names, as long as you keep reading with the same obarray.
+
+ No obarray contains all symbols; in fact, some symbols are not in any
+obarray. 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, an obarray is actually a vector. Each element of the
+vector is a bucket; its value is either an interned symbol whose name
+hashes to that bucket, or 0 if the bucket is empty. Each interned
+symbol has an internal link (invisible to the user) to the next symbol
+in the bucket. Because these links are invisible, there is no way to
+find all the symbols in an obarray except using `mapatoms' (below).
+The order of symbols in a bucket is not significant.
+
+ In an empty obarray, every element is 0, and you can create an
+obarray with `(make-vector LENGTH 0)'. *This is the only valid way to
+create an obarray.* Prime numbers as lengths tend to result in good
+hashing; lengths one less than a power of two are also good.
+
+ *Do not try to put symbols in an obarray yourself.* This does not
+work--only `intern' can enter a symbol in an obarray properly. *Do not
+try to intern one symbol in two obarrays.* This would garble both
+obarrays, because a symbol has just one slot to hold the following
+symbol in the obarray bucket. The results would be unpredictable.
+
+ It is possible for two different symbols to have the same name in
+different obarrays; these symbols are not `eq' or `equal'. However,
+this normally happens only as part of the abbrev mechanism (*note
+Abbrevs::).
+
+ Common Lisp note: In Common Lisp, a single symbol may be interned
+ in several obarrays.
+
+ 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 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 the obarray 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 obarray
+ This function calls FUNCTION for each symbol in the obarray
+ OBARRAY. It returns `nil'. If OBARRAY is omitted, it defaults to
+ the value of `obarray', the standard obarray 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'.
+
+\1f
+File: lispref.info, Node: Symbol Properties, Prev: Creating Symbols, Up: Symbols
+
+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.
+
+\1f
+File: lispref.info, Node: Plists and Alists, Next: Object Plists, Up: Symbol Properties
+
+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.
+
+\1f
+File: lispref.info, Node: Object Plists, Next: Other Plists, Prev: Plists and Alists, Up: Symbol Properties
+
+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.)
+
+\1f
+File: lispref.info, Node: Other Plists, Prev: Object Plists, Up: Symbol Properties
+
+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
+
+\1f
+File: lispref.info, Node: Evaluation, Next: Control Structures, Prev: Symbols, Up: Top
+
+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).
+
+\1f
+File: lispref.info, Node: Intro Eval, Next: Eval, Up: Evaluation
+
+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::. 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.
+
+\1f
+File: lispref.info, Node: Eval, Next: Forms, Prev: Intro Eval, Up: Evaluation
+
+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
+
+\1f
+File: lispref.info, Node: Forms, Next: Quoting, Prev: Eval, Up: Evaluation
+
+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 Forms:: ``Special forms'' are idiosyncratic primitives,
+ most of them extremely important.
+* Autoloading:: Functions set up to load files
+ containing their real definitions.
+
+\1f
+File: lispref.info, Node: Self-Evaluating Forms, Next: Symbol Forms, Up: Forms
+
+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>
+
+\1f
+File: lispref.info, Node: Symbol Forms, Next: Classifying Lists, Prev: Self-Evaluating Forms, Up: Forms
+
+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.
+
+\1f
+File: lispref.info, Node: Classifying Lists, Next: Function Indirection, Prev: Symbol Forms, Up: Forms
+
+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 form.
+
+ 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.
+
+\1f
+File: lispref.info, Node: Function Indirection, Next: Function Forms, Prev: Classifying Lists, Up: Forms
+
+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 form, 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))
+
+\1f
+File: lispref.info, Node: Function Forms, Next: Macro Forms, Prev: Function Indirection, Up: Forms
+
+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.
+
+\1f
+File: lispref.info, Node: Macro Forms, Next: Special Forms, Prev: Function Forms, Up: Forms
+
+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.
+
+\1f
+File: lispref.info, Node: Special Forms, Next: Autoloading, Prev: Macro Forms, Up: Forms
+
+Special Forms
+-------------
+
+A "special form" is a primitive function specially marked so that its
+arguments are not all evaluated. Most special forms define control
+structures or perform variable bindings--things which functions cannot
+do.
+
+ Each special form 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 forms 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 forms in
+ XEmacs Lisp and Common Lisp. `setq', `if', and `catch' are
+ special forms in both XEmacs Lisp and Common Lisp. `defun' is a
+ special form in XEmacs Lisp, but a macro in Common Lisp.
+ `save-excursion' is a special form in XEmacs Lisp, but doesn't
+ exist in Common Lisp. `throw' is a special form in Common Lisp
+ (because it must be able to throw multiple values), but it is a
+ function in XEmacs Lisp (which doesn't have multiple values).
+
+\1f
+File: lispref.info, Node: Autoloading, Prev: Special Forms, Up: Forms
+
+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::.
+
+\1f
+File: lispref.info, Node: Quoting, Prev: Forms, Up: Evaluation
+
+Quoting
+=======
+
+The special form `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 Form: quote object
+ This special form 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.
+
+\1f
+File: lispref.info, Node: Control Structures, Next: Variables, Prev: Evaluation, Up: Top
+
+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 forms which
+control when, whether, or how many times to execute the forms they
+contain.
+
+ 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 forms since their 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.
+
+\1f
+File: lispref.info, Node: Sequencing, Next: Conditionals, Up: Control Structures
+
+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 Form: progn forms...
+ This special form 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 Form: prog1 form1 forms...
+ This special form 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 Form: prog2 form1 form2 forms...
+ This special form 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"
+
+\1f
+File: lispref.info, Node: Conditionals, Next: Combining Conditions, Prev: Sequencing, Up: Control Structures
+
+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 Form: 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 form 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 Form: 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))
+
+\1f
+File: lispref.info, Node: Combining Conditions, Next: Iteration, Prev: Conditionals, Up: Control Structures
+
+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 Form: and conditions...
+ The `and' special form 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 Form: or conditions...
+ The `or' special form 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.
+
+\1f
+File: lispref.info, Node: Iteration, Next: Nonlocal Exits, Prev: Combining Conditions, Up: Control Structures
+
+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 form `while':
+
+ - Special Form: 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).
+
+\1f
+File: lispref.info, Node: Nonlocal Exits, Prev: Iteration, Up: Control Structures
+
+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.
+
+\1f
+File: lispref.info, Node: Catch and Throw, Next: Examples of Catch, Up: Nonlocal Exits
+
+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 form 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::).
+
+ Common Lisp note: Most other versions of Lisp, including Common
+ Lisp, have several ways of transferring control nonsequentially:
+ `return', `return-from', and `go', for example. XEmacs Lisp has
+ only `throw'.
+
+ - Special Form: 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)'.
+
+\1f
+File: lispref.info, Node: Examples of Catch, Next: Errors, Prev: Catch and Throw, Up: Nonlocal Exits
+
+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.
+
+\1f
+File: lispref.info, Node: Errors, Next: Cleanups, Prev: Examples of Catch, Up: Nonlocal Exits
+
+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:
- Version 2, June 1991
+* 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.
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 675 Mass Ave, Cambridge, MA 02139, USA
+\1f
+File: lispref.info, Node: Signaling Errors, Next: Processing of Errors, Up: Errors
+
+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
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-Preamble
-========
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it in
-new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software,
-and (2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains a
- notice placed by the copyright holder saying it may be distributed
- under the terms of this General Public License. The "Program",
- below, refers to any such program or work, and a "work based on
- the Program" means either the Program or any derivative work under
- copyright law: that is to say, a work containing the Program or a
- portion of it, either verbatim or with modifications and/or
- translated into another language. (Hereinafter, translation is
- included without limitation in the term "modification".) Each
- licensee is addressed as "you".
-
- Activities other than copying, distribution and modification are
- not covered by this License; they are outside its scope. The act
- of running the Program is not restricted, and the output from the
- Program is covered only if its contents constitute a work based on
- the Program (independent of having been made by running the
- Program). Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
- source code as you receive it, in any medium, provided that you
- conspicuously and appropriately publish on each copy an appropriate
- copyright notice and disclaimer of warranty; keep intact all the
- notices that refer to this License and to the absence of any
- warranty; and give any other recipients of the Program a copy of
- this License along with the Program.
-
- You may charge a fee for the physical act of transferring a copy,
- and you may at your option offer warranty protection in exchange
- for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
- of it, thus forming a work based on the Program, and copy and
- distribute such modifications or work under the terms of Section 1
- above, provided that you also meet all of these conditions:
-
- a. You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b. You must cause any work that you distribute or publish, that
- in whole or in part contains or is derived from the Program
- or any part thereof, to be licensed as a whole at no charge
- to all third parties under the terms of this License.
-
- c. If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display
- an announcement including an appropriate copyright notice and
- a notice that there is no warranty (or else, saying that you
- provide a warranty) and that users may redistribute the
- program under these conditions, and telling the user how to
- view a copy of this License. (Exception: if the Program
- itself is interactive but does not normally print such an
- announcement, your work based on the Program is not required
- to print an announcement.)
-
- These requirements apply to the modified work as a whole. If
- identifiable sections of that work are not derived from the
- Program, and can be reasonably considered independent and separate
- works in themselves, then this License, and its terms, do not
- apply to those sections when you distribute them as separate
- works. But when you distribute the same sections as part of a
- whole which is a work based on the Program, the distribution of
- the whole must be on the terms of this License, whose permissions
- for other licensees extend to the entire whole, and thus to each
- and every part regardless of who wrote it.
-
- Thus, it is not the intent of this section to claim rights or
- contest your rights to work written entirely by you; rather, the
- intent is to exercise the right to control the distribution of
- derivative or collective works based on the Program.
-
- In addition, mere aggregation of another work not based on the
- Program with the Program (or with a work based on the Program) on
- a volume of a storage or distribution medium does not bring the
- other work under the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
- under Section 2) in object code or executable form under the terms
- of Sections 1 and 2 above provided that you also do one of the
- following:
-
- a. Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of
- Sections 1 and 2 above on a medium customarily used for
- software interchange; or,
-
- b. Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a
- medium customarily used for software interchange; or,
-
- c. Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with
- such an offer, in accord with Subsection b above.)
-
- The source code for a work means the preferred form of the work for
- making modifications to it. For an executable work, complete
- source code means all the source code for all modules it contains,
- plus any associated interface definition files, plus the scripts
- used to control compilation and installation of the executable.
- However, as a special exception, the source code distributed need
- not include anything that is normally distributed (in either
- source or binary form) with the major components (compiler,
- kernel, and so on) of the operating system on which the executable
- runs, unless that component itself accompanies the executable.
-
- If distribution of executable or object code is made by offering
- access to copy from a designated place, then offering equivalent
- access to copy the source code from the same place counts as
- distribution of the source code, even though third parties are not
- compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
- except as expressly provided under this License. Any attempt
- otherwise to copy, modify, sublicense or distribute the Program is
- void, and will automatically terminate your rights under this
- License. However, parties who have received copies, or rights,
- from you under this License will not have their licenses
- terminated so long as such parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
- signed it. However, nothing else grants you permission to modify
- or distribute the Program or its derivative works. These actions
- are prohibited by law if you do not accept this License.
- Therefore, by modifying or distributing the Program (or any work
- based on the Program), you indicate your acceptance of this
- License to do so, and all its terms and conditions for copying,
- distributing or modifying the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
- Program), the recipient automatically receives a license from the
- original licensor to copy, distribute or modify the Program
- subject to these terms and conditions. You may not impose any
- further restrictions on the recipients' exercise of the rights
- granted herein. You are not responsible for enforcing compliance
- by third parties to this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
- infringement or for any other reason (not limited to patent
- issues), conditions are imposed on you (whether by court order,
- agreement or otherwise) that contradict the conditions of this
- License, they do not excuse you from the conditions of this
- License. If you cannot distribute so as to satisfy simultaneously
- your obligations under this License and any other pertinent
- obligations, then as a consequence you may not distribute the
- Program at all. For example, if a patent license would not permit
- royalty-free redistribution of the Program by all those who
- receive copies directly or indirectly through you, then the only
- way you could satisfy both it and this License would be to refrain
- entirely from distribution of the Program.
-
- If any portion of this section is held invalid or unenforceable
- under any particular circumstance, the balance of the section is
- intended to apply and the section as a whole is intended to apply
- in other circumstances.
-
- It is not the purpose of this section to induce you to infringe any
- patents or other property right claims or to contest validity of
- any such claims; this section has the sole purpose of protecting
- the integrity of the free software distribution system, which is
- implemented by public license practices. Many people have made
- generous contributions to the wide range of software distributed
- through that system in reliance on consistent application of that
- system; it is up to the author/donor to decide if he or she is
- willing to distribute software through any other system and a
- licensee cannot impose that choice.
-
- This section is intended to make thoroughly clear what is believed
- to be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
- certain countries either by patents or by copyrighted interfaces,
- the original copyright holder who places the Program under this
- License may add an explicit geographical distribution limitation
- excluding those countries, so that distribution is permitted only
- in or among countries not thus excluded. In such case, this
- License incorporates the limitation as if written in the body of
- this License.
-
- 9. The Free Software Foundation may publish revised and/or new
- versions of the General Public License from time to time. Such
- new versions will be similar in spirit to the present version, but
- may differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
- Program specifies a version number of this License which applies
- to it and "any later version", you have the option of following
- the terms and conditions either of that version or of any later
- version published by the Free Software Foundation. If the Program
- does not specify a version number of this License, you may choose
- any version ever published by the Free Software Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
- programs whose distribution conditions are different, write to the
- author to ask for permission. For software which is copyrighted
- by the Free Software Foundation, write to the Free Software
- Foundation; we sometimes make exceptions for this. Our decision
- will be guided by the two goals of preserving the free status of
- all derivatives of our free software and of promoting the sharing
- and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
- WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
- LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
- HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
- WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
- NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
- FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
- QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
- PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
- SERVICING, REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
- WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
- MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
- LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
- INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
- INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
- DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
- OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
- OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
- ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
-How to Apply These Terms to Your New Programs
-=============================================
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these
-terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- ONE LINE TO GIVE THE PROGRAM'S NAME AND AN IDEA OF WHAT IT DOES.
- Copyright (C) 19YY NAME OF AUTHOR
+ invalid-argument
+ wrong-type-argument
+ args-out-of-range
+ wrong-number-of-arguments
+ invalid-function
+ no-catch
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
+ invalid-state
+ void-function
+ cyclic-function-indirection
+ void-variable
+ cyclic-variable-indirection
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+ 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)
+ ...)
+
+\1f
+File: lispref.info, Node: Processing of Errors, Next: Handling Errors, Prev: Signaling Errors, Up: Errors
+
+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.
+
+\1f
+File: lispref.info, Node: Handling Errors, Next: Error Symbols, Prev: Processing of Errors, Up: Errors
+
+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 form `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 Form: condition-case var protected-form handlers...
+ This special form 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
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
- Also add information on how to contact you by electronic and paper
-mail.
-
- If the program is interactive, make it output a short notice like
-this when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
- type `show w'. This is free software, and you are welcome
- to redistribute it under certain conditions; type `show c'
- for details.
-
- The hypothetical commands `show w' and `show c' should show the
-appropriate parts of the General Public License. Of course, the
-commands you use may be called something other than `show w' and `show
-c'; they could even be mouse-clicks or menu items--whatever suits your
-program.
-
- You should also get your employer (if you work as a programmer) or
-your school, if any, to sign a "copyright disclaimer" for the program,
-if necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright
- interest in the program `Gnomovision'
- (which makes passes at compilers) written
- by James Hacker.
+ (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
- SIGNATURE OF TY COON, 1 April 1989
- Ty Coon, President of Vice
+ (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
+
+\1f
+File: lispref.info, Node: Error Symbols, Prev: Handling Errors, Up: Errors
+
+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.
+
+\1f
+File: lispref.info, Node: Cleanups, Prev: Errors, Up: Nonlocal Exits
+
+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 Form: 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)))))
+
+\1f
+File: lispref.info, Node: Variables, Next: Functions, Prev: Control Structures, Up: Top
+
+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.
+
+\1f
+File: lispref.info, Node: Global Variables, Next: Constant Variables, Up: Variables
+
+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)
- This General Public License does not permit incorporating your
-program into proprietary programs. If your program is a subroutine
-library, you may consider it more useful to permit linking proprietary
-applications with the library. If this is what you want to do, use the
-GNU Library General Public License instead of this License.
+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
+
+\1f
+File: lispref.info, Node: Constant Variables, Next: Local Variables, Prev: Global Variables, Up: Variables
+
+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
+
+\1f
+File: lispref.info, Node: Local Variables, Next: Void Variables, Prev: Constant Variables, Up: Variables
+
+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 form 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 form 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 forms `let' and `let*' exist to create local bindings.
+
+ - Special Form: let (bindings...) forms...
+ This special form 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 Form: let* (bindings...) forms...
+ This special form 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::).
+
+ * 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::.
+
+\1f
+File: lispref.info, Node: Void Variables, Next: Defining Variables, Prev: Local Variables, Up: Variables
+
+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
+
+\1f
+File: lispref.info, Node: Defining Variables, Next: Accessing Variables, Prev: Void Variables, Up: Variables
+
+Defining Global Variables
+=========================
+
+You may announce your intention to use a symbol as a global variable
+with a "variable definition": a special form, 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 Form: defvar symbol [value [doc-string]]
+ This special form 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 form:
+
+ (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 Form: defconst symbol [value [doc-string]]
+ This special form 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 forms 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.
+
+\1f
+File: lispref.info, Node: Accessing Variables, Next: Setting Variables, Prev: Defining Variables, Up: Variables
+
+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.
\1f
-File: lispref.info, Node: Introduction, Next: Lisp Data Types, Prev: Copying, Up: Top
+File: lispref.info, Node: Setting Variables, Next: Variable Scoping, Prev: Accessing Variables, Up: Variables
+
+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 Form: setq [symbol form]...
+ This special form 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
+ 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.
+
+ 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)))
-Introduction
-************
+\1f
+File: lispref.info, Node: Variable Scoping, Next: Buffer-Local Variables, Prev: Setting Variables, Up: Variables
+
+Scoping Rules for Variable Bindings
+===================================
- Most of the XEmacs text editor is written in the programming
-language called XEmacs Lisp. You can write new code in XEmacs Lisp and
-install it as an extension to the editor. However, XEmacs Lisp is more
-than a mere "extension language"; it is a full computer programming
-language in its own right. You can use it as you would any other
-programming language.
+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.
- Because XEmacs Lisp is designed for use in an editor, it has special
-features for scanning and parsing text as well as features for handling
-files, buffers, displays, subprocesses, and so on. XEmacs Lisp is
-closely integrated with the editing facilities; thus, editing commands
-are functions that can also conveniently be called from Lisp programs,
-and parameters for customization are ordinary Lisp variables.
+ 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.
- This manual describes XEmacs Lisp, presuming considerable familiarity
-with the use of XEmacs for editing. (See `The XEmacs Reference
-Manual', for this basic information.) Generally speaking, the earlier
-chapters describe features of XEmacs Lisp that have counterparts in many
-programming languages, and later chapters describe features that are
-peculiar to XEmacs Lisp or relate specifically to editing.
+ 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.
- This is edition 3.3.
+ Common Lisp note: Variables declared "special" in Common Lisp are
+ dynamically scoped, like variables in XEmacs Lisp.
* Menu:
-* Caveats:: Flaws and a request for help.
-* Lisp History:: XEmacs Lisp is descended from Maclisp.
-* Conventions:: How the manual is formatted.
-* Acknowledgements:: The authors, editors, and sponsors of this manual.
+* 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.
\1f
-File: lispref.info, Node: Caveats, Next: Lisp History, Up: Introduction
+File: lispref.info, Node: Scope, Next: Extent, Up: Variable Scoping
-Caveats
-=======
+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:
- This manual has gone through numerous drafts. It is nearly complete
-but not flawless. There are a few topics that are not covered, either
-because we consider them secondary (such as most of the individual
-modes) or because they are yet to be written. Because we are not able
-to deal with them completely, we have left out several parts
-intentionally.
+ (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:
- The manual should be fully correct in what it does cover, and it is
-therefore open to criticism on anything it says--from specific examples
-and descriptive text, to the ordering of chapters and sections. If
-something is confusing, or you find that you have to look at the sources
-or experiment to learn something not covered in the manual, then perhaps
-the manual should be fixed. Please let us know.
+ * If we call `user' directly without calling `binder' at all, then
+ whatever binding of `x' is found, it cannot come from `binder'.
- As you use this manual, we ask that you send corrections as soon as
-you find them. If you think of a simple, real life example for a
-function or group of functions, please make an effort to write it up
-and send it in. Please reference any comments to the node name and
-function or variable name, as appropriate. Also state the number of
-the edition which you are criticizing.
+ * If we define `foo' as follows and call `binder', then the binding
+ made in `binder' will be seen in `user':
- This manual was originally written for FSF Emacs 19 and was updated
-by Ben Wing (ben@xemacs.org) for Lucid Emacs 19.10 and later for XEmacs
-19.12, 19.13, 19.14, and 20.0. It was further updated by the XEmacs
-Development Team for 19.15 and 20.1. Please send comments and
-corrections relating to XEmacs-specific portions of this manual to
- xemacs@xemacs.org
+ (defun foo (lose)
+ (user))
- or post to the newsgroup
- comp.emacs.xemacs
+ * If we define `foo' as follows and call `binder', then the binding
+ made in `binder' _will not_ be seen in `user':
- --Ben Wing
+ (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'.
\1f
-File: lispref.info, Node: Lisp History, Next: Conventions, Prev: Caveats, Up: Introduction
+File: lispref.info, Node: Extent, Next: Impl of Scope, Prev: Scope, Up: Variable Scoping
+
+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. XEmacs Lisp does not have
+closures.
-Lisp History
-============
+\1f
+File: lispref.info, Node: Impl of Scope, Next: Using Scoping, Prev: Extent, Up: Variable Scoping
+
+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.
+
+\1f
+File: lispref.info, Node: Using Scoping, Prev: Impl of Scope, Up: Variable Scoping
+
+Proper Use of Dynamic Scoping
+-----------------------------
- Lisp (LISt Processing language) was first developed in the late
-1950's at the Massachusetts Institute of Technology for research in
-artificial intelligence. The great power of the Lisp language makes it
-superior for other purposes as well, such as writing editing commands.
+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:
- Dozens of Lisp implementations have been built over the years, each
-with its own idiosyncrasies. Many of them were inspired by Maclisp,
-which was written in the 1960's at MIT's Project MAC. Eventually the
-implementors of the descendants of Maclisp came together and developed a
-standard for Lisp systems, called Common Lisp.
+ * 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.
- XEmacs Lisp is largely inspired by Maclisp, and a little by Common
-Lisp. If you know Common Lisp, you will notice many similarities.
-However, many of the features of Common Lisp have been omitted or
-simplified in order to reduce the memory requirements of XEmacs.
-Sometimes the simplifications are so drastic that a Common Lisp user
-might be very confused. We will occasionally point out how XEmacs Lisp
-differs from Common Lisp. If you don't know Common Lisp, don't worry
-about it; this manual is self-contained.
+ 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'.
\1f
-File: lispref.info, Node: Conventions, Next: Acknowledgements, Prev: Lisp History, Up: Introduction
+File: lispref.info, Node: Buffer-Local Variables, Next: Variable Aliases, Prev: Variable Scoping, Up: Variables
-Conventions
-===========
+Buffer-Local Variables
+======================
- This section explains the notational conventions that are used in
-this manual. You may want to skip this section and refer back to it
-later.
+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:
-* Some Terms:: Explanation of terms we use in this manual.
-* nil and t:: How the symbols `nil' and `t' are used.
-* Evaluation Notation:: The format we use for examples of evaluation.
-* Printing Notation:: The format we use for examples that print output.
-* Error Messages:: The format we use for examples of errors.
-* Buffer Text Notation:: The format we use for buffer contents in examples.
-* Format of Descriptions:: Notation for describing functions, variables, etc.
+* 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.
+
+\1f
+File: lispref.info, Node: Intro to Buffer-Local, Next: Creating Buffer-Local, Up: Buffer-Local Variables
+
+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::.
+
+\1f
+File: lispref.info, Node: Creating Buffer-Local, Next: Default Value, Prev: Intro to Buffer-Local, Up: Buffer-Local Variables
+
+Creating and Deleting Buffer-Local Bindings
+-------------------------------------------
+
+ - 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.
\1f
-File: lispref.info, Node: Some Terms, Next: nil and t, Up: Conventions
+File: lispref.info, Node: Default Value, Prev: Creating Buffer-Local, Up: Buffer-Local Variables
+
+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 forms `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 Form: 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
-Some Terms
-----------
+\1f
+File: lispref.info, Node: Variable Aliases, Prev: Buffer-Local Variables, Up: Variables
- Throughout this manual, the phrases "the Lisp reader" and "the Lisp
-printer" are used to refer to those routines in Lisp that convert
-textual representations of Lisp objects into actual Lisp objects, and
-vice versa. *Note Printed Representation::, for more details. You, the
-person reading this manual, are thought of as "the programmer" and are
-addressed as "you". "The user" is the person who uses Lisp programs,
-including those you write.
+Variable Aliases
+================
- Examples of Lisp code appear in this font or form: `(list 1 2 3)'.
-Names that represent arguments or metasyntactic variables appear in
-this font or form: FIRST-NUMBER.
+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.
\1f
-File: lispref.info, Node: nil and t, Next: Evaluation Notation, Prev: Some Terms, Up: Conventions
+File: lispref.info, Node: Functions, Next: Macros, Prev: Variables, Up: Top
-`nil' and `t'
--------------
+Functions
+*********
- In Lisp, the symbol `nil' has three separate meanings: it is a
-symbol with the name `nil'; it is the logical truth value FALSE; and it
-is the empty list--the list of zero elements. When used as a variable,
-`nil' always has the value `nil'.
-
- As far as the Lisp reader is concerned, `()' and `nil' are
-identical: they stand for the same object, the symbol `nil'. The
-different ways of writing the symbol are intended entirely for human
-readers. After the Lisp reader has read either `()' or `nil', there is
-no way to determine which representation was actually written by the
-programmer.
-
- In this manual, we use `()' when we wish to emphasize that it means
-the empty list, and we use `nil' when we wish to emphasize that it
-means the truth value FALSE. That is a good convention to use in Lisp
-programs also.
-
- (cons 'foo ()) ; Emphasize the empty list
- (not nil) ; Emphasize the truth value FALSE
-
- In contexts where a truth value is expected, any non-`nil' value is
-considered to be TRUE. However, `t' is the preferred way to represent
-the truth value TRUE. When you need to choose a value which represents
-TRUE, and there is no other basis for choosing, use `t'. The symbol
-`t' always has value `t'.
-
- In XEmacs Lisp, `nil' and `t' are special symbols that always
-evaluate to themselves. This is so that you do not need to quote them
-to use them as constants in a program. An attempt to change their
-values results in a `setting-constant' error. *Note Accessing
-Variables::.
+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.
\1f
-File: lispref.info, Node: Evaluation Notation, Next: Printing Notation, Prev: nil and t, Up: Conventions
+File: lispref.info, Node: What Is a Function, Next: Lambda Expressions, Up: Functions
+
+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 forms and
+ macros are not functions.
+
+"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 forms 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 form"
+ A "special form" 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 forms 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 forms can do.
+ *Note Macros::, for how to define and use macros.
+
+"command"
+ A "command" is an object that `command-execute' can invoke; it is
+ a possible definition for a key sequence. Some functions are
+ commands; a function written in Lisp is a command if it contains an
+ interactive declaration (*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. *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.
+
+"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
-Evaluation Notation
--------------------
+\1f
+File: lispref.info, Node: Lambda Expressions, Next: Function Names, Prev: What Is a Function, Up: Functions
- A Lisp expression that you can evaluate is called a "form".
-Evaluating a form always produces a result, which is a Lisp object. In
-the examples in this manual, this is indicated with `=>':
+Lambda Expressions
+==================
- (car '(1 2))
- => 1
+A function written in Lisp is a list that looks like this:
-You can read this as "`(car '(1 2))' evaluates to 1".
+ (lambda (ARG-VARIABLES...)
+ [DOCUMENTATION-STRING]
+ [INTERACTIVE-DECLARATION]
+ BODY-FORMS...)
- When a form is a macro call, it expands into a new form for Lisp to
-evaluate. We show the result of the expansion with `==>'. We may or
-may not show the actual result of the evaluation of the expanded form.
+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.
- (news-cadr '(a b c))
- ==> (car (cdr '(a b c)))
- => b
+* Menu:
- Sometimes to help describe one form we show another form that
-produces identical results. The exact equivalence of two forms is
-indicated with `=='.
+* 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.
- (cons 'a nil) == (list 'a)
+\1f
+File: lispref.info, Node: Lambda Components, Next: Simple Lambda, Up: Lambda Expressions
+
+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.
\1f
-File: lispref.info, Node: Printing Notation, Next: Error Messages, Prev: Evaluation Notation, Up: Conventions
+File: lispref.info, Node: Simple Lambda, Next: Argument List, Prev: Lambda Components, Up: Lambda Expressions
-Printing Notation
------------------
+A Simple Lambda-Expression Example
+----------------------------------
- Many of the examples in this manual print text when they are
-evaluated. If you execute example code in a Lisp Interaction buffer
-(such as the buffer `*scratch*'), the printed text is inserted into the
-buffer. If you execute the example by other means (such as by
-evaluating the function `eval-region'), the printed text is displayed
-in the echo area. You should be aware that text displayed in the echo
-area is truncated to a single line.
+Consider for example the following function:
- Examples in this manual indicate printed text with `-|',
-irrespective of where that text goes. The value returned by evaluating
-the form (here `bar') follows on a separate line.
+ (lambda (a b c) (+ a b c))
- (progn (print 'foo) (print 'bar))
- -| foo
- -| bar
- => bar
+We can call this function by writing it as the CAR of an expression,
+like this:
-\1f
-File: lispref.info, Node: Error Messages, Next: Buffer Text Notation, Prev: Printing Notation, Up: Conventions
+ ((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))
-Error Messages
---------------
+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.
- Some examples signal errors. This normally displays an error message
-in the echo area. We show the error message on a line starting with
-`error-->'. Note that `error-->' itself does not appear in the echo
-area.
+ 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 form `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::).
- (+ 23 'x)
- error--> Wrong type argument: integer-or-marker-p, x
+ However, calls to explicit lambda expressions were very useful in the
+old days of Lisp, before the special form `let' was invented. At that
+time, they were the only way to bind and initialize local variables.
\1f
-File: lispref.info, Node: Buffer Text Notation, Next: Format of Descriptions, Prev: Error Messages, Up: Conventions
+File: lispref.info, Node: Argument List, Next: Function Documentation, Prev: Simple Lambda, Up: Lambda Expressions
+
+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 `substring' accepts
+three arguments--a string, the start index and the end index--but the
+third argument defaults to the LENGTH of the string 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
+`substring' does; `nil' as the third argument to `substring' means to
+use the length of the string supplied.
+
+ Common Lisp note: Common Lisp allows the function to specify what
+ default value to use when an optional argument is omitted; XEmacs
+ Lisp always uses `nil'.
+
+ 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
-Buffer Text Notation
---------------------
+\1f
+File: lispref.info, Node: Function Documentation, Prev: Argument List, Up: Lambda Expressions
+
+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.
- Some examples show modifications to text in a buffer, with "before"
-and "after" versions of the text. These examples show the contents of
-the buffer in question between two lines of dashes containing the buffer
-name. In addition, `-!-' indicates the location of point. (The symbol
-for point, of course, is not part of the text in the buffer; it
-indicates the place _between_ two characters where point is located.)
+\1f
+File: lispref.info, Node: Function Names, Next: Defining Functions, Prev: Lambda Expressions, Up: Functions
- ---------- Buffer: foo ----------
- This is the -!-contents of foo.
- ---------- Buffer: foo ----------
-
- (insert "changed ")
- => nil
- ---------- Buffer: foo ----------
- This is the changed -!-contents of foo.
- ---------- Buffer: foo ----------
+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.
+
+\1f
+File: lispref.info, Node: Defining Functions, Next: Calling Functions, Prev: Function Names, Up: Functions
+
+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
+form.
+
+ - Special Form: 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 special forms 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::.
\1f
-File: lispref.info, Node: Format of Descriptions, Prev: Buffer Text Notation, Up: Conventions
+File: lispref.info, Node: Calling Functions, Next: Mapping Functions, Prev: Defining Functions, Up: Functions
-Format of Descriptions
-----------------------
+Calling Functions
+=================
- Functions, variables, macros, commands, user options, and special
-forms are described in this manual in a uniform format. The first line
-of a description contains the name of the item followed by its
-arguments, if any. The category--function, variable, or
-whatever--appears at the beginning of the line. The description
-follows on succeeding lines, sometimes with examples.
+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 forms 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 forms 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'.
-* Menu:
+\1f
+File: lispref.info, Node: Mapping Functions, Next: Anonymous Functions, Prev: Calling Functions, Up: Functions
+
+Mapping Functions
+=================
-* A Sample Function Description:: A description of an imaginary
- function, `foo'.
-* A Sample Variable Description:: A description of an imaginary
- variable,
- `electric-future-map'.
+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"
\1f
-File: lispref.info, Node: A Sample Function Description, Next: A Sample Variable Description, Up: Format of Descriptions
+File: lispref.info, Node: Anonymous Functions, Next: Function Cells, Prev: Mapping Functions, Up: Functions
-A Sample Function Description
-.............................
+Anonymous Functions
+===================
- In a function description, the name of the function being described
-appears first. It is followed on the same line by a list of parameters.
-The names used for the parameters are also used in the body of the
-description.
+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.
- The appearance of the keyword `&optional' in the parameter list
-indicates that the arguments for subsequent parameters may be omitted
-(omitted parameters default to `nil'). Do not write `&optional' when
-you call the function.
+ Any method of creating such a list makes a valid function. Even
+this:
- The keyword `&rest' (which will always be followed by a single
-parameter) indicates that any number of arguments can follow. The value
-of the single following parameter will be a list of all these arguments.
-Do not write `&rest' when you call the function.
+ (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
+ => (lambda (x) (+ 12 x))
- Here is a description of an imaginary function `foo':
+This computes a list that looks like `(lambda (x) (+ 12 x))' and makes
+it the value (_not_ the function definition!) of `silly'.
- - Function: foo integer1 &optional integer2 &rest integers
- The function `foo' subtracts INTEGER1 from INTEGER2, then adds all
- the rest of the arguments to the result. If INTEGER2 is not
- supplied, then the number 19 is used by default.
+ Here is how we might call this function:
- (foo 1 5 3 9)
- => 16
- (foo 5)
- => 14
+ (funcall silly 1)
+ => 13
- More generally,
+(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.)
- (foo W X Y...)
- ==
- (+ (- X W) Y...)
-
- Any parameter whose name contains the name of a type (e.g., INTEGER,
-INTEGER1 or BUFFER) is expected to be of that type. A plural of a type
-(such as BUFFERS) often means a list of objects of that type.
-Parameters named OBJECT may be of any type. (*Note Lisp Data Types::,
-for a list of XEmacs object types.) Parameters with other sorts of
-names (e.g., NEW-FILE) are discussed specifically in the description of
-the function. In some sections, features common to parameters of
-several functions are described at the beginning.
-
- *Note Lambda Expressions::, for a more complete description of
-optional and rest arguments.
-
- Command, macro, and special form descriptions have the same format,
-but the word `Function' is replaced by `Command', `Macro', or `Special
-Form', respectively. Commands are simply functions that may be called
-interactively; macros process their arguments differently from functions
-(the arguments are not evaluated), but are presented the same way.
-
- Special form descriptions use a more complex notation to specify
-optional and repeated parameters because they can break the argument
-list down into separate arguments in more complicated ways.
-``[OPTIONAL-ARG]'' means that OPTIONAL-ARG is optional and
-`REPEATED-ARGS...' stands for zero or more arguments. Parentheses are
-used when several arguments are grouped into additional levels of list
-structure. Here is an example:
-
- - Special Form: count-loop (VAR [FROM TO [INC]]) BODY...
- This imaginary special form implements a loop that executes the
- BODY forms and then increments the variable VAR on each iteration.
- On the first iteration, the variable has the value FROM; on
- subsequent iterations, it is incremented by 1 (or by INC if that
- is given). The loop exits before executing BODY if VAR equals TO.
- Here is an example:
-
- (count-loop (i 0 10)
- (prin1 i) (princ " ")
- (prin1 (aref vector i)) (terpri))
-
- If FROM and TO are omitted, then VAR is bound to `nil' before the
- loop begins, and the loop exits if VAR is non-`nil' at the
- beginning of an iteration. Here is an example:
-
- (count-loop (done)
- (if (pending)
- (fixit)
- (setq done t)))
-
- In this special form, the arguments FROM and TO are optional, but
- must both be present or both absent. If they are present, INC may
- optionally be specified as well. These arguments are grouped with
- the argument VAR into a list, to distinguish them from BODY, which
- includes all remaining elements of the form.
-
-\1f
-File: lispref.info, Node: A Sample Variable Description, Prev: A Sample Function Description, Up: Format of Descriptions
-
-A Sample Variable Description
-.............................
+ 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:
- A "variable" is a name that can hold a value. Although any variable
-can be set by the user, certain variables that exist specifically so
-that users can change them are called "user options". Ordinary
-variables and user options are described using a format like that for
-functions except that there are no arguments.
+ (defun double-each (list)
+ (mapcar '(lambda (x) (* 2 x)) list))
+ => double-each
+ (double-each '(2 11))
+ => (4 22)
- Here is a description of the imaginary `electric-future-map'
-variable.
+In such cases, we usually use the special form `function' instead of
+simple quotation to quote the anonymous function.
+
+ - Special Form: function function-object
+ This special form 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.
- - Variable: electric-future-map
- The value of this variable is a full keymap used by Electric
- Command Future mode. The functions in this map allow you to edit
- commands you have not yet thought about executing.
+ (function SYMBOL) == (quote SYMBOL) == 'SYMBOL
- User option descriptions have the same format, but `Variable' is
-replaced by `User Option'.
+ See `documentation' in *Note Accessing Documentation::, for a
+realistic example using `function' and an anonymous function.
\1f
-File: lispref.info, Node: Acknowledgements, Prev: Conventions, Up: Introduction
+File: lispref.info, Node: Function Cells, Next: Inline Functions, Prev: Anonymous Functions, Up: Functions
+
+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.
-Acknowledgements
+\1f
+File: lispref.info, Node: Inline Functions, Next: Related Topics, Prev: Function Cells, Up: Functions
+
+Inline Functions
================
- This manual was based on the GNU Emacs Lisp Reference Manual, version
-2.4, written by Robert Krawitz, Bil Lewis, Dan LaLiberte, Richard M.
-Stallman and Chris Welty, the volunteers of the GNU manual group, in an
-effort extending over several years. Robert J. Chassell helped to
-review and edit the manual, with the support of the Defense Advanced
-Research Projects Agency, ARPA Order 6082, arranged by Warren A. Hunt,
-Jr. of Computational Logic, Inc.
-
- Ben Wing adapted this manual for XEmacs 19.14 and 20.0, and earlier
-for Lucid Emacs 19.10, XEmacs 19.12, and XEmacs 19.13. He is the sole
-author of many of the manual sections, in particular the XEmacs-specific
-sections: events, faces, extents, glyphs, specifiers, toolbar, menubars,
-scrollbars, dialog boxes, devices, consoles, hash tables, range tables,
-char tables, databases, and others. The section on annotations was
-originally written by Chuck Thompson. Corrections to v3.1 and later
-were done by Martin Buchholz, Steve Baur, and Hrvoje Niksic.
-
- Corrections to the original GNU Emacs Lisp Reference Manual were
-supplied by Karl Berry, Jim Blandy, Bard Bloom, Stephane Boucher, David
-Boyes, Alan Carroll, Richard Davis, Lawrence R. Dodd, Peter Doornbosch,
-David A. Duff, Chris Eich, Beverly Erlebacher, David Eckelkamp, Ralf
-Fassel, Eirik Fuller, Stephen Gildea, Bob Glickstein, Eric Hanchrow,
-George Hartzell, Nathan Hess, Masayuki Ida, Dan Jacobson, Jak Kirman,
-Bob Knighten, Frederick M. Korz, Joe Lammens, Glenn M. Lewis, K. Richard
-Magill, Brian Marick, Roland McGrath, Skip Montanaro, John Gardiner
-Myers, Thomas A. Peterson, Francesco Potorti, Friedrich Pukelsheim,
-Arnold D. Robbins, Raul Rockwell, Per Starback, Shinichirou Sugou, Kimmo
-Suominen, Edward Tharp, Bill Trost, Rickard Westman, Jean White, Matthew
-Wilding, Carl Witty, Dale Worley, Rusty Wright, and David D. Zuhn.
-
-\1f
-File: lispref.info, Node: Lisp Data Types, Next: Numbers, Prev: Introduction, Up: Top
-
-Lisp Data Types
-***************
-
- A Lisp "object" is a piece of data used and manipulated by Lisp
-programs. For our purposes, a "type" or "data type" is a set of
-possible objects.
-
- Every object belongs to at least one type. Objects of the same type
-have similar structures and may usually be used in the same contexts.
-Types can overlap, and objects can belong to two or more types.
-Consequently, we can ask whether an object belongs to a particular type,
-but not for "the" type of an object.
-
- A few fundamental object types are built into XEmacs. These, from
-which all other types are constructed, are called "primitive types".
-Each object belongs to one and only one primitive type. These types
-include "integer", "character" (starting with XEmacs 20.0), "float",
-"cons", "symbol", "string", "vector", "bit-vector", "subr",
-"compiled-function", "hash-table", "range-table", "char-table",
-"weak-list", and several special types, such as "buffer", that are
-related to editing. (*Note Editing Types::.)
-
- Each primitive type has a corresponding Lisp function that checks
-whether an object is a member of that type.
-
- Note that Lisp is unlike many other languages in that Lisp objects
-are "self-typing": the primitive type of the object is implicit in the
-object itself. For example, if an object is a vector, nothing can treat
-it as a number; Lisp knows it is a vector, not a number.
-
- In most languages, the programmer must declare the data type of each
-variable, and the type is known by the compiler but not represented in
-the data. Such type declarations do not exist in XEmacs Lisp. A Lisp
-variable can have any type of value, and it remembers whatever value
-you store in it, type and all.
-
- This chapter describes the purpose, printed representation, and read
-syntax of each of the standard types in Emacs Lisp. Details on how to
-use these types can be found in later chapters.
+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.
+
+\1f
+File: lispref.info, Node: Related Topics, Prev: Inline Functions, Up: Functions
+
+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::.
+
+\1f
+File: lispref.info, Node: Macros, Next: Loading, Prev: Functions, Up: Top
+
+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:
-* Printed Representation:: How Lisp objects are represented as text.
-* Comments:: Comments and their formatting conventions.
-* Primitive Types:: List of all primitive types in XEmacs.
-* Programming Types:: Types found in all Lisp systems.
-* Editing Types:: Types specific to XEmacs.
-* Window-System Types:: Types specific to windowing systems.
-* Type Predicates:: Tests related to types.
-* Equality Predicates:: Tests of equality between any two objects.
+* 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.
\1f
-File: lispref.info, Node: Printed Representation, Next: Comments, Up: Lisp Data Types
+File: lispref.info, Node: Simple Macro, Next: Expansion, Up: Macros
-Printed Representation and Read Syntax
-======================================
+A Simple Example of a Macro
+===========================
- The "printed representation" of an object is the format of the
-output generated by the Lisp printer (the function `prin1') for that
-object. The "read syntax" of an object is the format of the input
-accepted by the Lisp reader (the function `read') for that object.
-Most objects have more than one possible read syntax. Some types of
-object have no read syntax; except for these cases, the printed
-representation of an object is also a read syntax for it.
-
- In other languages, an expression is text; it has no other form. In
-Lisp, an expression is primarily a Lisp object and only secondarily the
-text that is the object's read syntax. Often there is no need to
-emphasize this distinction, but you must keep it in the back of your
-mind, or you will occasionally be very confused.
-
- Every type has a printed representation. Some types have no read
-syntax, since it may not make sense to enter objects of these types
-directly in a Lisp program. For example, the buffer type does not have
-a read syntax. Objects of these types are printed in "hash notation":
-the characters `#<' followed by a descriptive string (typically the
-type name followed by the name of the object), and closed with a
-matching `>'. Hash notation cannot be read at all, so the Lisp reader
-signals the error `invalid-read-syntax' whenever it encounters `#<'.
-
- (current-buffer)
- => #<buffer "objects.texi">
-
- When you evaluate an expression interactively, the Lisp interpreter
-first reads the textual representation of it, producing a Lisp object,
-and then evaluates that object (*note Evaluation::). However,
-evaluation and reading are separate activities. Reading returns the
-Lisp object represented by the text that is read; the object may or may
-not be evaluated later. *Note Input Functions::, for a description of
-`read', the basic function for reading objects.
-
-\1f
-File: lispref.info, Node: Comments, Next: Primitive Types, Prev: Printed Representation, Up: Lisp Data Types
-
-Comments
-========
-
- A "comment" is text that is written in a program only for the sake
-of humans that read the program, and that has no effect on the meaning
-of the program. In Lisp, a semicolon (`;') starts a comment if it is
-not within a string or character constant. The comment continues to
-the end of line. The Lisp reader discards comments; they do not become
-part of the Lisp objects which represent the program within the Lisp
-system.
-
- The `#@COUNT' construct, which skips the next COUNT characters, is
-useful for program-generated comments containing binary data. The
-XEmacs Lisp byte compiler uses this in its output files (*note Byte
-Compilation::). It isn't meant for source files, however.
-
- *Note Comment Tips::, for conventions for formatting comments.
-
-\1f
-File: lispref.info, Node: Primitive Types, Next: Programming Types, Prev: Comments, Up: Lisp Data Types
-
-Primitive Types
-===============
+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)))
- For reference, here is a list of all the primitive types that may
-exist in XEmacs. Note that some of these types may not exist in some
-XEmacs executables; that depends on the options that XEmacs was
-configured with.
+ 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'.
- * bit-vector
+\1f
+File: lispref.info, Node: Expansion, Next: Compiling Macros, Prev: Simple Macro, Up: Macros
+
+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'.
+
+ - 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.
+
+ (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.
- * buffer
+\1f
+File: lispref.info, Node: Compiling Macros, Next: Defining Macros, Prev: Expansion, Up: Macros
+
+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::).
- * char-table
+\1f
+File: lispref.info, Node: Defining Macros, Next: Backquote, Prev: Compiling Macros, Up: Macros
- * character
+Defining Macros
+===============
- * charset
+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.
- * coding-system
+ It is possible to use an anonymous Lisp macro just like an anonymous
+function, but this is never done, because it does not make sense to pass
+an anonymous macro to functionals such as `mapcar'. In practice, all
+Lisp macros have names, and they are usually defined with the special
+form `defmacro'.
- * cons
+ - Special Form: defmacro name argument-list body-forms...
+ `defmacro' defines the symbol NAME as a macro that looks like this:
- * color-instance
+ (macro lambda ARGUMENT-LIST . BODY-FORMS)
- * compiled-function
+ 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.
- * console
+ 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.
- * database
+\1f
+File: lispref.info, Node: Backquote, Next: Problems with Macros, Prev: Defining Macros, Up: Macros
+
+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 form `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.
- * device
+\1f
+File: lispref.info, Node: Problems with Macros, Prev: Backquote, Up: Macros
- * event
+Common Problems Using Macros
+============================
- * extent
+The basic facts of macro expansion have counterintuitive consequences.
+This section describes some important consequences that can lead to
+trouble, and rules to follow to avoid trouble.
- * face
+* Menu:
- * float
+* Argument Evaluation:: The expansion should evaluate each macro arg once.
+* Surprising Local Vars:: Local variable bindings in the expansion
+ require special care.
+* Eval During Expansion:: Don't evaluate them; put them in the expansion.
+* Repeated Expansion:: Avoid depending on how many times expansion is done.
- * font-instance
+\1f
+File: lispref.info, Node: Argument Evaluation, Next: Surprising Local Vars, Up: Problems with Macros
+
+Evaluating Macro Arguments Repeatedly
+-------------------------------------
+
+When defining a macro you must pay attention to the number of times the
+arguments will be evaluated when the expansion is executed. The
+following macro (used to facilitate iteration) illustrates the problem.
+This macro allows us to write a simple "for" loop such as one might
+find in Pascal.
+
+ (defmacro for (var from init to final do &rest body)
+ "Execute a simple \"for\" loop.
+ For example, (for i from 1 to 10 do (print i))."
+ (list 'let (list (list var init))
+ (cons 'while (cons (list '<= var final)
+ (append body (list (list 'inc var)))))))
+ => for
+
+ (for i from 1 to 3 do
+ (setq square (* i i))
+ (princ (format "\n%d %d" i square)))
+ ==>
+ (let ((i 1))
+ (while (<= i 3)
+ (setq square (* i i))
+ (princ (format "%d %d" i square))
+ (inc i)))
+
+ -|1 1
+ -|2 4
+ -|3 9
+ => nil
+
+(The arguments `from', `to', and `do' in this macro are "syntactic
+sugar"; they are entirely ignored. The idea is that you will write
+noise words (such as `from', `to', and `do') in those positions in the
+macro call.)
+
+ Here's an equivalent definition simplified through use of backquote:
+
+ (defmacro for (var from init to final do &rest body)
+ "Execute a simple \"for\" loop.
+ For example, (for i from 1 to 10 do (print i))."
+ `(let ((,var ,init))
+ (while (<= ,var ,final)
+ ,@body
+ (inc ,var))))
+
+ Both forms of this definition (with backquote and without) suffer
+from the defect that FINAL is evaluated on every iteration. If FINAL
+is a constant, this is not a problem. If it is a more complex form,
+say `(long-complex-calculation x)', this can slow down the execution
+significantly. If FINAL has side effects, executing it more than once
+is probably incorrect.
+
+ A well-designed macro definition takes steps to avoid this problem by
+producing an expansion that evaluates the argument expressions exactly
+once unless repeated evaluation is part of the intended purpose of the
+macro. Here is a correct expansion for the `for' macro:
+
+ (let ((i 1)
+ (max 3))
+ (while (<= i max)
+ (setq square (* i i))
+ (princ (format "%d %d" i square))
+ (inc i)))
+
+ Here is a macro definition that creates this expansion:
+
+ (defmacro for (var from init to final do &rest body)
+ "Execute a simple for loop: (for i from 1 to 10 do (print i))."
+ `(let ((,var ,init)
+ (max ,final))
+ (while (<= ,var max)
+ ,@body
+ (inc ,var))))
+
+ Unfortunately, this introduces another problem. Proceed to the
+following node.
- * frame
+\1f
+File: lispref.info, Node: Surprising Local Vars, Next: Eval During Expansion, Prev: Argument Evaluation, Up: Problems with Macros
+
+Local Variables in Macro Expansions
+-----------------------------------
+
+In the previous section, the definition of `for' was fixed as follows
+to make the expansion evaluate the macro arguments the proper number of
+times:
+
+ (defmacro for (var from init to final do &rest body)
+ "Execute a simple for loop: (for i from 1 to 10 do (print i))."
+ `(let ((,var ,init)
+ (max ,final))
+ (while (<= ,var max)
+ ,@body
+ (inc ,var))))
+
+The new definition of `for' has a new problem: it introduces a local
+variable named `max' which the user does not expect. This causes
+trouble in examples such as the following:
+
+ (let ((max 0))
+ (for x from 0 to 10 do
+ (let ((this (frob x)))
+ (if (< max this)
+ (setq max this)))))
+
+The references to `max' inside the body of the `for', which are
+supposed to refer to the user's binding of `max', really access the
+binding made by `for'.
+
+ The way to correct this is to use an uninterned symbol instead of
+`max' (*note Creating Symbols::). The uninterned symbol can be bound
+and referred to just like any other symbol, but since it is created by
+`for', we know that it cannot already appear in the user's program.
+Since it is not interned, there is no way the user can put it into the
+program later. It will never appear anywhere except where put by
+`for'. Here is a definition of `for' that works this way:
+
+ (defmacro for (var from init to final do &rest body)
+ "Execute a simple for loop: (for i from 1 to 10 do (print i))."
+ (let ((tempvar (make-symbol "max")))
+ `(let ((,var ,init)
+ (,tempvar ,final))
+ (while (<= ,var ,tempvar)
+ ,@body
+ (inc ,var)))))
+
+This creates an uninterned symbol named `max' and puts it in the
+expansion instead of the usual interned symbol `max' that appears in
+expressions ordinarily.
- * glyph
+\1f
+File: lispref.info, Node: Eval During Expansion, Next: Repeated Expansion, Prev: Surprising Local Vars, Up: Problems with Macros
+
+Evaluating Macro Arguments in Expansion
+---------------------------------------
+
+Another problem can happen if you evaluate any of the macro argument
+expressions during the computation of the expansion, such as by calling
+`eval' (*note Eval::). If the argument is supposed to refer to the
+user's variables, you may have trouble if the user happens to use a
+variable with the same name as one of the macro arguments. Inside the
+macro body, the macro argument binding is the most local binding of this
+variable, so any references inside the form being evaluated do refer to
+it. Here is an example:
+
+ (defmacro foo (a)
+ (list 'setq (eval a) t))
+ => foo
+ (setq x 'b)
+ (foo x) ==> (setq b t)
+ => t ; and `b' has been set.
+ ;; but
+ (setq a 'c)
+ (foo a) ==> (setq a t)
+ => t ; but this set `a', not `c'.
+
+ It makes a difference whether the user's variable is named `a' or
+`x', because `a' conflicts with the macro argument variable `a'.
+
+ Another reason not to call `eval' in a macro definition is that it
+probably won't do what you intend in a compiled program. The
+byte-compiler runs macro definitions while compiling the program, when
+the program's own computations (which you might have wished to access
+with `eval') don't occur and its local variable bindings don't exist.
+
+ The safe way to work with the run-time value of an expression is to
+put the expression into the macro expansion, so that its value is
+computed as part of executing the expansion.
- * hash-table
+\1f
+File: lispref.info, Node: Repeated Expansion, Prev: Eval During Expansion, Up: Problems with Macros
+
+How Many Times is the Macro Expanded?
+-------------------------------------
+
+Occasionally problems result from the fact that a macro call is
+expanded each time it is evaluated in an interpreted function, but is
+expanded only once (during compilation) for a compiled function. If the
+macro definition has side effects, they will work differently depending
+on how many times the macro is expanded.
+
+ In particular, constructing objects is a kind of side effect. If the
+macro is called once, then the objects are constructed only once. In
+other words, the same structure of objects is used each time the macro
+call is executed. In interpreted operation, the macro is reexpanded
+each time, producing a fresh collection of objects each time. Usually
+this does not matter--the objects have the same contents whether they
+are shared or not. But if the surrounding program does side effects on
+the objects, it makes a difference whether they are shared. Here is an
+example:
+
+ (defmacro empty-object ()
+ (list 'quote (cons nil nil)))
+
+ (defun initialize (condition)
+ (let ((object (empty-object)))
+ (if condition
+ (setcar object condition))
+ object))
+
+If `initialize' is interpreted, a new list `(nil)' is constructed each
+time `initialize' is called. Thus, no side effect survives between
+calls. If `initialize' is compiled, then the macro `empty-object' is
+expanded during compilation, producing a single "constant" `(nil)' that
+is reused and altered each time `initialize' is called.
+
+ One way to avoid pathological cases like this is to think of
+`empty-object' as a funny kind of constant, not as a memory allocation
+construct. You wouldn't use `setcar' on a constant such as `'(nil)',
+so naturally you won't use it on `(empty-object)' either.
- * image-instance
+\1f
+File: lispref.info, Node: Customization, Up: Top
- * integer
+Writing Customization Definitions
+*********************************
- * keymap
+This chapter describes how to declare user options for customization,
+and also customization groups for classifying them. We use the term
+"customization item" to include both kinds of customization
+definitions--as well as face definitions.
- * marker
+* Menu:
- * process
+* Common Keywords::
+* Group Definitions::
+* Variable Definitions::
+* Customization Types::
- * range-table
+\1f
+File: lispref.info, Node: Common Keywords, Next: Group Definitions, Up: Customization
- * specifier
+Common Keywords for All Kinds of Items
+======================================
- * string
+All kinds of customization declarations (for variables and groups, and
+for faces) accept keyword arguments for specifying various information.
+This section describes some keywords that apply to all kinds.
- * subr
+ All of these keywords, except `:tag', can be used more than once in
+a given item. Each use of the keyword has an independent effect. The
+keyword `:tag' is an exception because any given item can only display
+one name.
- * subwindow
+`:tag NAME'
+ Use NAME, a string, instead of the item's name, to label the item
+ in customization menus and buffers.
- * symbol
+`:group GROUP'
+ Put this customization item in group GROUP. When you use `:group'
+ in a `defgroup', it makes the new group a subgroup of GROUP.
- * toolbar-button
+ If you use this keyword more than once, you can put a single item
+ into more than one group. Displaying any of those groups will
+ show this item. Be careful not to overdo this!
- * tooltalk-message
+`:link LINK-DATA'
+ Include an external link after the documentation string for this
+ item. This is a sentence containing an active field which
+ references some other documentation.
- * tooltalk-pattern
+ There are three alternatives you can use for LINK-DATA:
- * vector
+ `(custom-manual INFO-NODE)'
+ Link to an Info node; INFO-NODE is a string which specifies
+ the node name, as in `"(emacs)Top"'. The link appears as
+ `[manual]' in the customization buffer.
- * weak-list
+ `(info-link INFO-NODE)'
+ Like `custom-manual' except that the link appears in the
+ customization buffer with the Info node name.
- * window
+ `(url-link URL)'
+ Link to a web page; URL is a string which specifies the URL.
+ The link appears in the customization buffer as URL.
- * window-configuration
+ You can specify the text to use in the customization buffer by
+ adding `:tag NAME' after the first element of the LINK-DATA; for
+ example, `(info-link :tag "foo" "(emacs)Top")' makes a link to the
+ Emacs manual which appears in the buffer as `foo'.
- * x-resource
+ An item can have more than one external link; however, most items
+ have none at all.
- In addition, the following special types are created internally but
-will never be seen by Lisp code. You may encounter them, however, if
-you are debugging XEmacs. The printed representation of these objects
-begins `#<INTERNAL EMACS BUG', which indicates to the Lisp programmer
-that he has found an internal bug in XEmacs if he ever encounters any
-of these objects.
+`:load FILE'
+ Load file FILE (a string) before displaying this customization
+ item. Loading is done with `load-library', and only if the file is
+ not already loaded.
- * char-table-entry
+`:require FEATURE'
+ Require feature FEATURE (a symbol) when installing a value for
+ this item (an option or a face) that was saved using the
+ customization feature. This is done by calling `require'.
- * command-builder
+ The most common reason to use `:require' is when a variable enables
+ a feature such as a minor mode, and just setting the variable
+ won't have any effect unless the code which implements the mode is
+ loaded.
- * extent-auxiliary
+\1f
+File: lispref.info, Node: Group Definitions, Next: Variable Definitions, Prev: Common Keywords, Up: Customization
- * extent-info
+Defining Custom Groups
+======================
- * lcrecord-list
+Each Emacs Lisp package should have one main customization group which
+contains all the options, faces and other groups in the package. If the
+package has a small number of options and faces, use just one group and
+put everything in it. When there are more than twelve or so options and
+faces, then you should structure them into subgroups, and put the
+subgroups under the package's main customization group. It is OK to
+put some of the options and faces in the package's main group alongside
+the subgroups.
- * lstream
+ The package's main or only group should be a member of one or more of
+the standard customization groups. (To display the full list of them,
+use `M-x customize'.) Choose one or more of them (but not too many),
+and add your group to each of them using the `:group' keyword.
- * opaque
+ The way to declare new customization groups is with `defgroup'.
- * opaque-list
+ - Macro: defgroup group members doc [keyword value]...
+ Declare GROUP as a customization group containing MEMBERS. Do not
+ quote the symbol GROUP. The argument DOC specifies the
+ documentation string for the group.
- * popup-data
+ The argument MEMBERS is a list specifying an initial set of
+ customization items to be members of the group. However, most
+ often MEMBERS is `nil', and you specify the group's members by
+ using the `:group' keyword when defining those members.
- * symbol-value-buffer-local
+ If you want to specify group members through MEMBERS, each element
+ should have the form `(NAME WIDGET)'. Here NAME is a symbol, and
+ WIDGET is a widget type for editing that symbol. Useful widgets
+ are `custom-variable' for a variable, `custom-face' for a face,
+ and `custom-group' for a group.
- * symbol-value-forward
+ In addition to the common keywords (*note Common Keywords::), you
+ can use this keyword in `defgroup':
- * symbol-value-lisp-magic
+ `:prefix PREFIX'
+ If the name of an item in the group starts with PREFIX, then
+ the tag for that item is constructed (by default) by omitting
+ PREFIX.
- * symbol-value-varalias
+ One group can have any number of prefixes.
- * toolbar-data
+\1f
+File: lispref.info, Node: Variable Definitions, Next: Customization Types, Prev: Group Definitions, Up: Customization
+
+Defining Customization Variables
+================================
+
+Use `defcustom' to declare user-editable variables.
+
+ - Macro: defcustom option default doc [keyword value]...
+ Declare OPTION as a customizable user option variable. Do not
+ quote OPTION. The argument DOC specifies the documentation string
+ for the variable.
+
+ If OPTION is void, `defcustom' initializes it to DEFAULT. DEFAULT
+ should be an expression to compute the value; be careful in
+ writing it, because it can be evaluated on more than one occasion.
+
+ The following additional keywords are defined:
+
+ `:type TYPE'
+ Use TYPE as the data type for this option. It specifies which
+ values are legitimate, and how to display the value. *Note
+ Customization Types::, for more information.
+
+ `:options LIST'
+ Specify LIST as the list of reasonable values for use in this
+ option.
+
+ Currently this is meaningful only when the type is `hook'.
+ In that case, the elements of LIST should be functions that
+ are useful as elements of the hook value. The user is not
+ restricted to using only these functions, but they are
+ offered as convenient alternatives.
+
+ `:version VERSION'
+ This option specifies that the variable was first introduced,
+ or its default value was changed, in Emacs version VERSION.
+ The value VERSION must be a string. For example,
+
+ (defcustom foo-max 34
+ "*Maximum number of foo's allowed."
+ :type 'integer
+ :group 'foo
+ :version "20.3")
+
+ `:set SETFUNCTION'
+ Specify SETFUNCTION as the way to change the value of this
+ option. The function SETFUNCTION should take two arguments,
+ a symbol and the new value, and should do whatever is
+ necessary to update the value properly for this option (which
+ may not mean simply setting the option as a Lisp variable).
+ The default for SETFUNCTION is `set-default'.
+
+ `:get GETFUNCTION'
+ Specify GETFUNCTION as the way to extract the value of this
+ option. The function GETFUNCTION should take one argument, a
+ symbol, and should return the "current value" for that symbol
+ (which need not be the symbol's Lisp value). The default is
+ `default-value'.
+
+ `:initialize FUNCTION'
+ FUNCTION should be a function used to initialize the variable
+ when the `defcustom' is evaluated. It should take two
+ arguments, the symbol and value. Here are some predefined
+ functions meant for use in this way:
+
+ `custom-initialize-set'
+ Use the variable's `:set' function to initialize the
+ variable, but do not reinitialize it if it is already
+ non-void. This is the default `:initialize' function.
+
+ `custom-initialize-default'
+ Like `custom-initialize-set', but use the function
+ `set-default' to set the variable, instead of the
+ variable's `:set' function. This is the usual choice
+ for a variable whose `:set' function enables or disables
+ a minor mode; with this choice, defining the variable
+ will not call the minor mode function, but customizing
+ the variable will do so.
+
+ `custom-initialize-reset'
+ Always use the `:set' function to initialize the
+ variable. If the variable is already non-void, reset it
+ by calling the `:set' function using the current value
+ (returned by the `:get' method).
+
+ `custom-initialize-changed'
+ Use the `:set' function to initialize the variable, if
+ it is already set or has been customized; otherwise,
+ just use `set-default'.
+
+ The `:require' option is useful for an option that turns on the
+operation of a certain feature. Assuming that the package is coded to
+check the value of the option, you still need to arrange for the package
+to be loaded. You can do that with `:require'. *Note Common
+Keywords::. Here is an example, from the library `paren.el':
+
+ (defcustom show-paren-mode nil
+ "Toggle Show Paren mode...."
+ :set (lambda (symbol value)
+ (show-paren-mode (or value 0)))
+ :initialize 'custom-initialize-default
+ :type 'boolean
+ :group 'paren-showing
+ :require 'paren)
+
+ Internally, `defcustom' uses the symbol property `standard-value' to
+record the expression for the default value, and `saved-value' to
+record the value saved by the user with the customization buffer. The
+`saved-value' property is actually a list whose car is an expression
+which evaluates to the value.
\1f
-File: lispref.info, Node: Programming Types, Next: Editing Types, Prev: Primitive Types, Up: Lisp Data Types
+File: lispref.info, Node: Customization Types, Prev: Variable Definitions, Up: Customization
+
+Customization Types
+===================
+
+When you define a user option with `defcustom', you must specify its
+"customization type". That is a Lisp object which describes (1) which
+values are legitimate and (2) how to display the value in the
+customization buffer for editing.
+
+ You specify the customization type in `defcustom' with the `:type'
+keyword. The argument of `:type' is evaluated; since types that vary
+at run time are rarely useful, normally you use a quoted constant. For
+example:
+
+ (defcustom diff-command "diff"
+ "*The command to use to run diff."
+ :type '(string)
+ :group 'diff)
+
+ In general, a customization type is a list whose first element is a
+symbol, one of the customization type names defined in the following
+sections. After this symbol come a number of arguments, depending on
+the symbol. Between the type symbol and its arguments, you can
+optionally write keyword-value pairs (*note Type Keywords::).
+
+ Some of the type symbols do not use any arguments; those are called
+"simple types". For a simple type, if you do not use any keyword-value
+pairs, you can omit the parentheses around the type symbol. For
+example just `string' as a customization type is equivalent to
+`(string)'.
-Programming Types
-=================
+* Menu:
- There are two general categories of types in XEmacs Lisp: those
-having to do with Lisp programming, and those having to do with
-editing. The former exist in many Lisp implementations, in one form or
-another. The latter are unique to XEmacs Lisp.
+* Simple Types::
+* Composite Types::
+* Splicing into Lists::
+* Type Keywords::
-* Menu:
+\1f
+File: lispref.info, Node: Simple Types, Next: Composite Types, Up: Customization Types
-* Integer Type:: Numbers without fractional parts.
-* Floating Point Type:: Numbers with fractional parts and with a large range.
-* Character Type:: The representation of letters, numbers and
- control characters.
-* Symbol Type:: A multi-use object that refers to a function,
- variable, or property list, and has a unique identity.
-* Sequence Type:: Both lists and arrays are classified as sequences.
-* Cons Cell Type:: Cons cells, and lists (which are made from cons cells).
-* Array Type:: Arrays include strings and vectors.
-* String Type:: An (efficient) array of characters.
-* Vector Type:: One-dimensional arrays.
-* Bit Vector Type:: An (efficient) array of bits.
-* Function Type:: A piece of executable code you can call from elsewhere.
-* Macro Type:: A method of expanding an expression into another
- expression, more fundamental but less pretty.
-* Primitive Function Type:: A function written in C, callable from Lisp.
-* Compiled-Function Type:: A function written in Lisp, then compiled.
-* Autoload Type:: A type used for automatically loading seldom-used
- functions.
-* Char Table Type:: A mapping from characters to Lisp objects.
-* Hash Table Type:: A fast mapping between Lisp objects.
-* Range Table Type:: A mapping from ranges of integers to Lisp objects.
-* Weak List Type:: A list with special garbage-collection properties.
-
-\1f
-File: lispref.info, Node: Integer Type, Next: Floating Point Type, Up: Programming Types
-
-Integer Type
+Simple Types
------------
- The range of values for integers in XEmacs Lisp is -134217728 to
-134217727 (28 bits; i.e., -2**27 to 2**27 - 1) on most machines. (Some
-machines, in particular 64-bit machines such as the DEC Alpha, may
-provide a wider range.) It is important to note that the XEmacs Lisp
-arithmetic functions do not check for overflow. Thus `(1+ 134217727)'
-is -134217728 on most machines. (However, you _will_ get an error if
-you attempt to read an out-of-range number using the Lisp reader.)
+This section describes all the simple customization types.
+
+`sexp'
+ The value may be any Lisp object that can be printed and read
+ back. You can use `sexp' as a fall-back for any option, if you
+ don't want to take the time to work out a more specific type to
+ use.
+
+`integer'
+ The value must be an integer, and is represented textually in the
+ customization buffer.
+
+`number'
+ The value must be a number, and is represented textually in the
+ customization buffer.
+
+`string'
+ The value must be a string, and the customization buffer shows
+ just the contents, with no delimiting `"' characters and no
+ quoting with `\'.
+
+`regexp'
+ Like `string' except that the string must be a valid regular
+ expression.
+
+`character'
+ The value must be a character code. A character code is actually
+ an integer, but this type shows the value by inserting the
+ character in the buffer, rather than by showing the number.
+
+`file'
+ The value must be a file name, and you can do completion with
+ `M-<TAB>'.
+
+`(file :must-match t)'
+ The value must be a file name for an existing file, and you can do
+ completion with `M-<TAB>'.
+
+`directory'
+ The value must be a directory name, and you can do completion with
+ `M-<TAB>'.
+
+`symbol'
+ The value must be a symbol. It appears in the customization
+ buffer as the name of the symbol.
+
+`function'
+ The value must be either a lambda expression or a function name.
+ When it is a function name, you can do completion with `M-<TAB>'.
+
+`variable'
+ The value must be a variable name, and you can do completion with
+ `M-<TAB>'.
+
+`face'
+ The value must be a symbol which is a face name.
+
+`boolean'
+ The value is boolean--either `nil' or `t'. Note that by using
+ `choice' and `const' together (see the next section), you can
+ specify that the value must be `nil' or `t', but also specify the
+ text to describe each value in a way that fits the specific
+ meaning of the alternative.
+
+\1f
+File: lispref.info, Node: Composite Types, Next: Splicing into Lists, Prev: Simple Types, Up: Customization Types
+
+Composite Types
+---------------
+
+When none of the simple types is appropriate, you can use composite
+types, which build new types from other types. Here are several ways of
+doing that:
+
+`(restricted-sexp :match-alternatives CRITERIA)'
+ The value may be any Lisp object that satisfies one of CRITERIA.
+ CRITERIA should be a list, and each elements should be one of
+ these possibilities:
+
+ * A predicate--that is, a function of one argument that returns
+ non-`nil' if the argument fits a certain type. This means
+ that objects of that type are acceptable.
+
+ * A quoted constant--that is, `'OBJECT'. This means that
+ OBJECT itself is an acceptable value.
+
+ For example,
+
+ (restricted-sexp :match-alternatives (integerp 't 'nil))
+
+ allows integers, `t' and `nil' as legitimate values.
+
+ The customization buffer shows all legitimate values using their
+ read syntax, and the user edits them textually.
- The read syntax for integers is a sequence of (base ten) digits with
-an optional sign at the beginning. (The printed representation produced
-by the Lisp interpreter never has a leading `+'.)
+`(cons CAR-TYPE CDR-TYPE)'
+ The value must be a cons cell, its CAR must fit CAR-TYPE, and its
+ CDR must fit CDR-TYPE. For example, `(cons string symbol)' is a
+ customization type which matches values such as `("foo" . foo)'.
- -1 ; The integer -1.
- 1 ; The integer 1.
- +1 ; Also the integer 1.
- 268435457 ; Causes an error on a 28-bit implementation.
+ In the customization buffer, the CAR and the CDR are displayed and
+ edited separately, each according to the type that you specify for
+ it.
- *Note Numbers::, for more information.
+`(list ELEMENT-TYPES...)'
+ The value must be a list with exactly as many elements as the
+ ELEMENT-TYPES you have specified; and each element must fit the
+ corresponding ELEMENT-TYPE.
+
+ For example, `(list integer string function)' describes a list of
+ three elements; the first element must be an integer, the second a
+ string, and the third a function.
+
+ In the customization buffer, the each element is displayed and
+ edited separately, according to the type specified for it.
+
+`(vector ELEMENT-TYPES...)'
+ Like `list' except that the value must be a vector instead of a
+ list. The elements work the same as in `list'.
+
+`(choice ALTERNATIVE-TYPES...)'
+ The value must fit at least one of ALTERNATIVE-TYPES. For
+ example, `(choice integer string)' allows either an integer or a
+ string.
+
+ In the customization buffer, the user selects one of the
+ alternatives using a menu, and can then edit the value in the
+ usual way for that alternative.
+
+ Normally the strings in this menu are determined automatically
+ from the choices; however, you can specify different strings for
+ the menu by including the `:tag' keyword in the alternatives. For
+ example, if an integer stands for a number of spaces, while a
+ string is text to use verbatim, you might write the customization
+ type this way,
+
+ (choice (integer :tag "Number of spaces")
+ (string :tag "Literal text"))
+
+ so that the menu offers `Number of spaces' and `Literal Text'.
+
+ In any alternative for which `nil' is not a valid value, other than
+ a `const', you should specify a valid default for that alternative
+ using the `:value' keyword. *Note Type Keywords::.
+
+`(const VALUE)'
+ The value must be VALUE--nothing else is allowed.
+
+ The main use of `const' is inside of `choice'. For example,
+ `(choice integer (const nil))' allows either an integer or `nil'.
+
+ `:tag' is often used with `const', inside of `choice'. For
+ example,
+
+ (choice (const :tag "Yes" t)
+ (const :tag "No" nil)
+ (const :tag "Ask" foo))
+
+`(function-item FUNCTION)'
+ Like `const', but used for values which are functions. This
+ displays the documentation string as well as the function name.
+ The documentation string is either the one you specify with
+ `:doc', or FUNCTION's own documentation string.
+
+`(variable-item VARIABLE)'
+ Like `const', but used for values which are variable names. This
+ displays the documentation string as well as the variable name.
+ The documentation string is either the one you specify with
+ `:doc', or VARIABLE's own documentation string.
+
+`(set ELEMENTS...)'
+ The value must be a list and each element of the list must be one
+ of the ELEMENTS specified. This appears in the customization
+ buffer as a checklist.
+
+`(repeat ELEMENT-TYPE)'
+ The value must be a list and each element of the list must fit the
+ type ELEMENT-TYPE. This appears in the customization buffer as a
+ list of elements, with `[INS]' and `[DEL]' buttons for adding more
+ elements or removing elements.
\1f
-File: lispref.info, Node: Floating Point Type, Next: Character Type, Prev: Integer Type, Up: Programming Types
+File: lispref.info, Node: Splicing into Lists, Next: Type Keywords, Prev: Composite Types, Up: Customization Types
-Floating Point Type
+Splicing into Lists
-------------------
- XEmacs supports floating point numbers. The precise range of
-floating point numbers is machine-specific.
+The `:inline' feature lets you splice a variable number of elements
+into the middle of a list or vector. You use it in a `set', `choice'
+or `repeat' type which appears among the element-types of a `list' or
+`vector'.
+
+ Normally, each of the element-types in a `list' or `vector'
+describes one and only one element of the list or vector. Thus, if an
+element-type is a `repeat', that specifies a list of unspecified length
+which appears as one element.
+
+ But when the element-type uses `:inline', the value it matches is
+merged directly into the containing sequence. For example, if it
+matches a list with three elements, those become three elements of the
+overall sequence. This is analogous to using `,@' in the backquote
+construct.
+
+ For example, to specify a list whose first element must be `t' and
+whose remaining arguments should be zero or more of `foo' and `bar',
+use this customization type:
+
+ (list (const t) (set :inline t foo bar))
+
+This matches values such as `(t)', `(t foo)', `(t bar)' and `(t foo
+bar)'.
+
+ When the element-type is a `choice', you use `:inline' not in the
+`choice' itself, but in (some of) the alternatives of the `choice'.
+For example, to match a list which must start with a file name,
+followed either by the symbol `t' or two strings, use this
+customization type:
+
+ (list file
+ (choice (const t)
+ (list :inline t string string)))
+
+If the user chooses the first alternative in the choice, then the
+overall list has two elements and the second element is `t'. If the
+user chooses the second alternative, then the overall list has three
+elements and the second and third must be strings.
+
+\1f
+File: lispref.info, Node: Type Keywords, Prev: Splicing into Lists, Up: Customization Types
+
+Type Keywords
+-------------
+
+You can specify keyword-argument pairs in a customization type after the
+type name symbol. Here are the keywords you can use, and their
+meanings:
+
+`:value DEFAULT'
+ This is used for a type that appears as an alternative inside of
+ `choice'; it specifies the default value to use, at first, if and
+ when the user selects this alternative with the menu in the
+ customization buffer.
+
+ Of course, if the actual value of the option fits this
+ alternative, it will appear showing the actual value, not DEFAULT.
- The printed representation for floating point numbers requires either
-a decimal point (with at least one digit following), an exponent, or
-both. For example, `1500.0', `15e2', `15.0e2', `1.5e3', and `.15e4'
-are five ways of writing a floating point number whose value is 1500.
-They are all equivalent.
+ If `nil' is not a valid value for the alternative, then it is
+ essential to specify a valid default with `:value'.
- *Note Numbers::, for more information.
+`:format FORMAT-STRING'
+ This string will be inserted in the buffer to represent the value
+ corresponding to the type. The following `%' escapes are available
+ for use in FORMAT-STRING:
+
+ `%[BUTTON%]'
+ Display the text BUTTON marked as a button. The `:action'
+ attribute specifies what the button will do if the user
+ invokes it; its value is a function which takes two
+ arguments--the widget which the button appears in, and the
+ event.
+
+ There is no way to specify two different buttons with
+ different actions.
+
+ `%{SAMPLE%}'
+ Show SAMPLE in a special face specified by `:sample-face'.
+
+ `%v'
+ Substitute the item's value. How the value is represented
+ depends on the kind of item, and (for variables) on the
+ customization type.
+
+ `%d'
+ Substitute the item's documentation string.
+
+ `%h'
+ Like `%d', but if the documentation string is more than one
+ line, add an active field to control whether to show all of
+ it or just the first line.
+
+ `%t'
+ Substitute the tag here. You specify the tag with the `:tag'
+ keyword.
+
+ `%%'
+ Display a literal `%'.
+
+`:action ACTION'
+ Perform ACTION if the user clicks on a button.
+
+`:button-face FACE'
+ Use the face FACE (a face name or a list of face names) for button
+ text displayed with `%[...%]'.
+
+`:button-prefix PREFIX'
+`:button-suffix SUFFIX'
+ These specify the text to display before and after a button. Each
+ can be:
+
+ `nil'
+ No text is inserted.
+
+ a string
+ The string is inserted literally.
+
+ a symbol
+ The symbol's value is used.
+
+`:tag TAG'
+ Use TAG (a string) as the tag for the value (or part of the value)
+ that corresponds to this type.
+
+`:doc DOC'
+ Use DOC as the documentation string for this value (or part of the
+ value) that corresponds to this type. In order for this to work,
+ you must specify a value for `:format', and use `%d' or `%h' in
+ that value.
+
+ The usual reason to specify a documentation string for a type is to
+ provide more information about the meanings of alternatives inside
+ a `:choice' type or the parts of some other composite type.
+
+`:help-echo MOTION-DOC'
+ When you move to this item with `widget-forward' or
+ `widget-backward', it will display the string MOTION-DOC in the
+ echo area.
+
+`:match FUNCTION'
+ Specify how to decide whether a value matches the type. The
+ corresponding value, FUNCTION, should be a function that accepts
+ two arguments, a widget and a value; it should return non-`nil' if
+ the value is acceptable.
+
+
+\1f
+File: lispref.info, Node: Loading, Next: Byte Compilation, Prev: Macros, Up: Top
+
+Loading
+*******
+
+Loading a file of Lisp code means bringing its contents into the Lisp
+environment in the form of Lisp objects. XEmacs finds and opens the
+file, reads the text, evaluates each form, and then closes the file.
+
+ The load functions evaluate all the expressions in a file just as
+the `eval-current-buffer' function evaluates all the expressions in a
+buffer. The difference is that the load functions read and evaluate
+the text in the file as found on disk, not the text in an Emacs buffer.
+
+ The loaded file must contain Lisp expressions, either as source code
+or as byte-compiled code. Each form in the file is called a "top-level
+form". There is no special format for the forms in a loadable file;
+any form in a file may equally well be typed directly into a buffer and
+evaluated there. (Indeed, most code is tested this way.) Most often,
+the forms are function definitions and variable definitions.
+
+ A file containing Lisp code is often called a "library". Thus, the
+"Rmail library" is a file containing code for Rmail mode. Similarly, a
+"Lisp library directory" is a directory of files containing Lisp code.
+
+* Menu:
+
+* How Programs Do Loading:: The `load' function and others.
+* Autoload:: Setting up a function to autoload.
+* Repeated Loading:: Precautions about loading a file twice.
+* Named Features:: Loading a library if it isn't already loaded.
+* Unloading:: How to ``unload'' a library that was loaded.
+* Hooks for Loading:: Providing code to be run when
+ particular libraries are loaded.
+
+\1f
+File: lispref.info, Node: How Programs Do Loading, Next: Autoload, Up: Loading
+
+How Programs Do Loading
+=======================
+
+XEmacs Lisp has several interfaces for loading. For example,
+`autoload' creates a placeholder object for a function in a file;
+trying to call the autoloading function loads the file to get the
+function's real definition (*note Autoload::). `require' loads a file
+if it isn't already loaded (*note Named Features::). Ultimately, all
+these facilities call the `load' function to do the work.
+
+ - Function: load filename &optional missing-ok nomessage nosuffix
+ This function finds and opens a file of Lisp code, evaluates all
+ the forms in it, and closes the file.
+
+ To find the file, `load' first looks for a file named
+ `FILENAME.elc', that is, for a file whose name is FILENAME with
+ `.elc' appended. If such a file exists, it is loaded. If there
+ is no file by that name, then `load' looks for a file named
+ `FILENAME.el'. If that file exists, it is loaded. Finally, if
+ neither of those names is found, `load' looks for a file named
+ FILENAME with nothing appended, and loads it if it exists. (The
+ `load' function is not clever about looking at FILENAME. In the
+ perverse case of a file named `foo.el.el', evaluation of `(load
+ "foo.el")' will indeed find it.)
+
+ If the optional argument NOSUFFIX is non-`nil', then the suffixes
+ `.elc' and `.el' are not tried. In this case, you must specify
+ the precise file name you want.
+
+ If FILENAME is a relative file name, such as `foo' or
+ `baz/foo.bar', `load' searches for the file using the variable
+ `load-path'. It appends FILENAME to each of the directories
+ listed in `load-path', and loads the first file it finds whose name
+ matches. The current default directory is tried only if it is
+ specified in `load-path', where `nil' stands for the default
+ directory. `load' tries all three possible suffixes in the first
+ directory in `load-path', then all three suffixes in the second
+ directory, and so on.
+
+ If you get a warning that `foo.elc' is older than `foo.el', it
+ means you should consider recompiling `foo.el'. *Note Byte
+ Compilation::.
+
+ Messages like `Loading foo...' and `Loading foo...done' appear in
+ the echo area during loading unless NOMESSAGE is non-`nil'.
+
+ Any unhandled errors while loading a file terminate loading. If
+ the load was done for the sake of `autoload', any function
+ definitions made during the loading are undone.
+
+ If `load' can't find the file to load, then normally it signals the
+ error `file-error' (with `Cannot open load file FILENAME'). But
+ if MISSING-OK is non-`nil', then `load' just returns `nil'.
+
+ You can use the variable `load-read-function' to specify a function
+ for `load' to use instead of `read' for reading expressions. See
+ below.
+
+ `load' returns `t' if the file loads successfully.
+
+ - User Option: load-path
+ The value of this variable is a list of directories to search when
+ loading files with `load'. Each element is a string (which must be
+ a directory name) or `nil' (which stands for the current working
+ directory). The value of `load-path' is initialized from the
+ environment variable `EMACSLOADPATH', if that exists; otherwise its
+ default value is specified in `emacs/src/paths.h' when XEmacs is
+ built.
+
+ The syntax of `EMACSLOADPATH' is the same as used for `PATH'; `:'
+ (or `;', according to the operating system) separates directory
+ names, and `.' is used for the current default directory. Here is
+ an example of how to set your `EMACSLOADPATH' variable from a
+ `csh' `.login' file:
+
+ setenv EMACSLOADPATH .:/user/bil/emacs:/usr/lib/emacs/lisp
+
+ Here is how to set it using `sh':
+
+ export EMACSLOADPATH
+ EMACSLOADPATH=.:/user/bil/emacs:/usr/local/lib/emacs/lisp
+
+ Here is an example of code you can place in a `.emacs' file to add
+ several directories to the front of your default `load-path':
+
+ (setq load-path
+ (append (list nil "/user/bil/emacs"
+ "/usr/local/lisplib"
+ "~/emacs")
+ load-path))
+
+ In this example, the path searches the current working directory
+ first, followed then by the `/user/bil/emacs' directory, the
+ `/usr/local/lisplib' directory, and the `~/emacs' directory, which
+ are then followed by the standard directories for Lisp code.
+
+ The command line options `-l' or `-load' specify a Lisp library to
+ load as part of Emacs startup. Since this file might be in the
+ current directory, Emacs 18 temporarily adds the current directory
+ to the front of `load-path' so the file can be found there. Newer
+ Emacs versions also find such files in the current directory, but
+ without altering `load-path'.
+
+ Dumping Emacs uses a special value of `load-path'. If the value of
+ `load-path' at the end of dumping is unchanged (that is, still the
+ same special value), the dumped Emacs switches to the ordinary
+ `load-path' value when it starts up, as described above. But if
+ `load-path' has any other value at the end of dumping, that value
+ is used for execution of the dumped Emacs also.
+
+ Therefore, if you want to change `load-path' temporarily for
+ loading a few libraries in `site-init.el' or `site-load.el', you
+ should bind `load-path' locally with `let' around the calls to
+ `load'.
+
+ - Function: locate-file filename path-list &optional suffixes mode
+ This function searches for a file in the same way that `load' does,
+ and returns the file found (if any). (In fact, `load' uses this
+ function to search through `load-path'.) It searches for FILENAME
+ through PATH-LIST, expanded by one of the optional SUFFIXES
+ (string of suffixes separated by `:'s), checking for access MODE
+ (0|1|2|4 = exists|executable|writable|readable), default readable.
+
+ `locate-file' keeps hash tables of the directories it searches
+ through, in order to speed things up. It tries valiantly to not
+ get confused in the face of a changing and unpredictable
+ environment, but can occasionally get tripped up. In this case,
+ you will have to call `locate-file-clear-hashing' to get it back
+ on track. See that function for details.
+
+ - Function: locate-file-clear-hashing path
+ This function clears the hash records for the specified list of
+ directories. `locate-file' uses a hashing scheme to speed lookup,
+ and will correctly track the following environmental changes:
+
+ * changes of any sort to the list of directories to be searched.
+
+ * addition and deletion of non-shadowing files (see below) from
+ the directories in the list.
+
+ * byte-compilation of a .el file into a .elc file.
+
+ `locate-file' will primarily get confused if you add a file that
+ shadows (i.e. has the same name as) another file further down in
+ the directory list. In this case, you must call
+ `locate-file-clear-hashing'.
+
+ - Variable: load-in-progress
+ This variable is non-`nil' if Emacs is in the process of loading a
+ file, and it is `nil' otherwise.
+
+ - Variable: load-read-function
+ This variable specifies an alternate expression-reading function
+ for `load' and `eval-region' to use instead of `read'. The
+ function should accept one argument, just as `read' does.
+
+ Normally, the variable's value is `nil', which means those
+ functions should use `read'.
+
+ - User Option: load-warn-when-source-newer
+ This variable specifies whether `load' should check whether the
+ source is newer than the binary. If this variable is true, then
+ when a `.elc' file is being loaded and the corresponding `.el' is
+ newer, a warning message will be printed. The default is `nil',
+ but it is bound to `t' during the initial loadup.
+
+ - User Option: load-warn-when-source-only
+ This variable specifies whether `load' should warn when loading a
+ `.el' file instead of an `.elc'. If this variable is true, then
+ when `load' is called with a filename without an extension, and
+ the `.elc' version doesn't exist but the `.el' version does, then
+ a message will be printed. If an explicit extension is passed to
+ `load', no warning will be printed. The default is `nil', but it
+ is bound to `t' during the initial loadup.
+
+ - User Option: load-ignore-elc-files
+ This variable specifies whether `load' should ignore `.elc' files
+ when a suffix is not given. This is normally used only to
+ bootstrap the `.elc' files when building XEmacs, when you use the
+ command `make all-elc'. (This forces the `.el' versions to be
+ loaded in the process of compiling those same files, so that
+ existing out-of-date `.elc' files do not make it mess things up.)
+
+ To learn how `load' is used to build XEmacs, see *Note Building
+XEmacs::.