1 This is ../info/lispref.info, produced by makeinfo version 4.6 from
4 INFO-DIR-SECTION XEmacs Editor
6 * Lispref: (lispref). XEmacs Lisp Reference Manual.
11 GNU Emacs Lisp Reference Manual Second Edition (v2.01), May 1993 GNU
12 Emacs Lisp Reference Manual Further Revised (v2.02), August 1993 Lucid
13 Emacs Lisp Reference Manual (for 19.10) First Edition, March 1994
14 XEmacs Lisp Programmer's Manual (for 19.12) Second Edition, April 1995
15 GNU Emacs Lisp Reference Manual v2.4, June 1995 XEmacs Lisp
16 Programmer's Manual (for 19.13) Third Edition, July 1995 XEmacs Lisp
17 Reference Manual (for 19.14 and 20.0) v3.1, March 1996 XEmacs Lisp
18 Reference Manual (for 19.15 and 20.1, 20.2, 20.3) v3.2, April, May,
19 November 1997 XEmacs Lisp Reference Manual (for 21.0) v3.3, April 1998
21 Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995 Free Software
22 Foundation, Inc. Copyright (C) 1994, 1995 Sun Microsystems, Inc.
23 Copyright (C) 1995, 1996 Ben Wing.
25 Permission is granted to make and distribute verbatim copies of this
26 manual provided the copyright notice and this permission notice are
27 preserved on all copies.
29 Permission is granted to copy and distribute modified versions of
30 this manual under the conditions for verbatim copying, provided that the
31 entire resulting derived work is distributed under the terms of a
32 permission notice identical to this one.
34 Permission is granted to copy and distribute translations of this
35 manual into another language, under the above conditions for modified
36 versions, except that this permission notice may be stated in a
37 translation approved by the Foundation.
39 Permission is granted to copy and distribute modified versions of
40 this manual under the conditions for verbatim copying, provided also
41 that the section entitled "GNU General Public License" is included
42 exactly as in the original, and provided that the entire resulting
43 derived work is distributed under the terms of a permission notice
44 identical to this one.
46 Permission is granted to copy and distribute translations of this
47 manual into another language, under the above conditions for modified
48 versions, except that the section entitled "GNU General Public License"
49 may be included in a translation approved by the Free Software
50 Foundation instead of in the original English.
53 File: lispref.info, Node: List Elements, Next: Building Lists, Prev: List-related Predicates, Up: Lists
55 Accessing Elements of Lists
56 ===========================
58 - Function: car cons-cell
59 This function returns the value pointed to by the first pointer of
60 the cons cell CONS-CELL. Expressed another way, this function
61 returns the CAR of CONS-CELL.
63 As a special case, if CONS-CELL is `nil', then `car' is defined to
64 return `nil'; therefore, any list is a valid argument for `car'.
65 An error is signaled if the argument is not a cons cell or `nil'.
72 - Function: cdr cons-cell
73 This function returns the value pointed to by the second pointer of
74 the cons cell CONS-CELL. Expressed another way, this function
75 returns the CDR of CONS-CELL.
77 As a special case, if CONS-CELL is `nil', then `cdr' is defined to
78 return `nil'; therefore, any list is a valid argument for `cdr'.
79 An error is signaled if the argument is not a cons cell or `nil'.
86 - Function: car-safe object
87 This function lets you take the CAR of a cons cell while avoiding
88 errors for other data types. It returns the CAR of OBJECT if
89 OBJECT is a cons cell, `nil' otherwise. This is in contrast to
90 `car', which signals an error if OBJECT is not a list.
99 - Function: cdr-safe object
100 This function lets you take the CDR of a cons cell while avoiding
101 errors for other data types. It returns the CDR of OBJECT if
102 OBJECT is a cons cell, `nil' otherwise. This is in contrast to
103 `cdr', which signals an error if OBJECT is not a list.
112 - Function: nth n list
113 This function returns the Nth element of LIST. Elements are
114 numbered starting with zero, so the CAR of LIST is element number
115 zero. If the length of LIST is N or less, the value is `nil'.
117 If N is negative, `nth' returns the first element of LIST.
126 (nth n x) == (car (nthcdr n x))
128 - Function: nthcdr n list
129 This function returns the Nth CDR of LIST. In other words, it
130 removes the first N links of LIST and returns what follows.
132 If N is zero or negative, `nthcdr' returns all of LIST. If the
133 length of LIST is N or less, `nthcdr' returns `nil'.
135 (nthcdr 1 '(1 2 3 4))
137 (nthcdr 10 '(1 2 3 4))
139 (nthcdr -3 '(1 2 3 4))
142 Many convenience functions are provided to make it easier for you to
143 access particular elements in a nested list. All of these can be
144 rewritten in terms of the functions just described.
146 - Function: caar cons-cell
147 - Function: cadr cons-cell
148 - Function: cdar cons-cell
149 - Function: cddr cons-cell
150 - Function: caaar cons-cell
151 - Function: caadr cons-cell
152 - Function: cadar cons-cell
153 - Function: caddr cons-cell
154 - Function: cdaar cons-cell
155 - Function: cdadr cons-cell
156 - Function: cddar cons-cell
157 - Function: cdddr cons-cell
158 - Function: caaaar cons-cell
159 - Function: caaadr cons-cell
160 - Function: caadar cons-cell
161 - Function: caaddr cons-cell
162 - Function: cadaar cons-cell
163 - Function: cadadr cons-cell
164 - Function: caddar cons-cell
165 - Function: cadddr cons-cell
166 - Function: cdaaar cons-cell
167 - Function: cdaadr cons-cell
168 - Function: cdadar cons-cell
169 - Function: cdaddr cons-cell
170 - Function: cddaar cons-cell
171 - Function: cddadr cons-cell
172 - Function: cdddar cons-cell
173 - Function: cddddr cons-cell
174 Each of these functions is equivalent to one or more applications
175 of `car' and/or `cdr'. For example,
189 (cdr (car (cdr (cdr x))))
191 That is to say, read the a's and d's from right to left and apply
192 a `car' or `cdr' for each a or d found, respectively.
194 - Function: first list
195 This is equivalent to `(nth 0 LIST)', i.e. the first element of
196 LIST. (Note that this is also equivalent to `car'.)
198 - Function: second list
199 This is equivalent to `(nth 1 LIST)', i.e. the second element of
202 - Function: third list
203 - Function: fourth list
204 - Function: fifth list
205 - Function: sixth list
206 - Function: seventh list
207 - Function: eighth list
208 - Function: ninth list
209 - Function: tenth list
210 These are equivalent to `(nth 2 LIST)' through `(nth 9 LIST)'
211 respectively, i.e. the third through tenth elements of LIST.
214 File: lispref.info, Node: Building Lists, Next: Modifying Lists, Prev: List Elements, Up: Lists
216 Building Cons Cells and Lists
217 =============================
219 Many functions build lists, as lists reside at the very heart of Lisp.
220 `cons' is the fundamental list-building function; however, it is
221 interesting to note that `list' is used more times in the source code
222 for Emacs than `cons'.
224 - Function: cons object1 object2
225 This function is the fundamental function used to build new list
226 structure. It creates a new cons cell, making OBJECT1 the CAR,
227 and OBJECT2 the CDR. It then returns the new cons cell. The
228 arguments OBJECT1 and OBJECT2 may be any Lisp objects, but most
229 often OBJECT2 is a list.
238 `cons' is often used to add a single element to the front of a
239 list. This is called "consing the element onto the list". For
242 (setq list (cons newelt list))
244 Note that there is no conflict between the variable named `list'
245 used in this example and the function named `list' described below;
246 any symbol can serve both purposes.
248 - Function: list &rest objects
249 This function creates a list with OBJECTS as its elements. The
250 resulting list is always `nil'-terminated. If no OBJECTS are
251 given, the empty list is returned.
255 (list 1 2 '(3 4 5) 'foo)
260 - Function: make-list length object
261 This function creates a list of length LENGTH, in which all the
262 elements have the identical value OBJECT. Compare `make-list'
263 with `make-string' (*note Creating Strings::).
270 - Function: append &rest sequences
271 This function returns a list containing all the elements of
272 SEQUENCES. The SEQUENCES may be lists, vectors, or strings, but
273 the last one should be a list. All arguments except the last one
274 are copied, so none of them are altered.
276 More generally, the final argument to `append' may be any Lisp
277 object. The final argument is not copied or converted; it becomes
278 the CDR of the last cons cell in the new list. If the final
279 argument is itself a list, then its elements become in effect
280 elements of the result list. If the final element is not a list,
281 the result is a "dotted list" since its final CDR is not `nil' as
282 required in a true list.
284 See `nconc' in *Note Rearrangement::, for a way to join lists with
287 Here is an example of using `append':
289 (setq trees '(pine oak))
291 (setq more-trees (append '(maple birch) trees))
292 => (maple birch pine oak)
297 => (maple birch pine oak)
298 (eq trees (cdr (cdr more-trees)))
301 You can see how `append' works by looking at a box diagram. The
302 variable `trees' is set to the list `(pine oak)' and then the
303 variable `more-trees' is set to the list `(maple birch pine oak)'.
304 However, the variable `trees' continues to refer to the original
309 | ___ ___ ___ ___ -> ___ ___ ___ ___
310 --> |___|___|--> |___|___|--> |___|___|--> |___|___|--> nil
313 --> maple -->birch --> pine --> oak
315 An empty sequence contributes nothing to the value returned by
316 `append'. As a consequence of this, a final `nil' argument forces
317 a copy of the previous argument.
321 (setq wood (append trees ()))
328 This once was the usual way to copy a list, before the function
329 `copy-sequence' was invented. *Note Sequences Arrays Vectors::.
331 With the help of `apply', we can append all the lists in a list of
334 (apply 'append '((a b c) nil (x y z) nil))
337 If no SEQUENCES are given, `nil' is returned:
342 Here are some examples where the final argument is not a list:
349 The second example shows that when the final argument is a
350 sequence but not a list, the sequence's elements do not become
351 elements of the resulting list. Instead, the sequence becomes the
352 final CDR, like any other non-list final argument.
354 The `append' function also allows integers as arguments. It
355 converts them to strings of digits, making up the decimal print
356 representation of the integer, and then uses the strings instead
357 of the original integers. *Don't use this feature; we plan to
358 eliminate it. If you already use this feature, change your
359 programs now!* The proper way to convert an integer to a decimal
360 number in this way is with `format' (*note Formatting Strings::)
361 or `number-to-string' (*note String Conversion::).
363 - Function: reverse list
364 This function creates a new list whose elements are the elements of
365 LIST, but in reverse order. The original argument LIST is _not_
376 File: lispref.info, Node: Modifying Lists, Next: Sets And Lists, Prev: Building Lists, Up: Lists
378 Modifying Existing List Structure
379 =================================
381 You can modify the CAR and CDR contents of a cons cell with the
382 primitives `setcar' and `setcdr'.
384 Common Lisp note: Common Lisp uses functions `rplaca' and `rplacd'
385 to alter list structure; they change structure the same way as
386 `setcar' and `setcdr', but the Common Lisp functions return the
387 cons cell while `setcar' and `setcdr' return the new CAR or CDR.
391 * Setcar:: Replacing an element in a list.
392 * Setcdr:: Replacing part of the list backbone.
393 This can be used to remove or add elements.
394 * Rearrangement:: Reordering the elements in a list; combining lists.
397 File: lispref.info, Node: Setcar, Next: Setcdr, Up: Modifying Lists
399 Altering List Elements with `setcar'
400 ------------------------------------
402 Changing the CAR of a cons cell is done with `setcar'. When used on a
403 list, `setcar' replaces one element of a list with a different element.
405 - Function: setcar cons-cell object
406 This function stores OBJECT as the new CAR of CONS-CELL, replacing
407 its previous CAR. It returns the value OBJECT. For example:
416 When a cons cell is part of the shared structure of several lists,
417 storing a new CAR into the cons changes one element of each of these
418 lists. Here is an example:
420 ;; Create two lists that are partly shared.
423 (setq x2 (cons 'z (cdr x1)))
426 ;; Replace the CAR of a shared link.
427 (setcar (cdr x1) 'foo)
429 x1 ; Both lists are changed.
434 ;; Replace the CAR of a link that is not shared.
437 x1 ; Only one list is changed.
442 Here is a graphical depiction of the shared structure of the two
443 lists in the variables `x1' and `x2', showing why replacing `b' changes
446 ___ ___ ___ ___ ___ ___
447 x1---> |___|___|----> |___|___|--> |___|___|--> nil
458 Here is an alternative form of box diagram, showing the same
462 -------------- -------------- --------------
463 | car | cdr | | car | cdr | | car | cdr |
464 | a | o------->| b | o------->| c | nil |
466 -------------- | -------------- --------------
476 File: lispref.info, Node: Setcdr, Next: Rearrangement, Prev: Setcar, Up: Modifying Lists
478 Altering the CDR of a List
479 --------------------------
481 The lowest-level primitive for modifying a CDR is `setcdr':
483 - Function: setcdr cons-cell object
484 This function stores OBJECT as the new CDR of CONS-CELL, replacing
485 its previous CDR. It returns the value OBJECT.
487 Here is an example of replacing the CDR of a list with a different
488 list. All but the first element of the list are removed in favor of a
489 different sequence of elements. The first element is unchanged,
490 because it resides in the CAR of the list, and is not reached via the
500 You can delete elements from the middle of a list by altering the
501 CDRs of the cons cells in the list. For example, here we delete the
502 second element, `b', from the list `(a b c)', by changing the CDR of
507 (setcdr x1 (cdr (cdr x1)))
512 Here is the result in box notation:
516 -------------- | -------------- | --------------
517 | car | cdr | | | car | cdr | -->| car | cdr |
518 | a | o----- | b | o-------->| c | nil |
520 -------------- -------------- --------------
522 The second cons cell, which previously held the element `b', still
523 exists and its CAR is still `b', but it no longer forms part of this
526 It is equally easy to insert a new element by changing CDRs:
530 (setcdr x1 (cons 'd (cdr x1)))
535 Here is this result in box notation:
537 -------------- ------------- -------------
538 | car | cdr | | car | cdr | | car | cdr |
539 | a | o | -->| b | o------->| c | nil |
540 | | | | | | | | | | |
541 --------- | -- | ------------- -------------
552 File: lispref.info, Node: Rearrangement, Prev: Setcdr, Up: Modifying Lists
554 Functions that Rearrange Lists
555 ------------------------------
557 Here are some functions that rearrange lists "destructively" by
558 modifying the CDRs of their component cons cells. We call these
559 functions "destructive" because they chew up the original lists passed
560 to them as arguments, to produce a new list that is the returned value.
562 See `delq', in *Note Sets And Lists::, for another function that
565 - Function: nconc &rest lists
566 This function returns a list containing all the elements of LISTS.
567 Unlike `append' (*note Building Lists::), the LISTS are _not_
568 copied. Instead, the last CDR of each of the LISTS is changed to
569 refer to the following list. The last of the LISTS is not
570 altered. For example:
579 Since the last argument of `nconc' is not itself modified, it is
580 reasonable to use a constant list, such as `'(4 5)', as in the
581 above example. For the same reason, the last argument need not be
591 A common pitfall is to use a quoted constant list as a non-last
592 argument to `nconc'. If you do this, your program will change
593 each time you run it! Here is what happens:
595 (defun add-foo (x) ; We want this function to add
596 (nconc '(foo) x)) ; `foo' to the front of its arg.
598 (symbol-function 'add-foo)
599 => (lambda (x) (nconc (quote (foo)) x))
601 (setq xx (add-foo '(1 2))) ; It seems to work.
603 (setq xy (add-foo '(3 4))) ; What happened?
608 (symbol-function 'add-foo)
609 => (lambda (x) (nconc (quote (foo 1 2 3 4) x)))
611 - Function: nreverse list
612 This function reverses the order of the elements of LIST. Unlike
613 `reverse', `nreverse' alters its argument by reversing the CDRs in
614 the cons cells forming the list. The cons cell that used to be
615 the last one in LIST becomes the first cell of the value.
625 ;; The cell that was first is now last.
629 To avoid confusion, we usually store the result of `nreverse' back
630 in the same variable which held the original list:
632 (setq x (nreverse x))
634 Here is the `nreverse' of our favorite example, `(a b c)',
635 presented graphically:
637 Original list head: Reversed list:
638 ------------- ------------- ------------
639 | car | cdr | | car | cdr | | car | cdr |
640 | a | nil |<-- | b | o |<-- | c | o |
641 | | | | | | | | | | | | |
642 ------------- | --------- | - | -------- | -
644 ------------- ------------
646 - Function: sort list predicate
647 This function sorts LIST stably, though destructively, and returns
648 the sorted list. It compares elements using PREDICATE. A stable
649 sort is one in which elements with equal sort keys maintain their
650 relative order before and after the sort. Stability is important
651 when successive sorts are used to order elements according to
654 The argument PREDICATE must be a function that accepts two
655 arguments. It is called with two elements of LIST. To get an
656 increasing order sort, the PREDICATE should return `t' if the
657 first element is "less than" the second, or `nil' if not.
659 The destructive aspect of `sort' is that it rearranges the cons
660 cells forming LIST by changing CDRs. A nondestructive sort
661 function would create new cons cells to store the elements in their
662 sorted order. If you wish to make a sorted copy without
663 destroying the original, copy it first with `copy-sequence' and
666 Sorting does not change the CARs of the cons cells in LIST; the
667 cons cell that originally contained the element `a' in LIST still
668 has `a' in its CAR after sorting, but it now appears in a
669 different position in the list due to the change of CDRs. For
672 (setq nums '(1 3 2 6 5 4 0))
679 Note that the list in `nums' no longer contains 0; this is the same
680 cons cell that it was before, but it is no longer the first one in
681 the list. Don't assume a variable that formerly held the argument
682 now holds the entire sorted list! Instead, save the result of
683 `sort' and use that. Most often we store the result back into the
684 variable that held the original list:
686 (setq nums (sort nums '<))
688 *Note Sorting::, for more functions that perform sorting. See
689 `documentation' in *Note Accessing Documentation::, for a useful
693 File: lispref.info, Node: Sets And Lists, Next: Association Lists, Prev: Modifying Lists, Up: Lists
698 A list can represent an unordered mathematical set--simply consider a
699 value an element of a set if it appears in the list, and ignore the
700 order of the list. To form the union of two sets, use `append' (as
701 long as you don't mind having duplicate elements). Other useful
702 functions for sets include `memq' and `delq', and their `equal'
703 versions, `member' and `delete'.
705 Common Lisp note: Common Lisp has functions `union' (which avoids
706 duplicate elements) and `intersection' for set operations, but
707 XEmacs Lisp does not have them. You can write them in Lisp if you
710 - Function: memq object list
711 This function tests to see whether OBJECT is a member of LIST. If
712 it is, `memq' returns a list starting with the first occurrence of
713 OBJECT. Otherwise, it returns `nil'. The letter `q' in `memq'
714 says that it uses `eq' to compare OBJECT against the elements of
715 the list. For example:
717 (memq 'b '(a b c b a))
719 (memq '(2) '((1) (2))) ; `(2)' and `(2)' are not `eq'.
722 - Function: delq object list
723 This function destructively removes all elements `eq' to OBJECT
724 from LIST. The letter `q' in `delq' says that it uses `eq' to
725 compare OBJECT against the elements of the list, like `memq'.
727 When `delq' deletes elements from the front of the list, it does so
728 simply by advancing down the list and returning a sublist that starts
729 after those elements:
731 (delq 'a '(a b c)) == (cdr '(a b c))
733 When an element to be deleted appears in the middle of the list,
734 removing it involves changing the CDRs (*note Setcdr::).
736 (setq sample-list '(a b c (4)))
738 (delq 'a sample-list)
742 (delq 'c sample-list)
747 Note that `(delq 'c sample-list)' modifies `sample-list' to splice
748 out the third element, but `(delq 'a sample-list)' does not splice
749 anything--it just returns a shorter list. Don't assume that a variable
750 which formerly held the argument LIST now has fewer elements, or that
751 it still holds the original list! Instead, save the result of `delq'
752 and use that. Most often we store the result back into the variable
753 that held the original list:
755 (setq flowers (delq 'rose flowers))
757 In the following example, the `(4)' that `delq' attempts to match
758 and the `(4)' in the `sample-list' are not `eq':
760 (delq '(4) sample-list)
763 The following two functions are like `memq' and `delq' but use
764 `equal' rather than `eq' to compare elements. They are new in Emacs 19.
766 - Function: member object list
767 The function `member' tests to see whether OBJECT is a member of
768 LIST, comparing members with OBJECT using `equal'. If OBJECT is a
769 member, `member' returns a list starting with its first occurrence
770 in LIST. Otherwise, it returns `nil'.
772 Compare this with `memq':
774 (member '(2) '((1) (2))) ; `(2)' and `(2)' are `equal'.
776 (memq '(2) '((1) (2))) ; `(2)' and `(2)' are not `eq'.
778 ;; Two strings with the same contents are `equal'.
779 (member "foo" '("foo" "bar"))
782 - Function: delete object list
783 This function destructively removes all elements `equal' to OBJECT
784 from LIST. It is to `delq' as `member' is to `memq': it uses
785 `equal' to compare elements with OBJECT, like `member'; when it
786 finds an element that matches, it removes the element just as
787 `delq' would. For example:
789 (delete '(2) '((2) (1) (2)))
792 Common Lisp note: The functions `member' and `delete' in XEmacs
793 Lisp are derived from Maclisp, not Common Lisp. The Common Lisp
794 versions do not use `equal' to compare elements.
796 See also the function `add-to-list', in *Note Setting Variables::,
797 for another way to add an element to a list stored in a variable.
800 File: lispref.info, Node: Association Lists, Next: Property Lists, Prev: Sets And Lists, Up: Lists
805 An "association list", or "alist" for short, records a mapping from
806 keys to values. It is a list of cons cells called "associations": the
807 CAR of each cell is the "key", and the CDR is the "associated value".(1)
809 Here is an example of an alist. The key `pine' is associated with
810 the value `cones'; the key `oak' is associated with `acorns'; and the
811 key `maple' is associated with `seeds'.
817 The associated values in an alist may be any Lisp objects; so may the
818 keys. For example, in the following alist, the symbol `a' is
819 associated with the number `1', and the string `"b"' is associated with
820 the _list_ `(2 3)', which is the CDR of the alist element:
824 Sometimes it is better to design an alist to store the associated
825 value in the CAR of the CDR of the element. Here is an example:
827 '((rose red) (lily white) (buttercup yellow))
829 Here we regard `red' as the value associated with `rose'. One
830 advantage of this method is that you can store other related
831 information--even a list of other items--in the CDR of the CDR. One
832 disadvantage is that you cannot use `rassq' (see below) to find the
833 element containing a given value. When neither of these considerations
834 is important, the choice is a matter of taste, as long as you are
835 consistent about it for any given alist.
837 Note that the same alist shown above could be regarded as having the
838 associated value in the CDR of the element; the value associated with
839 `rose' would be the list `(red)'.
841 Association lists are often used to record information that you might
842 otherwise keep on a stack, since new associations may be added easily to
843 the front of the list. When searching an association list for an
844 association with a given key, the first one found is returned, if there
847 In XEmacs Lisp, it is _not_ an error if an element of an association
848 list is not a cons cell. The alist search functions simply ignore such
849 elements. Many other versions of Lisp signal errors in such cases.
851 Note that property lists are similar to association lists in several
852 respects. A property list behaves like an association list in which
853 each key can occur only once. *Note Property Lists::, for a comparison
854 of property lists and association lists.
856 - Function: assoc key alist
857 This function returns the first association for KEY in ALIST. It
858 compares KEY against the alist elements using `equal' (*note
859 Equality Predicates::). It returns `nil' if no association in
860 ALIST has a CAR `equal' to KEY. For example:
862 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
863 => ((pine . cones) (oak . acorns) (maple . seeds))
866 (cdr (assoc 'oak trees))
871 Here is another example, in which the keys and values are not
874 (setq needles-per-cluster
875 '((2 "Austrian Pine" "Red Pine")
879 (cdr (assoc 3 needles-per-cluster))
881 (cdr (assoc 2 needles-per-cluster))
882 => ("Austrian Pine" "Red Pine")
884 - Function: rassoc value alist
885 This function returns the first association with value VALUE in
886 ALIST. It returns `nil' if no association in ALIST has a CDR
889 `rassoc' is like `assoc' except that it compares the CDR of each
890 ALIST association instead of the CAR. You can think of this as
891 "reverse `assoc'", finding the key for a given value.
893 - Function: assq key alist
894 This function is like `assoc' in that it returns the first
895 association for KEY in ALIST, but it makes the comparison using
896 `eq' instead of `equal'. `assq' returns `nil' if no association
897 in ALIST has a CAR `eq' to KEY. This function is used more often
898 than `assoc', since `eq' is faster than `equal' and most alists
899 use symbols as keys. *Note Equality Predicates::.
901 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
902 => ((pine . cones) (oak . acorns) (maple . seeds))
906 On the other hand, `assq' is not usually useful in alists where the
907 keys may not be symbols:
910 '(("simple leaves" . oak)
911 ("compound leaves" . horsechestnut)))
913 (assq "simple leaves" leaves)
915 (assoc "simple leaves" leaves)
916 => ("simple leaves" . oak)
918 - Function: rassq value alist
919 This function returns the first association with value VALUE in
920 ALIST. It returns `nil' if no association in ALIST has a CDR `eq'
923 `rassq' is like `assq' except that it compares the CDR of each
924 ALIST association instead of the CAR. You can think of this as
925 "reverse `assq'", finding the key for a given value.
929 (setq trees '((pine . cones) (oak . acorns) (maple . seeds)))
931 (rassq 'acorns trees)
933 (rassq 'spores trees)
936 Note that `rassq' cannot search for a value stored in the CAR of
937 the CDR of an element:
939 (setq colors '((rose red) (lily white) (buttercup yellow)))
941 (rassq 'white colors)
944 In this case, the CDR of the association `(lily white)' is not the
945 symbol `white', but rather the list `(white)'. This becomes
946 clearer if the association is written in dotted pair notation:
948 (lily white) == (lily . (white))
950 - Function: remassoc key alist
951 This function deletes by side effect any associations with key KEY
952 in ALIST--i.e. it removes any elements from ALIST whose `car' is
953 `equal' to KEY. The modified ALIST is returned.
955 If the first member of ALIST has a `car' that is `equal' to KEY,
956 there is no way to remove it by side effect; therefore, write
957 `(setq foo (remassoc key foo))' to be sure of changing the value
960 - Function: remassq key alist
961 This function deletes by side effect any associations with key KEY
962 in ALIST--i.e. it removes any elements from ALIST whose `car' is
963 `eq' to KEY. The modified ALIST is returned.
965 This function is exactly like `remassoc', but comparisons between
966 KEY and keys in ALIST are done using `eq' instead of `equal'.
968 - Function: remrassoc value alist
969 This function deletes by side effect any associations with value
970 VALUE in ALIST--i.e. it removes any elements from ALIST whose
971 `cdr' is `equal' to VALUE. The modified ALIST is returned.
973 If the first member of ALIST has a `car' that is `equal' to VALUE,
974 there is no way to remove it by side effect; therefore, write
975 `(setq foo (remassoc value foo))' to be sure of changing the value
978 `remrassoc' is like `remassoc' except that it compares the CDR of
979 each ALIST association instead of the CAR. You can think of this
980 as "reverse `remassoc'", removing an association based on its
981 value instead of its key.
983 - Function: remrassq value alist
984 This function deletes by side effect any associations with value
985 VALUE in ALIST--i.e. it removes any elements from ALIST whose
986 `cdr' is `eq' to VALUE. The modified ALIST is returned.
988 This function is exactly like `remrassoc', but comparisons between
989 VALUE and values in ALIST are done using `eq' instead of `equal'.
991 - Function: copy-alist alist
992 This function returns a two-level deep copy of ALIST: it creates a
993 new copy of each association, so that you can alter the
994 associations of the new alist without changing the old one.
996 (setq needles-per-cluster
997 '((2 . ("Austrian Pine" "Red Pine"))
999 (5 . ("White Pine"))))
1001 ((2 "Austrian Pine" "Red Pine")
1005 (setq copy (copy-alist needles-per-cluster))
1007 ((2 "Austrian Pine" "Red Pine")
1011 (eq needles-per-cluster copy)
1013 (equal needles-per-cluster copy)
1015 (eq (car needles-per-cluster) (car copy))
1017 (cdr (car (cdr needles-per-cluster)))
1019 (eq (cdr (car (cdr needles-per-cluster)))
1020 (cdr (car (cdr copy))))
1023 This example shows how `copy-alist' makes it possible to change
1024 the associations of one copy without affecting the other:
1026 (setcdr (assq 3 copy) '("Martian Vacuum Pine"))
1027 (cdr (assq 3 needles-per-cluster))
1030 ---------- Footnotes ----------
1032 (1) This usage of "key" is not related to the term "key sequence";
1033 it means a value used to look up an item in a table. In this case, the
1034 table is the alist, and the alist associations are the items.
1037 File: lispref.info, Node: Property Lists, Next: Weak Lists, Prev: Association Lists, Up: Lists
1042 A "property list" (or "plist") is another way of representing a mapping
1043 from keys to values. Instead of the list consisting of conses of a key
1044 and a value, the keys and values alternate as successive entries in the
1045 list. Thus, the association list
1047 ((a . 1) (b . 2) (c . 3))
1049 has the equivalent property list form
1053 Property lists are used to represent the properties associated with
1054 various sorts of objects, such as symbols, strings, frames, etc. The
1055 convention is that property lists can be modified in-place, while
1056 association lists generally are not.
1058 Plists come in two varieties: "normal" plists, whose keys are
1059 compared with `eq', and "lax" plists, whose keys are compared with
1062 - Function: valid-plist-p plist
1063 Given a plist, this function returns non-`nil' if its format is
1064 correct. If it returns `nil', `check-valid-plist' will signal an
1065 error when given the plist; that means it's a malformed or circular
1066 plist or has non-symbols as keywords.
1068 - Function: check-valid-plist plist
1069 Given a plist, this function signals an error if there is anything
1070 wrong with it. This means that it's a malformed or circular plist.
1074 * Working With Normal Plists:: Functions for normal plists.
1075 * Working With Lax Plists:: Functions for lax plists.
1076 * Converting Plists To/From Alists:: Alist to plist and vice-versa.
1079 File: lispref.info, Node: Working With Normal Plists, Next: Working With Lax Plists, Up: Property Lists
1081 Working With Normal Plists
1082 --------------------------
1084 - Function: plist-get plist property &optional default
1085 This function extracts a value from a property list. The function
1086 returns the value corresponding to the given PROPERTY, or DEFAULT
1087 if PROPERTY is not one of the properties on the list.
1089 - Function: plist-put plist property value
1090 This function changes the value in PLIST of PROPERTY to VALUE. If
1091 PROPERTY is already a property on the list, its value is set to
1092 VALUE, otherwise the new PROPERTY VALUE pair is added. The new
1093 plist is returned; use `(setq x (plist-put x property value))' to
1094 be sure to use the new value. The PLIST is modified by side
1097 - Function: plist-remprop plist property
1098 This function removes from PLIST the property PROPERTY and its
1099 value. The new plist is returned; use `(setq x (plist-remprop x
1100 property))' to be sure to use the new value. The PLIST is
1101 modified by side effects.
1103 - Function: plist-member plist property
1104 This function returns `t' if PROPERTY has a value specified in
1107 In the following functions, if optional arg NIL-MEANS-NOT-PRESENT is
1108 non-`nil', then a property with a `nil' value is ignored or removed.
1109 This feature is a virus that has infected old Lisp implementations (and
1110 thus E-Lisp, due to RMS's enamorment with old Lisps), but should not be
1111 used except for backward compatibility.
1113 - Function: plists-eq a b &optional nil-means-not-present
1114 This function returns non-`nil' if property lists A and B are `eq'
1115 (i.e. their values are `eq').
1117 - Function: plists-equal a b &optional nil-means-not-present
1118 This function returns non-`nil' if property lists A and B are
1119 `equal' (i.e. their values are `equal'; their keys are still
1120 compared using `eq').
1122 - Function: canonicalize-plist plist &optional nil-means-not-present
1123 This function destructively removes any duplicate entries from a
1124 plist. In such cases, the first entry applies.
1126 The new plist is returned. If NIL-MEANS-NOT-PRESENT is given, the
1127 return value may not be `eq' to the passed-in value, so make sure
1128 to `setq' the value back into where it came from.
1131 File: lispref.info, Node: Working With Lax Plists, Next: Converting Plists To/From Alists, Prev: Working With Normal Plists, Up: Property Lists
1133 Working With Lax Plists
1134 -----------------------
1136 Recall that a "lax plist" is a property list whose keys are compared
1137 using `equal' instead of `eq'.
1139 - Function: lax-plist-get lax-plist property &optional default
1140 This function extracts a value from a lax property list. The
1141 function returns the value corresponding to the given PROPERTY, or
1142 DEFAULT if PROPERTY is not one of the properties on the list.
1144 - Function: lax-plist-put lax-plist property value
1145 This function changes the value in LAX-PLIST of PROPERTY to VALUE.
1147 - Function: lax-plist-remprop lax-plist property
1148 This function removes from LAX-PLIST the property PROPERTY and its
1149 value. The new plist is returned; use `(setq x (lax-plist-remprop
1150 x property))' to be sure to use the new value. The LAX-PLIST is
1151 modified by side effects.
1153 - Function: lax-plist-member lax-plist property
1154 This function returns `t' if PROPERTY has a value specified in
1157 In the following functions, if optional arg NIL-MEANS-NOT-PRESENT is
1158 non-`nil', then a property with a `nil' value is ignored or removed.
1159 This feature is a virus that has infected old Lisp implementations (and
1160 thus E-Lisp, due to RMS's enamorment with old Lisps), but should not be
1161 used except for backward compatibility.
1163 - Function: lax-plists-eq a b &optional nil-means-not-present
1164 This function returns non-`nil' if lax property lists A and B are
1165 `eq' (i.e. their values are `eq'; their keys are still compared
1168 - Function: lax-plists-equal a b &optional nil-means-not-present
1169 This function returns non-`nil' if lax property lists A and B are
1170 `equal' (i.e. their values are `equal').
1172 - Function: canonicalize-lax-plist lax-plist &optional
1173 nil-means-not-present
1174 This function destructively removes any duplicate entries from a
1175 lax plist. In such cases, the first entry applies.
1177 The new plist is returned. If NIL-MEANS-NOT-PRESENT is given, the
1178 return value may not be `eq' to the passed-in value, so make sure
1179 to `setq' the value back into where it came from.
1182 File: lispref.info, Node: Converting Plists To/From Alists, Prev: Working With Lax Plists, Up: Property Lists
1184 Converting Plists To/From Alists
1185 --------------------------------
1187 - Function: alist-to-plist alist
1188 This function converts association list ALIST into the equivalent
1189 property-list form. The plist is returned. This converts from
1191 ((a . 1) (b . 2) (c . 3))
1197 The original alist is not modified.
1199 - Function: plist-to-alist plist
1200 This function converts property list PLIST into the equivalent
1201 association-list form. The alist is returned. This converts from
1207 ((a . 1) (b . 2) (c . 3))
1209 The original plist is not modified.
1211 The following two functions are equivalent to the preceding two
1212 except that they destructively modify their arguments, using cons cells
1213 from the original list to form the new list rather than allocating new
1216 - Function: destructive-alist-to-plist alist
1217 This function destructively converts association list ALIST into
1218 the equivalent property-list form. The plist is returned.
1220 - Function: destructive-plist-to-alist plist
1221 This function destructively converts property list PLIST into the
1222 equivalent association-list form. The alist is returned.
1225 File: lispref.info, Node: Weak Lists, Prev: Property Lists, Up: Lists
1230 A "weak list" is a special sort of list whose members are not counted
1231 as references for the purpose of garbage collection. This means that,
1232 for any object in the list, if there are no references to the object
1233 anywhere outside of the list (or other weak list or weak hash table),
1234 that object will disappear the next time a garbage collection happens.
1235 Weak lists can be useful for keeping track of things such as unobtrusive
1236 lists of another function's buffers or markers. When that function is
1237 done with the elements, they will automatically disappear from the list.
1239 Weak lists are used internally, for example, to manage the list
1240 holding the children of an extent--an extent that is unused but has a
1241 parent will still be reclaimed, and will automatically be removed from
1242 its parent's list of children.
1244 Weak lists are similar to weak hash tables (*note Weak Hash
1247 - Function: weak-list-p object
1248 This function returns non-`nil' if OBJECT is a weak list.
1250 Weak lists come in one of four types:
1253 Objects in the list disappear if not referenced outside of the
1257 Objects in the list disappear if they are conses and either the
1258 car or the cdr of the cons is not referenced outside of the list.
1261 Objects in the list disappear if they are conses and the car is not
1262 referenced outside of the list.
1265 Objects in the list disappear if they are conses and the cdr is not
1266 referenced outside of the list.
1268 - Function: make-weak-list &optional type
1269 This function creates a new weak list of type TYPE. TYPE is a
1270 symbol (one of `simple', `assoc', `key-assoc', or `value-assoc',
1271 as described above) and defaults to `simple'.
1273 - Function: weak-list-type weak
1274 This function returns the type of the given weak-list object.
1276 - Function: weak-list-list weak
1277 This function returns the list contained in a weak-list object.
1279 - Function: set-weak-list-list weak new-list
1280 This function changes the list contained in a weak-list object.
1283 File: lispref.info, Node: Sequences Arrays Vectors, Next: Symbols, Prev: Lists, Up: Top
1285 Sequences, Arrays, and Vectors
1286 ******************************
1288 Recall that the "sequence" type is the union of four other Lisp types:
1289 lists, vectors, bit vectors, and strings. In other words, any list is
1290 a sequence, any vector is a sequence, any bit vector is a sequence, and
1291 any string is a sequence. The common property that all sequences have
1292 is that each is an ordered collection of elements.
1294 An "array" is a single primitive object that has a slot for each
1295 elements. All the elements are accessible in constant time, but the
1296 length of an existing array cannot be changed. Strings, vectors, and
1297 bit vectors are the three types of arrays.
1299 A list is a sequence of elements, but it is not a single primitive
1300 object; it is made of cons cells, one cell per element. Finding the
1301 Nth element requires looking through N cons cells, so elements farther
1302 from the beginning of the list take longer to access. But it is
1303 possible to add elements to the list, or remove elements.
1305 The following diagram shows the relationship between these types:
1307 ___________________________________
1310 | ______ ______________________ |
1312 | | List | | Array | |
1313 | | | | ________ _______ | |
1314 | |______| | | | | | | |
1315 | | | Vector | | String| | |
1316 | | |________| |_______| | |
1317 | | __________________ | |
1319 | | | Bit Vector | | |
1320 | | |__________________| | |
1321 | |______________________| |
1322 |___________________________________|
1324 The elements of vectors and lists may be any Lisp objects. The
1325 elements of strings are all characters. The elements of bit vectors
1326 are the numbers 0 and 1.
1330 * Sequence Functions:: Functions that accept any kind of sequence.
1331 * Arrays:: Characteristics of arrays in XEmacs Lisp.
1332 * Array Functions:: Functions specifically for arrays.
1333 * Vectors:: Special characteristics of XEmacs Lisp vectors.
1334 * Vector Functions:: Functions specifically for vectors.
1335 * Bit Vectors:: Special characteristics of XEmacs Lisp bit vectors.
1336 * Bit Vector Functions:: Functions specifically for bit vectors.
1339 File: lispref.info, Node: Sequence Functions, Next: Arrays, Up: Sequences Arrays Vectors
1344 In XEmacs Lisp, a "sequence" is either a list, a vector, a bit vector,
1345 or a string. The common property that all sequences have is that each
1346 is an ordered collection of elements. This section describes functions
1347 that accept any kind of sequence.
1349 - Function: sequencep object
1350 Returns `t' if OBJECT is a list, vector, bit vector, or string,
1353 - Function: copy-sequence sequence
1354 Returns a copy of SEQUENCE. The copy is the same type of object
1355 as the original sequence, and it has the same elements in the same
1358 Storing a new element into the copy does not affect the original
1359 SEQUENCE, and vice versa. However, the elements of the new
1360 sequence are not copies; they are identical (`eq') to the elements
1361 of the original. Therefore, changes made within these elements, as
1362 found via the copied sequence, are also visible in the original
1365 If the sequence is a string with extents or text properties, the
1366 extents and text properties in the copy are also copied, not
1367 shared with the original. (This means that modifying the extents
1368 or text properties of the original will not affect the copy.)
1369 However, the actual values of the properties are shared. *Note
1370 Extents::, *Note Text Properties::.
1372 See also `append' in *Note Building Lists::, `concat' in *Note
1373 Creating Strings::, `vconcat' in *Note Vectors::, and `bvconcat'
1374 in *Note Bit Vectors::, for other ways to copy sequences.
1378 (setq x (vector 'foo bar))
1380 (setq y (copy-sequence x))
1387 (eq (elt x 1) (elt y 1))
1390 ;; Replacing an element of one sequence.
1395 ;; Modifying the inside of a shared element.
1396 (setcar (aref x 1) 69)
1400 ;; Creating a bit vector.
1401 (bit-vector 1 0 1 1 0 1 0 0)
1404 - Function: length sequence
1405 Returns the number of elements in SEQUENCE. If SEQUENCE is a cons
1406 cell that is not a list (because the final CDR is not `nil'), a
1407 `wrong-type-argument' error is signaled.
1420 - Function: elt sequence index
1421 This function returns the element of SEQUENCE indexed by INDEX.
1422 Legitimate values of INDEX are integers ranging from 0 up to one
1423 less than the length of SEQUENCE. If SEQUENCE is a list, then
1424 out-of-range values of INDEX return `nil'; otherwise, they trigger
1425 an `args-out-of-range' error.
1431 (char-to-string (elt "1234" 2))
1436 error-->Args out of range: [1 2 3 4], 4
1438 error-->Args out of range: [1 2 3 4], -1
1440 This function generalizes `aref' (*note Array Functions::) and
1441 `nth' (*note List Elements::).
1444 File: lispref.info, Node: Arrays, Next: Array Functions, Prev: Sequence Functions, Up: Sequences Arrays Vectors
1449 An "array" object has slots that hold a number of other Lisp objects,
1450 called the elements of the array. Any element of an array may be
1451 accessed in constant time. In contrast, an element of a list requires
1452 access time that is proportional to the position of the element in the
1455 When you create an array, you must specify how many elements it has.
1456 The amount of space allocated depends on the number of elements.
1457 Therefore, it is impossible to change the size of an array once it is
1458 created; you cannot add or remove elements. However, you can replace an
1459 element with a different value.
1461 XEmacs defines three types of array, all of which are
1462 one-dimensional: "strings", "vectors", and "bit vectors". A vector is a
1463 general array; its elements can be any Lisp objects. A string is a
1464 specialized array; its elements must be characters. A bit vector is
1465 another specialized array; its elements must be bits (an integer, either
1466 0 or 1). Each type of array has its own read syntax. *Note String
1467 Type::, *Note Vector Type::, and *Note Bit Vector Type::.
1469 All kinds of array share these characteristics:
1471 * The first element of an array has index zero, the second element
1472 has index 1, and so on. This is called "zero-origin" indexing.
1473 For example, an array of four elements has indices 0, 1, 2, and 3.
1475 * The elements of an array may be referenced or changed with the
1476 functions `aref' and `aset', respectively (*note Array
1479 In principle, if you wish to have an array of text characters, you
1480 could use either a string or a vector. In practice, we always choose
1481 strings for such applications, for four reasons:
1483 * They usually occupy one-fourth the space of a vector of the same
1484 elements. (This is one-eighth the space for 64-bit machines such
1485 as the DEC Alpha, and may also be different when MULE support is
1486 compiled into XEmacs.)
1488 * Strings are printed in a way that shows the contents more clearly
1491 * Strings can hold extent and text properties. *Note Extents::,
1492 *Note Text Properties::.
1494 * Many of the specialized editing and I/O facilities of XEmacs
1495 accept only strings. For example, you cannot insert a vector of
1496 characters into a buffer the way you can insert a string. *Note
1497 Strings and Characters::.
1499 By contrast, for an array of keyboard input characters (such as a key
1500 sequence), a vector may be necessary, because many keyboard input
1501 characters are non-printable and are represented with symbols rather
1502 than with characters. *Note Key Sequence Input::.
1504 Similarly, when representing an array of bits, a bit vector has the
1505 following advantages over a regular vector:
1507 * They occupy 1/32nd the space of a vector of the same elements.
1508 (1/64th on 64-bit machines such as the DEC Alpha.)
1510 * Bit vectors are printed in a way that shows the contents more
1514 File: lispref.info, Node: Array Functions, Next: Vectors, Prev: Arrays, Up: Sequences Arrays Vectors
1516 Functions that Operate on Arrays
1517 ================================
1519 In this section, we describe the functions that accept strings, vectors,
1522 - Function: arrayp object
1523 This function returns `t' if OBJECT is an array (i.e., a string,
1524 vector, or bit vector).
1533 - Function: aref array index
1534 This function returns the INDEXth element of ARRAY. The first
1535 element is at index zero.
1537 (setq primes [2 3 5 7 11 13])
1550 See also the function `elt', in *Note Sequence Functions::.
1552 - Function: aset array index object
1553 This function sets the INDEXth element of ARRAY to be OBJECT. It
1556 (setq w [foo bar baz])
1577 If ARRAY is a string and OBJECT is not a character, a
1578 `wrong-type-argument' error results.
1580 - Function: fillarray array object
1581 This function fills the array ARRAY with OBJECT, so that each
1582 element of ARRAY is OBJECT. It returns ARRAY.
1584 (setq a [a b c d e f g])
1591 (setq s "When in the course")
1592 => "When in the course"
1594 => "------------------"
1601 If ARRAY is a string and OBJECT is not a character, a
1602 `wrong-type-argument' error results.
1604 The general sequence functions `copy-sequence' and `length' are
1605 often useful for objects known to be arrays. *Note Sequence
1609 File: lispref.info, Node: Vectors, Next: Vector Functions, Prev: Array Functions, Up: Sequences Arrays Vectors
1614 Arrays in Lisp, like arrays in most languages, are blocks of memory
1615 whose elements can be accessed in constant time. A "vector" is a
1616 general-purpose array; its elements can be any Lisp objects. (The other
1617 kind of array in XEmacs Lisp is the "string", whose elements must be
1618 characters.) Vectors in XEmacs serve as obarrays (vectors of symbols),
1619 although this is a shortcoming that should be fixed. They are also used
1620 internally as part of the representation of a byte-compiled function; if
1621 you print such a function, you will see a vector in it.
1623 In XEmacs Lisp, the indices of the elements of a vector start from
1624 zero and count up from there.
1626 Vectors are printed with square brackets surrounding the elements.
1627 Thus, a vector whose elements are the symbols `a', `b' and `a' is
1628 printed as `[a b a]'. You can write vectors in the same way in Lisp
1631 A vector, like a string or a number, is considered a constant for
1632 evaluation: the result of evaluating it is the same vector. This does
1633 not evaluate or even examine the elements of the vector. *Note
1634 Self-Evaluating Forms::.
1636 Here are examples of these principles:
1638 (setq avector [1 two '(three) "four" [five]])
1639 => [1 two (quote (three)) "four" [five]]
1641 => [1 two (quote (three)) "four" [five]]
1642 (eq avector (eval avector))
1646 File: lispref.info, Node: Vector Functions, Next: Bit Vectors, Prev: Vectors, Up: Sequences Arrays Vectors
1648 Functions That Operate on Vectors
1649 =================================
1651 Here are some functions that relate to vectors:
1653 - Function: vectorp object
1654 This function returns `t' if OBJECT is a vector.
1661 - Function: vector &rest objects
1662 This function creates and returns a vector whose elements are the
1665 (vector 'foo 23 [bar baz] "rats")
1666 => [foo 23 [bar baz] "rats"]
1670 - Function: make-vector length object
1671 This function returns a new vector consisting of LENGTH elements,
1672 each initialized to OBJECT.
1674 (setq sleepy (make-vector 9 'Z))
1675 => [Z Z Z Z Z Z Z Z Z]
1677 - Function: vconcat &rest sequences
1678 This function returns a new vector containing all the elements of
1679 the SEQUENCES. The arguments SEQUENCES may be lists, vectors, or
1680 strings. If no SEQUENCES are given, an empty vector is returned.
1682 The value is a newly constructed vector that is not `eq' to any
1685 (setq a (vconcat '(A B C) '(D E F)))
1691 (vconcat [A B C] "aa" '(foo (6 7)))
1692 => [A B C 97 97 foo (6 7)]
1694 The `vconcat' function also allows integers as arguments. It
1695 converts them to strings of digits, making up the decimal print
1696 representation of the integer, and then uses the strings instead
1697 of the original integers. *Don't use this feature; we plan to
1698 eliminate it. If you already use this feature, change your
1699 programs now!* The proper way to convert an integer to a decimal
1700 number in this way is with `format' (*note Formatting Strings::)
1701 or `number-to-string' (*note String Conversion::).
1703 For other concatenation functions, see `mapconcat' in *Note
1704 Mapping Functions::, `concat' in *Note Creating Strings::, `append'
1705 in *Note Building Lists::, and `bvconcat' in *Note Bit Vector
1708 The `append' function provides a way to convert a vector into a list
1709 with the same elements (*note Building Lists::):
1711 (setq avector [1 two (quote (three)) "four" [five]])
1712 => [1 two (quote (three)) "four" [five]]
1713 (append avector nil)
1714 => (1 two (quote (three)) "four" [five])
1717 File: lispref.info, Node: Bit Vectors, Next: Bit Vector Functions, Prev: Vector Functions, Up: Sequences Arrays Vectors
1722 Bit vectors are specialized vectors that can only represent arrays of
1723 1's and 0's. Bit vectors have a very efficient representation and are
1724 useful for representing sets of boolean (true or false) values.
1726 There is no limit on the size of a bit vector. You could, for
1727 example, create a bit vector with 100,000 elements if you really wanted
1730 Bit vectors have a special printed representation consisting of `#*'
1731 followed by the bits of the vector. For example, a bit vector whose
1732 elements are 0, 1, 1, 0, and 1, respectively, is printed as
1736 Bit vectors are considered constants for evaluation, like vectors,
1737 strings, and numbers. *Note Self-Evaluating Forms::.
1740 File: lispref.info, Node: Bit Vector Functions, Prev: Bit Vectors, Up: Sequences Arrays Vectors
1742 Functions That Operate on Bit Vectors
1743 =====================================
1745 Here are some functions that relate to bit vectors:
1747 - Function: bit-vector-p object
1748 This function returns `t' if OBJECT is a bit vector.
1752 (bit-vector-p [0 1])
1757 - Function: bitp object
1758 This function returns `t' if OBJECT is either 0 or 1.
1760 - Function: bit-vector &rest bits
1761 This function creates and returns a bit vector whose elements are
1762 the arguments BITS. Each argument must be a bit, i.e. one of the
1763 two integers 0 or 1.
1765 (bit-vector 0 0 0 1 0 0 0 0 1 0)
1770 - Function: make-bit-vector length bit
1771 This function creates and returns a bit vector consisting of
1772 LENGTH elements, each initialized to BIT, which must be one of the
1773 two integers 0 or 1.
1775 (setq picket-fence (make-bit-vector 9 1))
1778 - Function: bvconcat &rest sequences
1779 This function returns a new bit vector containing all the elements
1780 of the SEQUENCES. The arguments SEQUENCES may be lists, vectors,
1781 or bit vectors, all of whose elements are the integers 0 or 1. If
1782 no SEQUENCES are given, an empty bit vector is returned.
1784 The value is a newly constructed bit vector that is not `eq' to any
1785 existing bit vector.
1787 (setq a (bvconcat '(1 1 0) '(0 0 1)))
1793 (bvconcat [1 0 0 0 0] #*111 '(0 0 0 0 1))
1796 For other concatenation functions, see `mapconcat' in *Note
1797 Mapping Functions::, `concat' in *Note Creating Strings::,
1798 `vconcat' in *Note Vector Functions::, and `append' in *Note
1801 The `append' function provides a way to convert a bit vector into a
1802 list with the same elements (*note Building Lists::):
1804 (setq bv #*00001110)
1807 => (0 0 0 0 1 1 1 0)
1810 File: lispref.info, Node: Symbols, Next: Evaluation, Prev: Sequences Arrays Vectors, Up: Top
1815 A "symbol" is an object with a unique name. This chapter describes
1816 symbols, their components, their property lists, and how they are
1817 created and interned. Separate chapters describe the use of symbols as
1818 variables and as function names; see *Note Variables::, and *Note
1819 Functions::. For the precise read syntax for symbols, see *Note Symbol
1822 You can test whether an arbitrary Lisp object is a symbol with
1825 - Function: symbolp object
1826 This function returns `t' if OBJECT is a symbol, `nil' otherwise.
1830 * Symbol Components:: Symbols have names, values, function definitions
1832 * Definitions:: A definition says how a symbol will be used.
1833 * Creating Symbols:: How symbols are kept unique.
1834 * Symbol Properties:: Each symbol has a property list
1835 for recording miscellaneous information.
1838 File: lispref.info, Node: Symbol Components, Next: Definitions, Up: Symbols
1843 Each symbol has four components (or "cells"), each of which references
1847 The "print name cell" holds a string that names the symbol for
1848 reading and printing. See `symbol-name' in *Note Creating
1852 The "value cell" holds the current value of the symbol as a
1853 variable. When a symbol is used as a form, the value of the form
1854 is the contents of the symbol's value cell. See `symbol-value' in
1855 *Note Accessing Variables::.
1858 The "function cell" holds the function definition of the symbol.
1859 When a symbol is used as a function, its function definition is
1860 used in its place. This cell is also used to make a symbol stand
1861 for a keymap or a keyboard macro, for editor command execution.
1862 Because each symbol has separate value and function cells,
1863 variables and function names do not conflict. See
1864 `symbol-function' in *Note Function Cells::.
1867 The "property list cell" holds the property list of the symbol.
1868 See `symbol-plist' in *Note Symbol Properties::.
1870 The print name cell always holds a string, and cannot be changed.
1871 The other three cells can be set individually to any specified Lisp
1874 The print name cell holds the string that is the name of the symbol.
1875 Since symbols are represented textually by their names, it is important
1876 not to have two symbols with the same name. The Lisp reader ensures
1877 this: every time it reads a symbol, it looks for an existing symbol with
1878 the specified name before it creates a new one. (In XEmacs Lisp, this
1879 lookup uses a hashing algorithm and an obarray; see *Note Creating
1882 In normal usage, the function cell usually contains a function or
1883 macro, as that is what the Lisp interpreter expects to see there (*note
1884 Evaluation::). Keyboard macros (*note Keyboard Macros::), keymaps
1885 (*note Keymaps::) and autoload objects (*note Autoloading::) are also
1886 sometimes stored in the function cell of symbols. We often refer to
1887 "the function `foo'" when we really mean the function stored in the
1888 function cell of the symbol `foo'. We make the distinction only when
1891 The property list cell normally should hold a correctly formatted
1892 property list (*note Property Lists::), as a number of functions expect
1893 to see a property list there.
1895 The function cell or the value cell may be "void", which means that
1896 the cell does not reference any object. (This is not the same thing as
1897 holding the symbol `void', nor the same as holding the symbol `nil'.)
1898 Examining a cell that is void results in an error, such as `Symbol's
1899 value as variable is void'.
1901 The four functions `symbol-name', `symbol-value', `symbol-plist',
1902 and `symbol-function' return the contents of the four cells of a
1903 symbol. Here as an example we show the contents of the four cells of
1904 the symbol `buffer-file-name':
1906 (symbol-name 'buffer-file-name)
1907 => "buffer-file-name"
1908 (symbol-value 'buffer-file-name)
1909 => "/gnu/elisp/symbols.texi"
1910 (symbol-plist 'buffer-file-name)
1911 => (variable-documentation 29529)
1912 (symbol-function 'buffer-file-name)
1913 => #<subr buffer-file-name>
1915 Because this symbol is the variable which holds the name of the file
1916 being visited in the current buffer, the value cell contents we see are
1917 the name of the source file of this chapter of the XEmacs Lisp Reference
1918 Manual. The property list cell contains the list
1919 `(variable-documentation 29529)' which tells the documentation
1920 functions where to find the documentation string for the variable
1921 `buffer-file-name' in the `DOC' file. (29529 is the offset from the
1922 beginning of the `DOC' file to where that documentation string begins.)
1923 The function cell contains the function for returning the name of the
1924 file. `buffer-file-name' names a primitive function, which has no read
1925 syntax and prints in hash notation (*note Primitive Function Type::). A
1926 symbol naming a function written in Lisp would have a lambda expression
1927 (or a byte-code object) in this cell.
1930 File: lispref.info, Node: Definitions, Next: Creating Symbols, Prev: Symbol Components, Up: Symbols
1935 A "definition" in Lisp is a special form that announces your intention
1936 to use a certain symbol in a particular way. In XEmacs Lisp, you can
1937 define a symbol as a variable, or define it as a function (or macro),
1938 or both independently.
1940 A definition construct typically specifies a value or meaning for the
1941 symbol for one kind of use, plus documentation for its meaning when used
1942 in this way. Thus, when you define a symbol as a variable, you can
1943 supply an initial value for the variable, plus documentation for the
1946 `defvar' and `defconst' are special forms that define a symbol as a
1947 global variable. They are documented in detail in *Note Defining
1950 `defun' defines a symbol as a function, creating a lambda expression
1951 and storing it in the function cell of the symbol. This lambda
1952 expression thus becomes the function definition of the symbol. (The
1953 term "function definition", meaning the contents of the function cell,
1954 is derived from the idea that `defun' gives the symbol its definition
1955 as a function.) `defsubst', `define-function' and `defalias' are other
1956 ways of defining a function. *Note Functions::.
1958 `defmacro' defines a symbol as a macro. It creates a macro object
1959 and stores it in the function cell of the symbol. Note that a given
1960 symbol can be a macro or a function, but not both at once, because both
1961 macro and function definitions are kept in the function cell, and that
1962 cell can hold only one Lisp object at any given time. *Note Macros::.
1964 In XEmacs Lisp, a definition is not required in order to use a symbol
1965 as a variable or function. Thus, you can make a symbol a global
1966 variable with `setq', whether you define it first or not. The real
1967 purpose of definitions is to guide programmers and programming tools.
1968 They inform programmers who read the code that certain symbols are
1969 _intended_ to be used as variables, or as functions. In addition,
1970 utilities such as `etags' and `make-docfile' recognize definitions, and
1971 add appropriate information to tag tables and the `DOC' file. *Note
1972 Accessing Documentation::.
1975 File: lispref.info, Node: Creating Symbols, Next: Symbol Properties, Prev: Definitions, Up: Symbols
1977 Creating and Interning Symbols
1978 ==============================
1980 To understand how symbols are created in XEmacs Lisp, you must know how
1981 Lisp reads them. Lisp must ensure that it finds the same symbol every
1982 time it reads the same set of characters. Failure to do so would cause
1985 When the Lisp reader encounters a symbol, it reads all the characters
1986 of the name. Then it "hashes" those characters to find an index in a
1987 table called an "obarray". Hashing is an efficient method of looking
1988 something up. For example, instead of searching a telephone book cover
1989 to cover when looking up Jan Jones, you start with the J's and go from
1990 there. That is a simple version of hashing. Each element of the
1991 obarray is a "bucket" which holds all the symbols with a given hash
1992 code; to look for a given name, it is sufficient to look through all
1993 the symbols in the bucket for that name's hash code.
1995 If a symbol with the desired name is found, the reader uses that
1996 symbol. If the obarray does not contain a symbol with that name, the
1997 reader makes a new symbol and adds it to the obarray. Finding or adding
1998 a symbol with a certain name is called "interning" it, and the symbol
1999 is then called an "interned symbol".
2001 Interning ensures that each obarray has just one symbol with any
2002 particular name. Other like-named symbols may exist, but not in the
2003 same obarray. Thus, the reader gets the same symbols for the same
2004 names, as long as you keep reading with the same obarray.
2006 No obarray contains all symbols; in fact, some symbols are not in any
2007 obarray. They are called "uninterned symbols". An uninterned symbol
2008 has the same four cells as other symbols; however, the only way to gain
2009 access to it is by finding it in some other object or as the value of a
2012 In XEmacs Lisp, an obarray is actually a vector. Each element of the
2013 vector is a bucket; its value is either an interned symbol whose name
2014 hashes to that bucket, or 0 if the bucket is empty. Each interned
2015 symbol has an internal link (invisible to the user) to the next symbol
2016 in the bucket. Because these links are invisible, there is no way to
2017 find all the symbols in an obarray except using `mapatoms' (below).
2018 The order of symbols in a bucket is not significant.
2020 In an empty obarray, every element is 0, and you can create an
2021 obarray with `(make-vector LENGTH 0)'. *This is the only valid way to
2022 create an obarray.* Prime numbers as lengths tend to result in good
2023 hashing; lengths one less than a power of two are also good.
2025 *Do not try to put symbols in an obarray yourself.* This does not
2026 work--only `intern' can enter a symbol in an obarray properly. *Do not
2027 try to intern one symbol in two obarrays.* This would garble both
2028 obarrays, because a symbol has just one slot to hold the following
2029 symbol in the obarray bucket. The results would be unpredictable.
2031 It is possible for two different symbols to have the same name in
2032 different obarrays; these symbols are not `eq' or `equal'. However,
2033 this normally happens only as part of the abbrev mechanism (*note
2036 Common Lisp note: In Common Lisp, a single symbol may be interned
2037 in several obarrays.
2039 Most of the functions below take a name and sometimes an obarray as
2040 arguments. A `wrong-type-argument' error is signaled if the name is
2041 not a string, or if the obarray is not a vector.
2043 - Function: symbol-name symbol
2044 This function returns the string that is SYMBOL's name. For
2050 Changing the string by substituting characters, etc, does change
2051 the name of the symbol, but fails to update the obarray, so don't
2054 - Function: make-symbol name
2055 This function returns a newly-allocated, uninterned symbol whose
2056 name is NAME (which must be a string). Its value and function
2057 definition are void, and its property list is `nil'. In the
2058 example below, the value of `sym' is not `eq' to `foo' because it
2059 is a distinct uninterned symbol whose name is also `foo'.
2061 (setq sym (make-symbol "foo"))
2066 - Function: intern name &optional obarray
2067 This function returns the interned symbol whose name is NAME. If
2068 there is no such symbol in the obarray OBARRAY, `intern' creates a
2069 new one, adds it to the obarray, and returns it. If OBARRAY is
2070 omitted, the value of the global variable `obarray' is used.
2072 (setq sym (intern "foo"))
2077 (setq sym1 (intern "foo" other-obarray))
2082 - Function: intern-soft name &optional obarray
2083 This function returns the symbol in OBARRAY whose name is NAME, or
2084 `nil' if OBARRAY has no symbol with that name. Therefore, you can
2085 use `intern-soft' to test whether a symbol with a given name is
2086 already interned. If OBARRAY is omitted, the value of the global
2087 variable `obarray' is used.
2089 (intern-soft "frazzle") ; No such symbol exists.
2091 (make-symbol "frazzle") ; Create an uninterned one.
2093 (intern-soft "frazzle") ; That one cannot be found.
2095 (setq sym (intern "frazzle")) ; Create an interned one.
2097 (intern-soft "frazzle") ; That one can be found!
2099 (eq sym 'frazzle) ; And it is the same one.
2103 This variable is the standard obarray for use by `intern' and
2106 - Function: mapatoms function &optional obarray
2107 This function calls FUNCTION for each symbol in the obarray
2108 OBARRAY. It returns `nil'. If OBARRAY is omitted, it defaults to
2109 the value of `obarray', the standard obarray for ordinary symbols.
2113 (defun count-syms (s)
2114 (setq count (1+ count)))
2116 (mapatoms 'count-syms)
2121 See `documentation' in *Note Accessing Documentation::, for another
2122 example using `mapatoms'.
2124 - Function: unintern symbol &optional obarray
2125 This function deletes SYMBOL from the obarray OBARRAY. If
2126 `symbol' is not actually in the obarray, `unintern' does nothing.
2127 If OBARRAY is `nil', the current obarray is used.
2129 If you provide a string instead of a symbol as SYMBOL, it stands
2130 for a symbol name. Then `unintern' deletes the symbol (if any) in
2131 the obarray which has that name. If there is no such symbol,
2132 `unintern' does nothing.
2134 If `unintern' does delete a symbol, it returns `t'. Otherwise it
2138 File: lispref.info, Node: Symbol Properties, Prev: Creating Symbols, Up: Symbols
2143 A "property list" ("plist" for short) is a list of paired elements,
2144 often stored in the property list cell of a symbol. Each of the pairs
2145 associates a property name (usually a symbol) with a property or value.
2146 Property lists are generally used to record information about a
2147 symbol, such as its documentation as a variable, the name of the file
2148 where it was defined, or perhaps even the grammatical class of the
2149 symbol (representing a word) in a language-understanding system.
2151 Some objects which are not symbols also have property lists
2152 associated with them, and XEmacs provides a full complement of
2153 functions for working with property lists. *Note Property Lists::.
2155 The property names and values in a property list can be any Lisp
2156 objects, but the names are usually symbols. They are compared using
2157 `eq'. Here is an example of a property list, found on the symbol
2158 `progn' when the compiler is loaded:
2160 (lisp-indent-function 0 byte-compile byte-compile-progn)
2162 Here `lisp-indent-function' and `byte-compile' are property names, and
2163 the other two elements are the corresponding values.
2167 * Plists and Alists:: Comparison of the advantages of property
2168 lists and association lists.
2169 * Object Plists:: Functions to access objects' property lists.
2170 * Other Plists:: Accessing property lists stored elsewhere.
2173 File: lispref.info, Node: Plists and Alists, Next: Object Plists, Up: Symbol Properties
2175 Property Lists and Association Lists
2176 ------------------------------------
2178 Association lists (*note Association Lists::) are very similar to
2179 property lists. In contrast to association lists, the order of the
2180 pairs in the property list is not significant since the property names
2183 Property lists are better than association lists for attaching
2184 information to various Lisp function names or variables. If all the
2185 associations are recorded in one association list, the program will need
2186 to search that entire list each time a function or variable is to be
2187 operated on. By contrast, if the information is recorded in the
2188 property lists of the function names or variables themselves, each
2189 search will scan only the length of one property list, which is usually
2190 short. This is why the documentation for a variable is recorded in a
2191 property named `variable-documentation'. The byte compiler likewise
2192 uses properties to record those functions needing special treatment.
2194 However, association lists have their own advantages. Depending on
2195 your application, it may be faster to add an association to the front of
2196 an association list than to update a property. All properties for a
2197 symbol are stored in the same property list, so there is a possibility
2198 of a conflict between different uses of a property name. (For this
2199 reason, it is a good idea to choose property names that are probably
2200 unique, such as by including the name of the library in the property
2201 name.) An association list may be used like a stack where associations
2202 are pushed on the front of the list and later discarded; this is not
2203 possible with a property list.
2206 File: lispref.info, Node: Object Plists, Next: Other Plists, Prev: Plists and Alists, Up: Symbol Properties
2208 Property List Functions for Objects
2209 -----------------------------------
2211 Once upon a time, only symbols had property lists. Now, several other
2212 object types, including strings, extents, faces and glyphs also have
2215 - Function: symbol-plist symbol
2216 This function returns the property list of SYMBOL.
2218 - Function: object-plist object
2219 This function returns the property list of OBJECT. If OBJECT is a
2220 symbol, this is identical to `symbol-plist'.
2222 - Function: setplist symbol plist
2223 This function sets SYMBOL's property list to PLIST. Normally,
2224 PLIST should be a well-formed property list, but this is not
2227 (setplist 'foo '(a 1 b (2 3) c nil))
2228 => (a 1 b (2 3) c nil)
2230 => (a 1 b (2 3) c nil)
2232 For symbols in special obarrays, which are not used for ordinary
2233 purposes, it may make sense to use the property list cell in a
2234 nonstandard fashion; in fact, the abbrev mechanism does so (*note
2235 Abbrevs::). But generally, its use is discouraged. Use `put'
2236 instead. `setplist' can only be used with symbols, not other
2239 - Function: get object property &optional default
2240 This function finds the value of the property named PROPERTY in
2241 OBJECT's property list. If there is no such property, `default'
2242 (which itself defaults to `nil') is returned.
2244 PROPERTY is compared with the existing properties using `eq', so
2245 any object is a legitimate property.
2247 See `put' for an example.
2249 - Function: put object property value
2250 This function puts VALUE onto OBJECT's property list under the
2251 property name PROPERTY, replacing any previous property value.
2252 The `put' function returns VALUE.
2254 (put 'fly 'verb 'transitive)
2256 (put 'fly 'noun '(a buzzing little bug))
2257 => (a buzzing little bug)
2261 => (verb transitive noun (a buzzing little bug))
2263 - Function: remprop object property
2264 This function removes the entry for PROPERTY from the property
2265 list of OBJECT. It returns `t' if the property was indeed found
2266 and removed, or `nil' if there was no such property. (This
2267 function was probably omitted from Emacs originally because, since
2268 `get' did not allow a DEFAULT, it was very difficult to
2269 distinguish between a missing property and a property whose value
2270 was `nil'; thus, setting a property to `nil' was close enough to
2271 `remprop' for most purposes.)
2274 File: lispref.info, Node: Other Plists, Prev: Object Plists, Up: Symbol Properties
2276 Property Lists Not Associated with Objects
2277 ------------------------------------------
2279 These functions are useful for manipulating property lists that are
2280 stored in places other than symbols:
2282 - Function: getf plist property &optional default
2283 This returns the value of the PROPERTY property stored in the
2284 property list PLIST. For example,
2286 (getf '(foo 4) 'foo)
2289 - Macro: putf plist property value
2290 This stores VALUE as the value of the PROPERTY property in the
2291 property list PLIST. It may modify PLIST destructively, or it may
2292 construct a new list structure without altering the old. The
2293 function returns the modified property list, so you can store that
2294 back in the place where you got PLIST. For example,
2296 (setq my-plist '(bar t foo 4))
2298 (setq my-plist (putf my-plist 'foo 69))
2300 (setq my-plist (putf my-plist 'quux '(a)))
2301 => (quux (a) bar t foo 5)
2303 - Function: plists-eq a b
2304 This function returns non-`nil' if property lists A and B are
2305 `eq'. This means that the property lists have the same values for
2306 all the same properties, where comparison between values is done
2309 - Function: plists-equal a b
2310 This function returns non-`nil' if property lists A and B are
2313 Both of the above functions do order-insensitive comparisons.
2315 (plists-eq '(a 1 b 2 c nil) '(b 2 a 1))
2317 (plists-eq '(foo "hello" bar "goodbye") '(bar "goodbye" foo "hello"))
2319 (plists-equal '(foo "hello" bar "goodbye") '(bar "goodbye" foo "hello"))
2323 File: lispref.info, Node: Evaluation, Next: Control Structures, Prev: Symbols, Up: Top
2328 The "evaluation" of expressions in XEmacs Lisp is performed by the
2329 "Lisp interpreter"--a program that receives a Lisp object as input and
2330 computes its "value as an expression". How it does this depends on the
2331 data type of the object, according to rules described in this chapter.
2332 The interpreter runs automatically to evaluate portions of your
2333 program, but can also be called explicitly via the Lisp primitive
2338 * Intro Eval:: Evaluation in the scheme of things.
2339 * Eval:: How to invoke the Lisp interpreter explicitly.
2340 * Forms:: How various sorts of objects are evaluated.
2341 * Quoting:: Avoiding evaluation (to put constants in the program).
2344 File: lispref.info, Node: Intro Eval, Next: Eval, Up: Evaluation
2346 Introduction to Evaluation
2347 ==========================
2349 The Lisp interpreter, or evaluator, is the program that computes the
2350 value of an expression that is given to it. When a function written in
2351 Lisp is called, the evaluator computes the value of the function by
2352 evaluating the expressions in the function body. Thus, running any
2353 Lisp program really means running the Lisp interpreter.
2355 How the evaluator handles an object depends primarily on the data
2358 A Lisp object that is intended for evaluation is called an
2359 "expression" or a "form". The fact that expressions are data objects
2360 and not merely text is one of the fundamental differences between
2361 Lisp-like languages and typical programming languages. Any object can
2362 be evaluated, but in practice only numbers, symbols, lists and strings
2363 are evaluated very often.
2365 It is very common to read a Lisp expression and then evaluate the
2366 expression, but reading and evaluation are separate activities, and
2367 either can be performed alone. Reading per se does not evaluate
2368 anything; it converts the printed representation of a Lisp object to the
2369 object itself. It is up to the caller of `read' whether this object is
2370 a form to be evaluated, or serves some entirely different purpose.
2371 *Note Input Functions::.
2373 Do not confuse evaluation with command key interpretation. The
2374 editor command loop translates keyboard input into a command (an
2375 interactively callable function) using the active keymaps, and then
2376 uses `call-interactively' to invoke the command. The execution of the
2377 command itself involves evaluation if the command is written in Lisp,
2378 but that is not a part of command key interpretation itself. *Note
2381 Evaluation is a recursive process. That is, evaluation of a form may
2382 call `eval' to evaluate parts of the form. For example, evaluation of
2383 a function call first evaluates each argument of the function call, and
2384 then evaluates each form in the function body. Consider evaluation of
2385 the form `(car x)': the subform `x' must first be evaluated
2386 recursively, so that its value can be passed as an argument to the
2389 Evaluation of a function call ultimately calls the function specified
2390 in it. *Note Functions::. The execution of the function may itself
2391 work by evaluating the function definition; or the function may be a
2392 Lisp primitive implemented in C, or it may be a byte-compiled function
2393 (*note Byte Compilation::).
2395 The evaluation of forms takes place in a context called the
2396 "environment", which consists of the current values and bindings of all
2397 Lisp variables.(1) Whenever the form refers to a variable without
2398 creating a new binding for it, the value of the binding in the current
2399 environment is used. *Note Variables::.
2401 Evaluation of a form may create new environments for recursive
2402 evaluation by binding variables (*note Local Variables::). These
2403 environments are temporary and vanish by the time evaluation of the form
2404 is complete. The form may also make changes that persist; these changes
2405 are called "side effects". An example of a form that produces side
2406 effects is `(setq foo 1)'.
2408 The details of what evaluation means for each kind of form are
2409 described below (*note Forms::).
2411 ---------- Footnotes ----------
2413 (1) This definition of "environment" is specifically not intended to
2414 include all the data that can affect the result of a program.
2417 File: lispref.info, Node: Eval, Next: Forms, Prev: Intro Eval, Up: Evaluation
2422 Most often, forms are evaluated automatically, by virtue of their
2423 occurrence in a program being run. On rare occasions, you may need to
2424 write code that evaluates a form that is computed at run time, such as
2425 after reading a form from text being edited or getting one from a
2426 property list. On these occasions, use the `eval' function.
2428 *Please note:* it is generally cleaner and more flexible to call
2429 functions that are stored in data structures, rather than to evaluate
2430 expressions stored in data structures. Using functions provides the
2431 ability to pass information to them as arguments.
2433 The functions and variables described in this section evaluate forms,
2434 specify limits to the evaluation process, or record recently returned
2435 values. Loading a file also does evaluation (*note Loading::).
2437 - Function: eval form
2438 This is the basic function for performing evaluation. It evaluates
2439 FORM in the current environment and returns the result. How the
2440 evaluation proceeds depends on the type of the object (*note
2443 Since `eval' is a function, the argument expression that appears
2444 in a call to `eval' is evaluated twice: once as preparation before
2445 `eval' is called, and again by the `eval' function itself. Here
2452 ;; `eval' receives argument `bar', which is the value of `foo'
2458 The number of currently active calls to `eval' is limited to
2459 `max-lisp-eval-depth' (see below).
2461 - Command: eval-region start end &optional stream
2462 This function evaluates the forms in the current buffer in the
2463 region defined by the positions START and END. It reads forms from
2464 the region and calls `eval' on them until the end of the region is
2465 reached, or until an error is signaled and not handled.
2467 If STREAM is supplied, `standard-output' is bound to it during the
2470 You can use the variable `load-read-function' to specify a function
2471 for `eval-region' to use instead of `read' for reading
2472 expressions. *Note How Programs Do Loading::.
2474 `eval-region' always returns `nil'.
2476 - Command: eval-buffer buffer &optional stream
2477 This is like `eval-region' except that it operates on the whole
2480 - Variable: max-lisp-eval-depth
2481 This variable defines the maximum depth allowed in calls to `eval',
2482 `apply', and `funcall' before an error is signaled (with error
2483 message `"Lisp nesting exceeds max-lisp-eval-depth"'). This counts
2484 internal uses of those functions, such as for calling the functions
2485 mentioned in Lisp expressions, and recursive evaluation of
2486 function call arguments and function body forms.
2488 This limit, with the associated error when it is exceeded, is one
2489 way that Lisp avoids infinite recursion on an ill-defined function.
2491 The default value of this variable is 1000. If you set it to a
2492 value less than 100, Lisp will reset it to 100 if the given value
2495 `max-specpdl-size' provides another limit on nesting. *Note Local
2499 The value of this variable is a list of the values returned by all
2500 the expressions that were read from buffers (including the
2501 minibuffer), evaluated, and printed. The elements are ordered
2506 (list 'A (1+ 2) auto-save-default)
2511 This variable is useful for referring back to values of forms
2512 recently evaluated. It is generally a bad idea to print the value
2513 of `values' itself, since this may be very long. Instead, examine
2514 particular elements, like this:
2516 ;; Refer to the most recent evaluation result.
2519 ;; That put a new element on,
2520 ;; so all elements move back one.
2523 ;; This gets the element that was next-to-most-recent
2524 ;; before this example.
2529 File: lispref.info, Node: Forms, Next: Quoting, Prev: Eval, Up: Evaluation
2534 A Lisp object that is intended to be evaluated is called a "form". How
2535 XEmacs evaluates a form depends on its data type. XEmacs has three
2536 different kinds of form that are evaluated differently: symbols, lists,
2537 and "all other types". This section describes all three kinds,
2538 starting with "all other types" which are self-evaluating forms.
2542 * Self-Evaluating Forms:: Forms that evaluate to themselves.
2543 * Symbol Forms:: Symbols evaluate as variables.
2544 * Classifying Lists:: How to distinguish various sorts of list forms.
2545 * Function Indirection:: When a symbol appears as the car of a list,
2546 we find the real function via the symbol.
2547 * Function Forms:: Forms that call functions.
2548 * Macro Forms:: Forms that call macros.
2549 * Special Forms:: ``Special forms'' are idiosyncratic primitives,
2550 most of them extremely important.
2551 * Autoloading:: Functions set up to load files
2552 containing their real definitions.
2555 File: lispref.info, Node: Self-Evaluating Forms, Next: Symbol Forms, Up: Forms
2557 Self-Evaluating Forms
2558 ---------------------
2560 A "self-evaluating form" is any form that is not a list or symbol.
2561 Self-evaluating forms evaluate to themselves: the result of evaluation
2562 is the same object that was evaluated. Thus, the number 25 evaluates to
2563 25, and the string `"foo"' evaluates to the string `"foo"'. Likewise,
2564 evaluation of a vector does not cause evaluation of the elements of the
2565 vector--it returns the same vector with its contents unchanged.
2567 '123 ; An object, shown without evaluation.
2569 123 ; Evaluated as usual--result is the same.
2571 (eval '123) ; Evaluated "by hand"--result is the same.
2573 (eval (eval '123)) ; Evaluating twice changes nothing.
2576 It is common to write numbers, characters, strings, and even vectors
2577 in Lisp code, taking advantage of the fact that they self-evaluate.
2578 However, it is quite unusual to do this for types that lack a read
2579 syntax, because there's no way to write them textually. It is possible
2580 to construct Lisp expressions containing these types by means of a Lisp
2581 program. Here is an example:
2583 ;; Build an expression containing a buffer object.
2584 (setq buffer (list 'print (current-buffer)))
2585 => (print #<buffer eval.texi>)
2588 -| #<buffer eval.texi>
2589 => #<buffer eval.texi>
2592 File: lispref.info, Node: Symbol Forms, Next: Classifying Lists, Prev: Self-Evaluating Forms, Up: Forms
2597 When a symbol is evaluated, it is treated as a variable. The result is
2598 the variable's value, if it has one. If it has none (if its value cell
2599 is void), an error is signaled. For more information on the use of
2600 variables, see *Note Variables::.
2602 In the following example, we set the value of a symbol with `setq'.
2603 Then we evaluate the symbol, and get back the value that `setq' stored.
2612 The symbols `nil' and `t' are treated specially, so that the value
2613 of `nil' is always `nil', and the value of `t' is always `t'; you
2614 cannot set or bind them to any other values. Thus, these two symbols
2615 act like self-evaluating forms, even though `eval' treats them like any
2619 File: lispref.info, Node: Classifying Lists, Next: Function Indirection, Prev: Symbol Forms, Up: Forms
2621 Classification of List Forms
2622 ----------------------------
2624 A form that is a nonempty list is either a function call, a macro call,
2625 or a special form, according to its first element. These three kinds
2626 of forms are evaluated in different ways, described below. The
2627 remaining list elements constitute the "arguments" for the function,
2628 macro, or special form.
2630 The first step in evaluating a nonempty list is to examine its first
2631 element. This element alone determines what kind of form the list is
2632 and how the rest of the list is to be processed. The first element is
2633 _not_ evaluated, as it would be in some Lisp dialects such as Scheme.
2636 File: lispref.info, Node: Function Indirection, Next: Function Forms, Prev: Classifying Lists, Up: Forms
2638 Symbol Function Indirection
2639 ---------------------------
2641 If the first element of the list is a symbol then evaluation examines
2642 the symbol's function cell, and uses its contents instead of the
2643 original symbol. If the contents are another symbol, this process,
2644 called "symbol function indirection", is repeated until it obtains a
2645 non-symbol. *Note Function Names::, for more information about using a
2646 symbol as a name for a function stored in the function cell of the
2649 One possible consequence of this process is an infinite loop, in the
2650 event that a symbol's function cell refers to the same symbol. Or a
2651 symbol may have a void function cell, in which case the subroutine
2652 `symbol-function' signals a `void-function' error. But if neither of
2653 these things happens, we eventually obtain a non-symbol, which ought to
2654 be a function or other suitable object.
2656 More precisely, we should now have a Lisp function (a lambda
2657 expression), a byte-code function, a primitive function, a Lisp macro, a
2658 special form, or an autoload object. Each of these types is a case
2659 described in one of the following sections. If the object is not one of
2660 these types, the error `invalid-function' is signaled.
2662 The following example illustrates the symbol indirection process. We
2663 use `fset' to set the function cell of a symbol and `symbol-function'
2664 to get the function cell contents (*note Function Cells::).
2665 Specifically, we store the symbol `car' into the function cell of
2666 `first', and the symbol `first' into the function cell of `erste'.
2668 ;; Build this function cell linkage:
2669 ;; ------------- ----- ------- -------
2670 ;; | #<subr car> | <-- | car | <-- | first | <-- | erste |
2671 ;; ------------- ----- ------- -------
2673 (symbol-function 'car)
2677 (fset 'erste 'first)
2679 (erste '(1 2 3)) ; Call the function referenced by `erste'.
2682 By contrast, the following example calls a function without any
2683 symbol function indirection, because the first element is an anonymous
2684 Lisp function, not a symbol.
2686 ((lambda (arg) (erste arg))
2690 Executing the function itself evaluates its body; this does involve
2691 symbol function indirection when calling `erste'.
2693 The built-in function `indirect-function' provides an easy way to
2694 perform symbol function indirection explicitly.
2696 - Function: indirect-function object
2697 This function returns the meaning of OBJECT as a function. If
2698 OBJECT is a symbol, then it finds OBJECT's function definition and
2699 starts over with that value. If OBJECT is not a symbol, then it
2700 returns OBJECT itself.
2702 Here is how you could define `indirect-function' in Lisp:
2704 (defun indirect-function (function)
2705 (if (symbolp function)
2706 (indirect-function (symbol-function function))
2710 File: lispref.info, Node: Function Forms, Next: Macro Forms, Prev: Function Indirection, Up: Forms
2712 Evaluation of Function Forms
2713 ----------------------------
2715 If the first element of a list being evaluated is a Lisp function
2716 object, byte-code object or primitive function object, then that list is
2717 a "function call". For example, here is a call to the function `+':
2721 The first step in evaluating a function call is to evaluate the
2722 remaining elements of the list from left to right. The results are the
2723 actual argument values, one value for each list element. The next step
2724 is to call the function with this list of arguments, effectively using
2725 the function `apply' (*note Calling Functions::). If the function is
2726 written in Lisp, the arguments are used to bind the argument variables
2727 of the function (*note Lambda Expressions::); then the forms in the
2728 function body are evaluated in order, and the value of the last body
2729 form becomes the value of the function call.
2732 File: lispref.info, Node: Macro Forms, Next: Special Forms, Prev: Function Forms, Up: Forms
2734 Lisp Macro Evaluation
2735 ---------------------
2737 If the first element of a list being evaluated is a macro object, then
2738 the list is a "macro call". When a macro call is evaluated, the
2739 elements of the rest of the list are _not_ initially evaluated.
2740 Instead, these elements themselves are used as the arguments of the
2741 macro. The macro definition computes a replacement form, called the
2742 "expansion" of the macro, to be evaluated in place of the original
2743 form. The expansion may be any sort of form: a self-evaluating
2744 constant, a symbol, or a list. If the expansion is itself a macro call,
2745 this process of expansion repeats until some other sort of form results.
2747 Ordinary evaluation of a macro call finishes by evaluating the
2748 expansion. However, the macro expansion is not necessarily evaluated
2749 right away, or at all, because other programs also expand macro calls,
2750 and they may or may not evaluate the expansions.
2752 Normally, the argument expressions are not evaluated as part of
2753 computing the macro expansion, but instead appear as part of the
2754 expansion, so they are computed when the expansion is computed.
2756 For example, given a macro defined as follows:
2759 (list 'car (list 'cdr x)))
2761 an expression such as `(cadr (assq 'handler list))' is a macro call,
2762 and its expansion is:
2764 (car (cdr (assq 'handler list)))
2766 Note that the argument `(assq 'handler list)' appears in the expansion.
2768 *Note Macros::, for a complete description of XEmacs Lisp macros.
2771 File: lispref.info, Node: Special Forms, Next: Autoloading, Prev: Macro Forms, Up: Forms
2776 A "special form" is a primitive function specially marked so that its
2777 arguments are not all evaluated. Most special forms define control
2778 structures or perform variable bindings--things which functions cannot
2781 Each special form has its own rules for which arguments are evaluated
2782 and which are used without evaluation. Whether a particular argument is
2783 evaluated may depend on the results of evaluating other arguments.
2785 Here is a list, in alphabetical order, of all of the special forms in
2786 XEmacs Lisp with a reference to where each is described.
2789 *note Combining Conditions::
2792 *note Catch and Throw::
2795 *note Conditionals::
2798 *note Handling Errors::
2801 *note Defining Variables::
2804 *note Defining Macros::
2807 *note Defining Functions::
2810 *note Defining Variables::
2813 *note Anonymous Functions::
2816 *note Conditionals::
2819 *note Interactive Call::
2823 *note Local Variables::
2826 *note Combining Conditions::
2836 `save-current-buffer'
2845 `save-selected-window'
2848 `save-window-excursion'
2849 *note Window Configurations::
2852 *note Setting Variables::
2855 *note Creating Buffer-Local::
2858 *note Nonlocal Exits::
2863 `with-output-to-temp-buffer'
2864 *note Temporary Displays::
2866 Common Lisp note: here are some comparisons of special forms in
2867 XEmacs Lisp and Common Lisp. `setq', `if', and `catch' are
2868 special forms in both XEmacs Lisp and Common Lisp. `defun' is a
2869 special form in XEmacs Lisp, but a macro in Common Lisp.
2870 `save-excursion' is a special form in XEmacs Lisp, but doesn't
2871 exist in Common Lisp. `throw' is a special form in Common Lisp
2872 (because it must be able to throw multiple values), but it is a
2873 function in XEmacs Lisp (which doesn't have multiple values).
2876 File: lispref.info, Node: Autoloading, Prev: Special Forms, Up: Forms
2881 The "autoload" feature allows you to call a function or macro whose
2882 function definition has not yet been loaded into XEmacs. It specifies
2883 which file contains the definition. When an autoload object appears as
2884 a symbol's function definition, calling that symbol as a function
2885 automatically loads the specified file; then it calls the real
2886 definition loaded from that file. *Note Autoload::.
2889 File: lispref.info, Node: Quoting, Prev: Forms, Up: Evaluation
2894 The special form `quote' returns its single argument, as written,
2895 without evaluating it. This provides a way to include constant symbols
2896 and lists, which are not self-evaluating objects, in a program. (It is
2897 not necessary to quote self-evaluating objects such as numbers, strings,
2900 - Special Form: quote object
2901 This special form returns OBJECT, without evaluating it.
2903 Because `quote' is used so often in programs, Lisp provides a
2904 convenient read syntax for it. An apostrophe character (`'') followed
2905 by a Lisp object (in read syntax) expands to a list whose first element
2906 is `quote', and whose second element is the object. Thus, the read
2907 syntax `'x' is an abbreviation for `(quote x)'.
2909 Here are some examples of expressions that use `quote':
2924 Other quoting constructs include `function' (*note Anonymous
2925 Functions::), which causes an anonymous lambda expression written in
2926 Lisp to be compiled, and ``' (*note Backquote::), which is used to quote
2927 only part of a list, while computing and substituting other parts.
2930 File: lispref.info, Node: Control Structures, Next: Variables, Prev: Evaluation, Up: Top
2935 A Lisp program consists of expressions or "forms" (*note Forms::). We
2936 control the order of execution of the forms by enclosing them in
2937 "control structures". Control structures are special forms which
2938 control when, whether, or how many times to execute the forms they
2941 The simplest order of execution is sequential execution: first form
2942 A, then form B, and so on. This is what happens when you write several
2943 forms in succession in the body of a function, or at top level in a
2944 file of Lisp code--the forms are executed in the order written. We
2945 call this "textual order". For example, if a function body consists of
2946 two forms A and B, evaluation of the function evaluates first A and
2947 then B, and the function's value is the value of B.
2949 Explicit control structures make possible an order of execution other
2952 XEmacs Lisp provides several kinds of control structure, including
2953 other varieties of sequencing, conditionals, iteration, and (controlled)
2954 jumps--all discussed below. The built-in control structures are
2955 special forms since their subforms are not necessarily evaluated or not
2956 evaluated sequentially. You can use macros to define your own control
2957 structure constructs (*note Macros::).
2961 * Sequencing:: Evaluation in textual order.
2962 * Conditionals:: `if', `cond'.
2963 * Combining Conditions:: `and', `or', `not'.
2964 * Iteration:: `while' loops.
2965 * Nonlocal Exits:: Jumping out of a sequence.
2968 File: lispref.info, Node: Sequencing, Next: Conditionals, Up: Control Structures
2973 Evaluating forms in the order they appear is the most common way
2974 control passes from one form to another. In some contexts, such as in a
2975 function body, this happens automatically. Elsewhere you must use a
2976 control structure construct to do this: `progn', the simplest control
2979 A `progn' special form looks like this:
2983 and it says to execute the forms A, B, C and so on, in that order.
2984 These forms are called the body of the `progn' form. The value of the
2985 last form in the body becomes the value of the entire `progn'.
2987 In the early days of Lisp, `progn' was the only way to execute two
2988 or more forms in succession and use the value of the last of them. But
2989 programmers found they often needed to use a `progn' in the body of a
2990 function, where (at that time) only one form was allowed. So the body
2991 of a function was made into an "implicit `progn'": several forms are
2992 allowed just as in the body of an actual `progn'. Many other control
2993 structures likewise contain an implicit `progn'. As a result, `progn'
2994 is not used as often as it used to be. It is needed now most often
2995 inside an `unwind-protect', `and', `or', or in the THEN-part of an `if'.
2997 - Special Form: progn forms...
2998 This special form evaluates all of the FORMS, in textual order,
2999 returning the result of the final form.
3001 (progn (print "The first form")
3002 (print "The second form")
3003 (print "The third form"))
3005 -| "The second form"
3009 Two other control constructs likewise evaluate a series of forms but
3010 return a different value:
3012 - Special Form: prog1 form1 forms...
3013 This special form evaluates FORM1 and all of the FORMS, in textual
3014 order, returning the result of FORM1.
3016 (prog1 (print "The first form")
3017 (print "The second form")
3018 (print "The third form"))
3020 -| "The second form"
3024 Here is a way to remove the first element from a list in the
3025 variable `x', then return the value of that former element:
3027 (prog1 (car x) (setq x (cdr x)))
3029 - Special Form: prog2 form1 form2 forms...
3030 This special form evaluates FORM1, FORM2, and all of the following
3031 FORMS, in textual order, returning the result of FORM2.
3033 (prog2 (print "The first form")
3034 (print "The second form")
3035 (print "The third form"))
3037 -| "The second form"
3039 => "The second form"
3042 File: lispref.info, Node: Conditionals, Next: Combining Conditions, Prev: Sequencing, Up: Control Structures
3047 Conditional control structures choose among alternatives. XEmacs Lisp
3048 has two conditional forms: `if', which is much the same as in other
3049 languages, and `cond', which is a generalized case statement.
3051 - Special Form: if condition then-form else-forms...
3052 `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
3053 value of CONDITION. If the evaluated CONDITION is non-`nil',
3054 THEN-FORM is evaluated and the result returned. Otherwise, the
3055 ELSE-FORMS are evaluated in textual order, and the value of the
3056 last one is returned. (The ELSE part of `if' is an example of an
3057 implicit `progn'. *Note Sequencing::.)
3059 If CONDITION has the value `nil', and no ELSE-FORMS are given,
3062 `if' is a special form because the branch that is not selected is
3063 never evaluated--it is ignored. Thus, in the example below,
3064 `true' is not printed because `print' is never called.
3071 - Special Form: cond clause...
3072 `cond' chooses among an arbitrary number of alternatives. Each
3073 CLAUSE in the `cond' must be a list. The CAR of this list is the
3074 CONDITION; the remaining elements, if any, the BODY-FORMS. Thus,
3075 a clause looks like this:
3077 (CONDITION BODY-FORMS...)
3079 `cond' tries the clauses in textual order, by evaluating the
3080 CONDITION of each clause. If the value of CONDITION is non-`nil',
3081 the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and
3082 the value of the last of BODY-FORMS becomes the value of the
3083 `cond'. The remaining clauses are ignored.
3085 If the value of CONDITION is `nil', the clause "fails", so the
3086 `cond' moves on to the following clause, trying its CONDITION.
3088 If every CONDITION evaluates to `nil', so that every clause fails,
3089 `cond' returns `nil'.
3091 A clause may also look like this:
3095 Then, if CONDITION is non-`nil' when tested, the value of
3096 CONDITION becomes the value of the `cond' form.
3098 The following example has four clauses, which test for the cases
3099 where the value of `x' is a number, string, buffer and symbol,
3102 (cond ((numberp x) x)
3105 (setq temporary-hack x) ; multiple body-forms
3106 (buffer-name x)) ; in one clause
3107 ((symbolp x) (symbol-value x)))
3109 Often we want to execute the last clause whenever none of the
3110 previous clauses was successful. To do this, we use `t' as the
3111 CONDITION of the last clause, like this: `(t BODY-FORMS)'. The
3112 form `t' evaluates to `t', which is never `nil', so this clause
3113 never fails, provided the `cond' gets to it at all.
3117 (cond ((eq a 'hack) 'foo)
3121 This expression is a `cond' which returns `foo' if the value of
3122 `a' is 1, and returns the string `"default"' otherwise.
3124 Any conditional construct can be expressed with `cond' or with `if'.
3125 Therefore, the choice between them is a matter of style. For example:
3132 File: lispref.info, Node: Combining Conditions, Next: Iteration, Prev: Conditionals, Up: Control Structures
3134 Constructs for Combining Conditions
3135 ===================================
3137 This section describes three constructs that are often used together
3138 with `if' and `cond' to express complicated conditions. The constructs
3139 `and' and `or' can also be used individually as kinds of multiple
3140 conditional constructs.
3142 - Function: not condition
3143 This function tests for the falsehood of CONDITION. It returns
3144 `t' if CONDITION is `nil', and `nil' otherwise. The function
3145 `not' is identical to `null', and we recommend using the name
3146 `null' if you are testing for an empty list.
3148 - Special Form: and conditions...
3149 The `and' special form tests whether all the CONDITIONS are true.
3150 It works by evaluating the CONDITIONS one by one in the order
3153 If any of the CONDITIONS evaluates to `nil', then the result of
3154 the `and' must be `nil' regardless of the remaining CONDITIONS; so
3155 `and' returns right away, ignoring the remaining CONDITIONS.
3157 If all the CONDITIONS turn out non-`nil', then the value of the
3158 last of them becomes the value of the `and' form.
3160 Here is an example. The first condition returns the integer 1,
3161 which is not `nil'. Similarly, the second condition returns the
3162 integer 2, which is not `nil'. The third condition is `nil', so
3163 the remaining condition is never evaluated.
3165 (and (print 1) (print 2) nil (print 3))
3170 Here is a more realistic example of using `and':
3172 (if (and (consp foo) (eq (car foo) 'x))
3173 (message "foo is a list starting with x"))
3175 Note that `(car foo)' is not executed if `(consp foo)' returns
3176 `nil', thus avoiding an error.
3178 `and' can be expressed in terms of either `if' or `cond'. For
3181 (and ARG1 ARG2 ARG3)
3183 (if ARG1 (if ARG2 ARG3))
3185 (cond (ARG1 (cond (ARG2 ARG3))))
3187 - Special Form: or conditions...
3188 The `or' special form tests whether at least one of the CONDITIONS
3189 is true. It works by evaluating all the CONDITIONS one by one in
3192 If any of the CONDITIONS evaluates to a non-`nil' value, then the
3193 result of the `or' must be non-`nil'; so `or' returns right away,
3194 ignoring the remaining CONDITIONS. The value it returns is the
3195 non-`nil' value of the condition just evaluated.
3197 If all the CONDITIONS turn out `nil', then the `or' expression
3200 For example, this expression tests whether `x' is either 0 or
3203 (or (eq x nil) (eq x 0))
3205 Like the `and' construct, `or' can be written in terms of `cond'.
3214 You could almost write `or' in terms of `if', but not quite:
3220 This is not completely equivalent because it can evaluate ARG1 or
3221 ARG2 twice. By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
3222 any argument more than once.
3225 File: lispref.info, Node: Iteration, Next: Nonlocal Exits, Prev: Combining Conditions, Up: Control Structures
3230 Iteration means executing part of a program repetitively. For example,
3231 you might want to repeat some computation once for each element of a
3232 list, or once for each integer from 0 to N. You can do this in XEmacs
3233 Lisp with the special form `while':
3235 - Special Form: while condition forms...
3236 `while' first evaluates CONDITION. If the result is non-`nil', it
3237 evaluates FORMS in textual order. Then it reevaluates CONDITION,
3238 and if the result is non-`nil', it evaluates FORMS again. This
3239 process repeats until CONDITION evaluates to `nil'.
3241 There is no limit on the number of iterations that may occur. The
3242 loop will continue until either CONDITION evaluates to `nil' or
3243 until an error or `throw' jumps out of it (*note Nonlocal Exits::).
3245 The value of a `while' form is always `nil'.
3250 (princ (format "Iteration %d." num))
3251 (setq num (1+ num)))
3258 If you would like to execute something on each iteration before the
3259 end-test, put it together with the end-test in a `progn' as the
3260 first argument of `while', as shown here:
3264 (not (looking-at "^$"))))
3266 This moves forward one line and continues moving by lines until it
3267 reaches an empty. It is unusual in that the `while' has no body,
3268 just the end test (which also does the real work of moving point).
3271 File: lispref.info, Node: Nonlocal Exits, Prev: Iteration, Up: Control Structures
3276 A "nonlocal exit" is a transfer of control from one point in a program
3277 to another remote point. Nonlocal exits can occur in XEmacs Lisp as a
3278 result of errors; you can also use them under explicit control.
3279 Nonlocal exits unbind all variable bindings made by the constructs being
3284 * Catch and Throw:: Nonlocal exits for the program's own purposes.
3285 * Examples of Catch:: Showing how such nonlocal exits can be written.
3286 * Errors:: How errors are signaled and handled.
3287 * Cleanups:: Arranging to run a cleanup form if an error happens.
3290 File: lispref.info, Node: Catch and Throw, Next: Examples of Catch, Up: Nonlocal Exits
3292 Explicit Nonlocal Exits: `catch' and `throw'
3293 --------------------------------------------
3295 Most control constructs affect only the flow of control within the
3296 construct itself. The function `throw' is the exception to this rule
3297 of normal program execution: it performs a nonlocal exit on request.
3298 (There are other exceptions, but they are for error handling only.)
3299 `throw' is used inside a `catch', and jumps back to that `catch'. For
3308 The `throw' transfers control straight back to the corresponding
3309 `catch', which returns immediately. The code following the `throw' is
3310 not executed. The second argument of `throw' is used as the return
3311 value of the `catch'.
3313 The `throw' and the `catch' are matched through the first argument:
3314 `throw' searches for a `catch' whose first argument is `eq' to the one
3315 specified. Thus, in the above example, the `throw' specifies `foo',
3316 and the `catch' specifies the same symbol, so that `catch' is
3317 applicable. If there is more than one applicable `catch', the
3318 innermost one takes precedence.
3320 Executing `throw' exits all Lisp constructs up to the matching
3321 `catch', including function calls. When binding constructs such as
3322 `let' or function calls are exited in this way, the bindings are
3323 unbound, just as they are when these constructs exit normally (*note
3324 Local Variables::). Likewise, `throw' restores the buffer and position
3325 saved by `save-excursion' (*note Excursions::), and the narrowing
3326 status saved by `save-restriction' and the window selection saved by
3327 `save-window-excursion' (*note Window Configurations::). It also runs
3328 any cleanups established with the `unwind-protect' special form when it
3329 exits that form (*note Cleanups::).
3331 The `throw' need not appear lexically within the `catch' that it
3332 jumps to. It can equally well be called from another function called
3333 within the `catch'. As long as the `throw' takes place chronologically
3334 after entry to the `catch', and chronologically before exit from it, it
3335 has access to that `catch'. This is why `throw' can be used in
3336 commands such as `exit-recursive-edit' that throw back to the editor
3337 command loop (*note Recursive Editing::).
3339 Common Lisp note: Most other versions of Lisp, including Common
3340 Lisp, have several ways of transferring control nonsequentially:
3341 `return', `return-from', and `go', for example. XEmacs Lisp has
3344 - Special Form: catch tag body...
3345 `catch' establishes a return point for the `throw' function. The
3346 return point is distinguished from other such return points by TAG,
3347 which may be any Lisp object. The argument TAG is evaluated
3348 normally before the return point is established.
3350 With the return point in effect, `catch' evaluates the forms of the
3351 BODY in textual order. If the forms execute normally, without
3352 error or nonlocal exit, the value of the last body form is
3353 returned from the `catch'.
3355 If a `throw' is done within BODY specifying the same value TAG,
3356 the `catch' exits immediately; the value it returns is whatever
3357 was specified as the second argument of `throw'.
3359 - Function: throw tag value
3360 The purpose of `throw' is to return from a return point previously
3361 established with `catch'. The argument TAG is used to choose
3362 among the various existing return points; it must be `eq' to the
3363 value specified in the `catch'. If multiple return points match
3364 TAG, the innermost one is used.
3366 The argument VALUE is used as the value to return from that
3369 If no return point is in effect with tag TAG, then a `no-catch'
3370 error is signaled with data `(TAG VALUE)'.
3373 File: lispref.info, Node: Examples of Catch, Next: Errors, Prev: Catch and Throw, Up: Nonlocal Exits
3375 Examples of `catch' and `throw'
3376 -------------------------------
3378 One way to use `catch' and `throw' is to exit from a doubly nested
3379 loop. (In most languages, this would be done with a "go to".) Here we
3380 compute `(foo I J)' for I and J varying from 0 to 9:
3382 (defun search-foo ()
3389 (throw 'loop (list i j)))
3393 If `foo' ever returns non-`nil', we stop immediately and return a list
3394 of I and J. If `foo' always returns `nil', the `catch' returns
3395 normally, and the value is `nil', since that is the result of the
3398 Here are two tricky examples, slightly different, showing two return
3399 points at once. First, two return points with the same tag, `hack':
3403 (throw 'hack 'yes)))
3407 (print (catch2 'hack))
3412 Since both return points have tags that match the `throw', it goes to
3413 the inner one, the one established in `catch2'. Therefore, `catch2'
3414 returns normally with value `yes', and this value is printed. Finally
3415 the second body form in the outer `catch', which is `'no', is evaluated
3416 and returned from the outer `catch'.
3418 Now let's change the argument given to `catch2':
3422 (throw 'hack 'yes)))
3426 (print (catch2 'quux))
3430 We still have two return points, but this time only the outer one has
3431 the tag `hack'; the inner one has the tag `quux' instead. Therefore,
3432 `throw' makes the outer `catch' return the value `yes'. The function
3433 `print' is never called, and the body-form `'no' is never evaluated.
3436 File: lispref.info, Node: Errors, Next: Cleanups, Prev: Examples of Catch, Up: Nonlocal Exits
3441 When XEmacs Lisp attempts to evaluate a form that, for some reason,
3442 cannot be evaluated, it "signals" an "error".
3444 When an error is signaled, XEmacs's default reaction is to print an
3445 error message and terminate execution of the current command. This is
3446 the right thing to do in most cases, such as if you type `C-f' at the
3449 In complicated programs, simple termination may not be what you want.
3450 For example, the program may have made temporary changes in data
3451 structures, or created temporary buffers that should be deleted before
3452 the program is finished. In such cases, you would use `unwind-protect'
3453 to establish "cleanup expressions" to be evaluated in case of error.
3454 (*Note Cleanups::.) Occasionally, you may wish the program to continue
3455 execution despite an error in a subroutine. In these cases, you would
3456 use `condition-case' to establish "error handlers" to recover control
3459 Resist the temptation to use error handling to transfer control from
3460 one part of the program to another; use `catch' and `throw' instead.
3461 *Note Catch and Throw::.
3465 * Signaling Errors:: How to report an error.
3466 * Processing of Errors:: What XEmacs does when you report an error.
3467 * Handling Errors:: How you can trap errors and continue execution.
3468 * Error Symbols:: How errors are classified for trapping them.
3471 File: lispref.info, Node: Signaling Errors, Next: Processing of Errors, Up: Errors
3473 How to Signal an Error
3474 ......................
3476 Most errors are signaled "automatically" within Lisp primitives which
3477 you call for other purposes, such as if you try to take the CAR of an
3478 integer or move forward a character at the end of the buffer; you can
3479 also signal errors explicitly with the functions `error', `signal', and
3482 Quitting, which happens when the user types `C-g', is not considered
3483 an error, but it is handled almost like an error. *Note Quitting::.
3485 XEmacs has a rich hierarchy of error symbols predefined via
3491 list-formation-error
3493 malformed-property-list
3495 circular-property-list
3500 wrong-number-of-arguments
3506 cyclic-function-indirection
3508 cyclic-variable-indirection
3526 The five most common errors you will probably use or base your new
3527 errors off of are `syntax-error', `invalid-argument', `invalid-state',
3528 `invalid-operation', and `invalid-change'. Note the semantic
3531 * `syntax-error' is for errors in complex structures: parsed strings,
3532 lists, and the like.
3534 * `invalid-argument' is for errors in a simple value. Typically, the
3535 entire value, not just one part of it, is wrong.
3537 * `invalid-state' means that some settings have been changed in such
3538 a way that their current state is unallowable. More and more,
3539 code is being written more carefully, and catches the error when
3540 the settings are being changed, rather than afterwards. This
3541 leads us to the next error:
3543 * `invalid-change' means that an attempt is being made to change some
3544 settings into an invalid state. `invalid-change' is a type of
3545 `invalid-operation'.
3547 * `invalid-operation' refers to all cases where code is trying to do
3548 something that's disallowed. This includes file errors, buffer
3549 errors (e.g. running off the end of a buffer), `invalid-change' as
3550 just mentioned, and arithmetic errors.
3552 - Function: error datum &rest args
3553 This function signals a non-continuable error.
3555 DATUM should normally be an error symbol, i.e. a symbol defined
3556 using `define-error'. ARGS will be made into a list, and DATUM
3557 and ARGS passed as the two arguments to `signal', the most basic
3558 error handling function.
3560 This error is not continuable: you cannot continue execution after
3561 the error using the debugger `r' command. See also `cerror'.
3563 The correct semantics of ARGS varies from error to error, but for
3564 most errors that need to be generated in Lisp code, the first
3565 argument should be a string describing the *context* of the error
3566 (i.e. the exact operation being performed and what went wrong),
3567 and the remaining arguments or \"frobs\" (most often, there is
3568 one) specify the offending object(s) and/or provide additional
3569 details such as the exact error when a file error occurred, e.g.:
3571 * the buffer in which an editing error occurred.
3573 * an invalid value that was encountered. (In such cases, the
3574 string should describe the purpose or \"semantics\" of the
3575 value [e.g. if the value is an argument to a function, the
3576 name of the argument; if the value is the value corresponding
3577 to a keyword, the name of the keyword; if the value is
3578 supposed to be a list length, say this and say what the
3579 purpose of the list is; etc.] as well as specifying why the
3580 value is invalid, if that's not self-evident.)
3582 * the file in which an error occurred. (In such cases, there
3583 should be a second frob, probably a string, specifying the
3584 exact error that occurred. This does not occur in the string
3585 that precedes the first frob, because that frob describes the
3586 exact operation that was happening.
3588 For historical compatibility, DATUM can also be a string. In this
3589 case, DATUM and ARGS are passed together as the arguments to
3590 `format', and then an error is signalled using the error symbol
3591 `error' and formatted string. Although this usage of `error' is
3592 very common, it is deprecated because it totally defeats the
3593 purpose of having structured errors. There is now a rich set of
3594 defined errors to use.
3596 See also `cerror', `signal', and `signal-error'."
3598 These examples show typical uses of `error':
3600 (error 'syntax-error
3601 "Dialog descriptor must supply at least one button"
3604 (error "You have committed an error.
3605 Try something else.")
3606 error--> You have committed an error.
3609 (error "You have committed %d errors." 10)
3610 error--> You have committed 10 errors.
3612 If you want to use your own string as an error message verbatim,
3613 don't just write `(error STRING)'. If STRING contains `%', it
3614 will be interpreted as a format specifier, with undesirable
3615 results. Instead, use `(error "%s" STRING)'.
3617 - Function: cerror datum &rest args
3618 This function behaves like `error', except that the error it
3619 signals is continuable. That means that debugger commands `c' and
3620 `r' can resume execution.
3622 - Function: signal error-symbol data
3623 This function signals a continuable error named by ERROR-SYMBOL.
3624 The argument DATA is a list of additional Lisp objects relevant to
3625 the circumstances of the error.
3627 The argument ERROR-SYMBOL must be an "error symbol"--a symbol
3628 bearing a property `error-conditions' whose value is a list of
3629 condition names. This is how XEmacs Lisp classifies different
3632 The number and significance of the objects in DATA depends on
3633 ERROR-SYMBOL. For example, with a `wrong-type-argument' error,
3634 there are two objects in the list: a predicate that describes the
3635 type that was expected, and the object that failed to fit that
3636 type. *Note Error Symbols::, for a description of error symbols.
3638 Both ERROR-SYMBOL and DATA are available to any error handlers
3639 that handle the error: `condition-case' binds a local variable to
3640 a list of the form `(ERROR-SYMBOL . DATA)' (*note Handling
3641 Errors::). If the error is not handled, these two values are used
3642 in printing the error message.
3644 The function `signal' can return, if the debugger is invoked and
3645 the user invokes the "return from signal" option. If you want the
3646 error not to be continuable, use `signal-error' instead. Note that
3647 in FSF Emacs `signal' never returns.
3649 (signal 'wrong-number-of-arguments '(x y))
3650 error--> Wrong number of arguments: x, y
3652 (signal 'no-such-error '("My unknown error condition"))
3653 error--> Peculiar error (no-such-error "My unknown error condition")
3655 - Function: signal-error error-symbol data
3656 This function behaves like `signal', except that the error it
3657 signals is not continuable.
3659 - Macro: check-argument-type predicate argument
3660 This macro checks that ARGUMENT satisfies PREDICATE. If that is
3661 not the case, it signals a continuable `wrong-type-argument' error
3662 until the returned value satisfies PREDICATE, and assigns the
3663 returned value to ARGUMENT. In other words, execution of the
3664 program will not continue until PREDICATE is met.
3666 ARGUMENT is not evaluated, and should be a symbol. PREDICATE is
3667 evaluated, and should name a function.
3669 As shown in the following example, `check-argument-type' is useful
3670 in low-level code that attempts to ensure the sanity of its data
3673 (defun cache-object-internal (object wlist)
3674 ;; Before doing anything, make sure that WLIST is indeed
3675 ;; a weak list, which is what we expect.
3676 (check-argument-type 'weak-list-p wlist)
3680 File: lispref.info, Node: Processing of Errors, Next: Handling Errors, Prev: Signaling Errors, Up: Errors
3682 How XEmacs Processes Errors
3683 ...........................
3685 When an error is signaled, `signal' searches for an active "handler"
3686 for the error. A handler is a sequence of Lisp expressions designated
3687 to be executed if an error happens in part of the Lisp program. If the
3688 error has an applicable handler, the handler is executed, and control
3689 resumes following the handler. The handler executes in the environment
3690 of the `condition-case' that established it; all functions called
3691 within that `condition-case' have already been exited, and the handler
3692 cannot return to them.
3694 If there is no applicable handler for the error, the current command
3695 is terminated and control returns to the editor command loop, because
3696 the command loop has an implicit handler for all kinds of errors. The
3697 command loop's handler uses the error symbol and associated data to
3698 print an error message.
3700 Errors in command loop are processed using the `command-error'
3701 function, which takes care of some necessary cleanup, and prints a
3702 formatted error message to the echo area. The functions that do the
3703 formatting are explained below.
3705 - Function: display-error error-object stream
3706 This function displays ERROR-OBJECT on STREAM. ERROR-OBJECT is a
3707 cons of error type, a symbol, and error arguments, a list. If the
3708 error type symbol of one of its error condition superclasses has a
3709 `display-error' property, that function is invoked for printing
3710 the actual error message. Otherwise, the error is printed as
3711 `Error: arg1, arg2, ...'.
3713 - Function: error-message-string error-object
3714 This function converts ERROR-OBJECT to an error message string,
3715 and returns it. The message is equivalent to the one that would be
3716 printed by `display-error', except that it is conveniently returned
3719 An error that has no explicit handler may call the Lisp debugger.
3720 The debugger is enabled if the variable `debug-on-error' (*note Error
3721 Debugging::) is non-`nil'. Unlike error handlers, the debugger runs in
3722 the environment of the error, so that you can examine values of
3723 variables precisely as they were at the time of the error.
3726 File: lispref.info, Node: Handling Errors, Next: Error Symbols, Prev: Processing of Errors, Up: Errors
3728 Writing Code to Handle Errors
3729 .............................
3731 The usual effect of signaling an error is to terminate the command that
3732 is running and return immediately to the XEmacs editor command loop.
3733 You can arrange to trap errors occurring in a part of your program by
3734 establishing an error handler, with the special form `condition-case'.
3735 A simple example looks like this:
3738 (delete-file filename)
3741 This deletes the file named FILENAME, catching any error and returning
3742 `nil' if an error occurs.
3744 The second argument of `condition-case' is called the "protected
3745 form". (In the example above, the protected form is a call to
3746 `delete-file'.) The error handlers go into effect when this form
3747 begins execution and are deactivated when this form returns. They
3748 remain in effect for all the intervening time. In particular, they are
3749 in effect during the execution of functions called by this form, in
3750 their subroutines, and so on. This is a good thing, since, strictly
3751 speaking, errors can be signaled only by Lisp primitives (including
3752 `signal' and `error') called by the protected form, not by the
3753 protected form itself.
3755 The arguments after the protected form are handlers. Each handler
3756 lists one or more "condition names" (which are symbols) to specify
3757 which errors it will handle. The error symbol specified when an error
3758 is signaled also defines a list of condition names. A handler applies
3759 to an error if they have any condition names in common. In the example
3760 above, there is one handler, and it specifies one condition name,
3761 `error', which covers all errors.
3763 The search for an applicable handler checks all the established
3764 handlers starting with the most recently established one. Thus, if two
3765 nested `condition-case' forms offer to handle the same error, the inner
3766 of the two will actually handle it.
3768 When an error is handled, control returns to the handler. Before
3769 this happens, XEmacs unbinds all variable bindings made by binding
3770 constructs that are being exited and executes the cleanups of all
3771 `unwind-protect' forms that are exited. Once control arrives at the
3772 handler, the body of the handler is executed.
3774 After execution of the handler body, execution continues by returning
3775 from the `condition-case' form. Because the protected form is exited
3776 completely before execution of the handler, the handler cannot resume
3777 execution at the point of the error, nor can it examine variable
3778 bindings that were made within the protected form. All it can do is
3779 clean up and proceed.
3781 `condition-case' is often used to trap errors that are predictable,
3782 such as failure to open a file in a call to `insert-file-contents'. It
3783 is also used to trap errors that are totally unpredictable, such as
3784 when the program evaluates an expression read from the user.
3786 Even when an error is handled, the debugger may still be called if
3787 the variable `debug-on-signal' (*note Error Debugging::) is non-`nil'.
3788 Note that this may yield unpredictable results with code that traps
3789 expected errors as normal part of its operation. Do not set
3790 `debug-on-signal' unless you know what you are doing.
3792 Error signaling and handling have some resemblance to `throw' and
3793 `catch', but they are entirely separate facilities. An error cannot be
3794 caught by a `catch', and a `throw' cannot be handled by an error
3795 handler (though using `throw' when there is no suitable `catch' signals
3796 an error that can be handled).
3798 - Special Form: condition-case var protected-form handlers...
3799 This special form establishes the error handlers HANDLERS around
3800 the execution of PROTECTED-FORM. If PROTECTED-FORM executes
3801 without error, the value it returns becomes the value of the
3802 `condition-case' form; in this case, the `condition-case' has no
3803 effect. The `condition-case' form makes a difference when an
3804 error occurs during PROTECTED-FORM.
3806 Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
3807 Here CONDITIONS is an error condition name to be handled, or a
3808 list of condition names; BODY is one or more Lisp expressions to
3809 be executed when this handler handles an error. Here are examples
3814 (arith-error (message "Division by zero"))
3816 ((arith-error file-error)
3818 "Either division by zero or failure to open a file"))
3820 Each error that occurs has an "error symbol" that describes what
3821 kind of error it is. The `error-conditions' property of this
3822 symbol is a list of condition names (*note Error Symbols::). Emacs
3823 searches all the active `condition-case' forms for a handler that
3824 specifies one or more of these condition names; the innermost
3825 matching `condition-case' handles the error. Within this
3826 `condition-case', the first applicable handler handles the error.
3828 After executing the body of the handler, the `condition-case'
3829 returns normally, using the value of the last form in the handler
3830 body as the overall value.
3832 The argument VAR is a variable. `condition-case' does not bind
3833 this variable when executing the PROTECTED-FORM, only when it
3834 handles an error. At that time, it binds VAR locally to a list of
3835 the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
3836 error. The handler can refer to this list to decide what to do.
3837 For example, if the error is for failure opening a file, the file
3838 name is the second element of DATA--the third element of VAR.
3840 If VAR is `nil', that means no variable is bound. Then the error
3841 symbol and associated data are not available to the handler.
3843 Here is an example of using `condition-case' to handle the error
3844 that results from dividing by zero. The handler prints out a warning
3845 message and returns a very large number.
3847 (defun safe-divide (dividend divisor)
3850 (/ dividend divisor)
3852 (arith-error ; Condition.
3853 (princ (format "Arithmetic error: %s" err))
3858 -| Arithmetic error: (arith-error)
3861 The handler specifies condition name `arith-error' so that it will
3862 handle only division-by-zero errors. Other kinds of errors will not be
3863 handled, at least not by this `condition-case'. Thus,
3866 error--> Wrong type argument: integer-or-marker-p, nil
3868 Here is a `condition-case' that catches all kinds of errors,
3869 including those signaled with `error':
3877 ;; This is a call to the function `error'.
3878 (error "Rats! The variable %s was %s, not 35" 'baz baz))
3879 ;; This is the handler; it is not a form.
3880 (error (princ (format "The error was: %s" err))
3882 -| The error was: (error "Rats! The variable baz was 34, not 35")
3886 File: lispref.info, Node: Error Symbols, Prev: Handling Errors, Up: Errors
3888 Error Symbols and Condition Names
3889 .................................
3891 When you signal an error, you specify an "error symbol" to specify the
3892 kind of error you have in mind. Each error has one and only one error
3893 symbol to categorize it. This is the finest classification of errors
3894 defined by the XEmacs Lisp language.
3896 These narrow classifications are grouped into a hierarchy of wider
3897 classes called "error conditions", identified by "condition names".
3898 The narrowest such classes belong to the error symbols themselves: each
3899 error symbol is also a condition name. There are also condition names
3900 for more extensive classes, up to the condition name `error' which
3901 takes in all kinds of errors. Thus, each error has one or more
3902 condition names: `error', the error symbol if that is distinct from
3903 `error', and perhaps some intermediate classifications.
3905 In other words, each error condition "inherits" from another error
3906 condition, with `error' sitting at the top of the inheritance hierarchy.
3908 - Function: define-error error-symbol error-message &optional
3910 This function defines a new error, denoted by ERROR-SYMBOL.
3911 ERROR-MESSAGE is an informative message explaining the error, and
3912 will be printed out when an unhandled error occurs. ERROR-SYMBOL
3913 is a sub-error of INHERITS-FROM (which defaults to `error').
3915 `define-error' internally works by putting on ERROR-SYMBOL an
3916 `error-message' property whose value is ERROR-MESSAGE, and an
3917 `error-conditions' property that is a list of ERROR-SYMBOL
3918 followed by each of its super-errors, up to and including `error'.
3919 You will sometimes see code that sets this up directly rather than
3920 calling `define-error', but you should _not_ do this yourself,
3921 unless you wish to maintain compatibility with FSF Emacs, which
3922 does not provide `define-error'.
3924 Here is how we define a new error symbol, `new-error', that belongs
3925 to a range of errors called `my-own-errors':
3927 (define-error 'my-own-errors "A whole range of errors" 'error)
3928 (define-error 'new-error "A new error" 'my-own-errors)
3930 `new-error' has three condition names: `new-error', the narrowest
3931 classification; `my-own-errors', which we imagine is a wider
3932 classification; and `error', which is the widest of all.
3934 Note that it is not legal to try to define an error unless its
3935 super-error is also defined. For instance, attempting to define
3936 `new-error' before `my-own-errors' are defined will signal an error.
3938 The error string should start with a capital letter but it should
3939 not end with a period. This is for consistency with the rest of Emacs.
3941 Naturally, XEmacs will never signal `new-error' on its own; only an
3942 explicit call to `signal' (*note Signaling Errors::) in your code can
3945 (signal 'new-error '(x y))
3946 error--> A new error: x, y
3948 This error can be handled through any of the three condition names.
3949 This example handles `new-error' and any other errors in the class
3954 (my-own-errors nil))
3956 The significant way that errors are classified is by their condition
3957 names--the names used to match errors with handlers. An error symbol
3958 serves only as a convenient way to specify the intended error message
3959 and list of condition names. It would be cumbersome to give `signal' a
3960 list of condition names rather than one error symbol.
3962 By contrast, using only error symbols without condition names would
3963 seriously decrease the power of `condition-case'. Condition names make
3964 it possible to categorize errors at various levels of generality when
3965 you write an error handler. Using error symbols alone would eliminate
3966 all but the narrowest level of classification.
3968 *Note Standard Errors::, for a list of all the standard error symbols
3969 and their conditions.
3972 File: lispref.info, Node: Cleanups, Prev: Errors, Up: Nonlocal Exits
3974 Cleaning Up from Nonlocal Exits
3975 -------------------------------
3977 The `unwind-protect' construct is essential whenever you temporarily
3978 put a data structure in an inconsistent state; it permits you to ensure
3979 the data are consistent in the event of an error or throw.
3981 - Special Form: unwind-protect body cleanup-forms...
3982 `unwind-protect' executes the BODY with a guarantee that the
3983 CLEANUP-FORMS will be evaluated if control leaves BODY, no matter
3984 how that happens. The BODY may complete normally, or execute a
3985 `throw' out of the `unwind-protect', or cause an error; in all
3986 cases, the CLEANUP-FORMS will be evaluated.
3988 If the BODY forms finish normally, `unwind-protect' returns the
3989 value of the last BODY form, after it evaluates the CLEANUP-FORMS.
3990 If the BODY forms do not finish, `unwind-protect' does not return
3991 any value in the normal sense.
3993 Only the BODY is actually protected by the `unwind-protect'. If
3994 any of the CLEANUP-FORMS themselves exits nonlocally (e.g., via a
3995 `throw' or an error), `unwind-protect' is _not_ guaranteed to
3996 evaluate the rest of them. If the failure of one of the
3997 CLEANUP-FORMS has the potential to cause trouble, then protect it
3998 with another `unwind-protect' around that form.
4000 The number of currently active `unwind-protect' forms counts,
4001 together with the number of local variable bindings, against the
4002 limit `max-specpdl-size' (*note Local Variables::).
4004 For example, here we make an invisible buffer for temporary use, and
4005 make sure to kill it before finishing:
4008 (let ((buffer (get-buffer-create " *temp*")))
4012 (kill-buffer buffer))))
4014 You might think that we could just as well write `(kill-buffer
4015 (current-buffer))' and dispense with the variable `buffer'. However,
4016 the way shown above is safer, if BODY happens to get an error after
4017 switching to a different buffer! (Alternatively, you could write
4018 another `save-excursion' around the body, to ensure that the temporary
4019 buffer becomes current in time to kill it.)
4021 Here is an actual example taken from the file `ftp.el'. It creates
4022 a process (*note Processes::) to try to establish a connection to a
4023 remote machine. As the function `ftp-login' is highly susceptible to
4024 numerous problems that the writer of the function cannot anticipate, it
4025 is protected with a form that guarantees deletion of the process in the
4026 event of failure. Otherwise, XEmacs might fill up with useless
4032 (setq process (ftp-setup-buffer host file))
4033 (if (setq win (ftp-login process host user password))
4034 (message "Logged in")
4035 (error "Ftp login failed")))
4036 (or win (and process (delete-process process)))))
4038 This example actually has a small bug: if the user types `C-g' to
4039 quit, and the quit happens immediately after the function
4040 `ftp-setup-buffer' returns but before the variable `process' is set,
4041 the process will not be killed. There is no easy way to fix this bug,
4042 but at least it is very unlikely.
4044 Here is another example which uses `unwind-protect' to make sure to
4045 kill a temporary buffer. In this example, the value returned by
4046 `unwind-protect' is used.
4048 (defun shell-command-string (cmd)
4049 "Return the output of the shell command CMD, as a string."
4051 (set-buffer (generate-new-buffer " OS*cmd"))
4052 (shell-command cmd t)
4055 (kill-buffer (current-buffer)))))
4058 File: lispref.info, Node: Variables, Next: Functions, Prev: Control Structures, Up: Top
4063 A "variable" is a name used in a program to stand for a value. Nearly
4064 all programming languages have variables of some sort. In the text of
4065 a Lisp program, variables are written using the syntax for symbols.
4067 In Lisp, unlike most programming languages, programs are represented
4068 primarily as Lisp objects and only secondarily as text. The Lisp
4069 objects used for variables are symbols: the symbol name is the variable
4070 name, and the variable's value is stored in the value cell of the
4071 symbol. The use of a symbol as a variable is independent of its use as
4072 a function name. *Note Symbol Components::.
4074 The Lisp objects that constitute a Lisp program determine the textual
4075 form of the program--it is simply the read syntax for those Lisp
4076 objects. This is why, for example, a variable in a textual Lisp program
4077 is written using the read syntax for the symbol that represents the
4082 * Global Variables:: Variable values that exist permanently, everywhere.
4083 * Constant Variables:: Certain "variables" have values that never change.
4084 * Local Variables:: Variable values that exist only temporarily.
4085 * Void Variables:: Symbols that lack values.
4086 * Defining Variables:: A definition says a symbol is used as a variable.
4087 * Accessing Variables:: Examining values of variables whose names
4088 are known only at run time.
4089 * Setting Variables:: Storing new values in variables.
4090 * Variable Scoping:: How Lisp chooses among local and global values.
4091 * Buffer-Local Variables:: Variable values in effect only in one buffer.
4092 * Variable Aliases:: Making one variable point to another.
4095 File: lispref.info, Node: Global Variables, Next: Constant Variables, Up: Variables
4100 The simplest way to use a variable is "globally". This means that the
4101 variable has just one value at a time, and this value is in effect (at
4102 least for the moment) throughout the Lisp system. The value remains in
4103 effect until you specify a new one. When a new value replaces the old
4104 one, no trace of the old value remains in the variable.
4106 You specify a value for a symbol with `setq'. For example,
4110 gives the variable `x' the value `(a b)'. Note that `setq' does not
4111 evaluate its first argument, the name of the variable, but it does
4112 evaluate the second argument, the new value.
4114 Once the variable has a value, you can refer to it by using the
4115 symbol by itself as an expression. Thus,
4119 assuming the `setq' form shown above has already been executed.
4121 If you do another `setq', the new value replaces the old one:
4131 File: lispref.info, Node: Constant Variables, Next: Local Variables, Prev: Global Variables, Up: Variables
4133 Variables That Never Change
4134 ===========================
4136 In XEmacs Lisp, some symbols always evaluate to themselves: the two
4137 special symbols `nil' and `t', as well as "keyword symbols", that is,
4138 symbols whose name begins with the character ``:''. These symbols
4139 cannot be rebound, nor can their value cells be changed. An attempt to
4140 change the value of `nil' or `t' signals a `setting-constant' error.
4145 error--> Attempt to set constant symbol: nil
4148 File: lispref.info, Node: Local Variables, Next: Void Variables, Prev: Constant Variables, Up: Variables
4153 Global variables have values that last until explicitly superseded with
4154 new values. Sometimes it is useful to create variable values that
4155 exist temporarily--only while within a certain part of the program.
4156 These values are called "local", and the variables so used are called
4159 For example, when a function is called, its argument variables
4160 receive new local values that last until the function exits. The `let'
4161 special form explicitly establishes new local values for specified
4162 variables; these last until exit from the `let' form.
4164 Establishing a local value saves away the previous value (or lack of
4165 one) of the variable. When the life span of the local value is over,
4166 the previous value is restored. In the mean time, we say that the
4167 previous value is "shadowed" and "not visible". Both global and local
4168 values may be shadowed (*note Scope::).
4170 If you set a variable (such as with `setq') while it is local, this
4171 replaces the local value; it does not alter the global value, or
4172 previous local values that are shadowed. To model this behavior, we
4173 speak of a "local binding" of the variable as well as a local value.
4175 The local binding is a conceptual place that holds a local value.
4176 Entry to a function, or a special form such as `let', creates the local
4177 binding; exit from the function or from the `let' removes the local
4178 binding. As long as the local binding lasts, the variable's value is
4179 stored within it. Use of `setq' or `set' while there is a local
4180 binding stores a different value into the local binding; it does not
4181 create a new binding.
4183 We also speak of the "global binding", which is where (conceptually)
4184 the global value is kept.
4186 A variable can have more than one local binding at a time (for
4187 example, if there are nested `let' forms that bind it). In such a
4188 case, the most recently created local binding that still exists is the
4189 "current binding" of the variable. (This is called "dynamic scoping";
4190 see *Note Variable Scoping::.) If there are no local bindings, the
4191 variable's global binding is its current binding. We also call the
4192 current binding the "most-local existing binding", for emphasis.
4193 Ordinary evaluation of a symbol always returns the value of its current
4196 The special forms `let' and `let*' exist to create local bindings.
4198 - Special Form: let (bindings...) forms...
4199 This special form binds variables according to BINDINGS and then
4200 evaluates all of the FORMS in textual order. The `let'-form
4201 returns the value of the last form in FORMS.
4203 Each of the BINDINGS is either (i) a symbol, in which case that
4204 symbol is bound to `nil'; or (ii) a list of the form `(SYMBOL
4205 VALUE-FORM)', in which case SYMBOL is bound to the result of
4206 evaluating VALUE-FORM. If VALUE-FORM is omitted, `nil' is used.
4208 All of the VALUE-FORMs in BINDINGS are evaluated in the order they
4209 appear and _before_ any of the symbols are bound. Here is an
4210 example of this: `Z' is bound to the old value of `Y', which is 2,
4211 not the new value, 1.
4220 - Special Form: let* (bindings...) forms...
4221 This special form is like `let', but it binds each variable right
4222 after computing its local value, before computing the local value
4223 for the next variable. Therefore, an expression in BINDINGS can
4224 reasonably refer to the preceding symbols bound in this `let*'
4225 form. Compare the following example with the example above for
4231 (Z Y)) ; Use the just-established value of `Y'.
4235 Here is a complete list of the other facilities that create local
4238 * Function calls (*note Functions::).
4240 * Macro calls (*note Macros::).
4242 * `condition-case' (*note Errors::).
4244 Variables can also have buffer-local bindings (*note Buffer-Local
4245 Variables::). These kinds of bindings work somewhat like ordinary local
4246 bindings, but they are localized depending on "where" you are in Emacs,
4247 rather than localized in time.
4249 - Variable: max-specpdl-size
4250 This variable defines the limit on the total number of local
4251 variable bindings and `unwind-protect' cleanups (*note Nonlocal
4252 Exits::) that are allowed before signaling an error (with data
4253 `"Variable binding depth exceeds max-specpdl-size"').
4255 This limit, with the associated error when it is exceeded, is one
4256 way that Lisp avoids infinite recursion on an ill-defined function.
4258 The default value is 3000.
4260 `max-lisp-eval-depth' provides another limit on depth of nesting.
4264 File: lispref.info, Node: Void Variables, Next: Defining Variables, Prev: Local Variables, Up: Variables
4266 When a Variable is "Void"
4267 =========================
4269 If you have never given a symbol any value as a global variable, we say
4270 that that symbol's global value is "void". In other words, the
4271 symbol's value cell does not have any Lisp object in it. If you try to
4272 evaluate the symbol, you get a `void-variable' error rather than a
4275 Note that a value of `nil' is not the same as void. The symbol
4276 `nil' is a Lisp object and can be the value of a variable just as any
4277 other object can be; but it is _a value_. A void variable does not
4280 After you have given a variable a value, you can make it void once
4281 more using `makunbound'.
4283 - Function: makunbound symbol
4284 This function makes the current binding of SYMBOL void.
4285 Subsequent attempts to use this symbol's value as a variable will
4286 signal the error `void-variable', unless or until you set it again.
4288 `makunbound' returns SYMBOL.
4290 (makunbound 'x) ; Make the global value
4294 error--> Symbol's value as variable is void: x
4296 If SYMBOL is locally bound, `makunbound' affects the most local
4297 existing binding. This is the only way a symbol can have a void
4298 local binding, since all the constructs that create local bindings
4299 create them with values. In this case, the voidness lasts at most
4300 as long as the binding does; when the binding is removed due to
4301 exit from the construct that made it, the previous or global
4302 binding is reexposed as usual, and the variable is no longer void
4303 unless the newly reexposed binding was void all along.
4305 (setq x 1) ; Put a value in the global binding.
4307 (let ((x 2)) ; Locally bind it.
4308 (makunbound 'x) ; Void the local binding.
4310 error--> Symbol's value as variable is void: x
4311 x ; The global binding is unchanged.
4314 (let ((x 2)) ; Locally bind it.
4315 (let ((x 3)) ; And again.
4316 (makunbound 'x) ; Void the innermost-local binding.
4317 x)) ; And refer: it's void.
4318 error--> Symbol's value as variable is void: x
4322 (makunbound 'x)) ; Void inner binding, then remove it.
4323 x) ; Now outer `let' binding is visible.
4326 A variable that has been made void with `makunbound' is
4327 indistinguishable from one that has never received a value and has
4330 You can use the function `boundp' to test whether a variable is
4333 - Function: boundp variable
4334 `boundp' returns `t' if VARIABLE (a symbol) is not void; more
4335 precisely, if its current binding is not void. It returns `nil'
4338 (boundp 'abracadabra) ; Starts out void.
4340 (let ((abracadabra 5)) ; Locally bind it.
4341 (boundp 'abracadabra))
4343 (boundp 'abracadabra) ; Still globally void.
4345 (setq abracadabra 5) ; Make it globally nonvoid.
4347 (boundp 'abracadabra)
4351 File: lispref.info, Node: Defining Variables, Next: Accessing Variables, Prev: Void Variables, Up: Variables
4353 Defining Global Variables
4354 =========================
4356 You may announce your intention to use a symbol as a global variable
4357 with a "variable definition": a special form, either `defconst' or
4360 In XEmacs Lisp, definitions serve three purposes. First, they inform
4361 people who read the code that certain symbols are _intended_ to be used
4362 a certain way (as variables). Second, they inform the Lisp system of
4363 these things, supplying a value and documentation. Third, they provide
4364 information to utilities such as `etags' and `make-docfile', which
4365 create data bases of the functions and variables in a program.
4367 The difference between `defconst' and `defvar' is primarily a matter
4368 of intent, serving to inform human readers of whether programs will
4369 change the variable. XEmacs Lisp does not restrict the ways in which a
4370 variable can be used based on `defconst' or `defvar' declarations.
4371 However, it does make a difference for initialization: `defconst'
4372 unconditionally initializes the variable, while `defvar' initializes it
4375 One would expect user option variables to be defined with
4376 `defconst', since programs do not change them. Unfortunately, this has
4377 bad results if the definition is in a library that is not preloaded:
4378 `defconst' would override any prior value when the library is loaded.
4379 Users would like to be able to set user options in their init files,
4380 and override the default values given in the definitions. For this
4381 reason, user options must be defined with `defvar'.
4383 - Special Form: defvar symbol [value [doc-string]]
4384 This special form defines SYMBOL as a value and initializes it.
4385 The definition informs a person reading your code that SYMBOL is
4386 used as a variable that programs are likely to set or change. It
4387 is also used for all user option variables except in the preloaded
4388 parts of XEmacs. Note that SYMBOL is not evaluated; the symbol to
4389 be defined must appear explicitly in the `defvar'.
4391 If SYMBOL already has a value (i.e., it is not void), VALUE is not
4392 even evaluated, and SYMBOL's value remains unchanged. If SYMBOL
4393 is void and VALUE is specified, `defvar' evaluates it and sets
4394 SYMBOL to the result. (If VALUE is omitted, the value of SYMBOL
4395 is not changed in any case.)
4397 When you evaluate a top-level `defvar' form with `C-M-x' in Emacs
4398 Lisp mode (`eval-defun'), a special feature of `eval-defun'
4399 evaluates it as a `defconst'. The purpose of this is to make sure
4400 the variable's value is reinitialized, when you ask for it
4403 If SYMBOL has a buffer-local binding in the current buffer,
4404 `defvar' sets the default value, not the local value. *Note
4405 Buffer-Local Variables::.
4407 If the DOC-STRING argument appears, it specifies the documentation
4408 for the variable. (This opportunity to specify documentation is
4409 one of the main benefits of defining the variable.) The
4410 documentation is stored in the symbol's `variable-documentation'
4411 property. The XEmacs help functions (*note Documentation::) look
4414 If the first character of DOC-STRING is `*', it means that this
4415 variable is considered a user option. This lets users set the
4416 variable conveniently using the commands `set-variable' and
4419 For example, this form defines `foo' but does not set its value:
4424 The following example sets the value of `bar' to `23', and gives
4425 it a documentation string:
4428 "The normal weight of a bar.")
4431 The following form changes the documentation string for `bar',
4432 making it a user option, but does not change the value, since `bar'
4433 already has a value. (The addition `(1+ 23)' is not even
4437 "*The normal weight of a bar.")
4442 Here is an equivalent expression for the `defvar' special form:
4444 (defvar SYMBOL VALUE DOC-STRING)
4447 (if (not (boundp 'SYMBOL))
4448 (setq SYMBOL VALUE))
4449 (put 'SYMBOL 'variable-documentation 'DOC-STRING)
4452 The `defvar' form returns SYMBOL, but it is normally used at top
4453 level in a file where its value does not matter.
4455 - Special Form: defconst symbol [value [doc-string]]
4456 This special form defines SYMBOL as a value and initializes it.
4457 It informs a person reading your code that SYMBOL has a global
4458 value, established here, that will not normally be changed or
4459 locally bound by the execution of the program. The user, however,
4460 may be welcome to change it. Note that SYMBOL is not evaluated;
4461 the symbol to be defined must appear explicitly in the `defconst'.
4463 `defconst' always evaluates VALUE and sets the global value of
4464 SYMBOL to the result, provided VALUE is given. If SYMBOL has a
4465 buffer-local binding in the current buffer, `defconst' sets the
4466 default value, not the local value.
4468 *Please note:* Don't use `defconst' for user option variables in
4469 libraries that are not standardly preloaded. The user should be
4470 able to specify a value for such a variable in the `.emacs' file,
4471 so that it will be in effect if and when the library is loaded
4474 Here, `pi' is a constant that presumably ought not to be changed
4475 by anyone (attempts by the Indiana State Legislature
4476 notwithstanding). As the second form illustrates, however, this
4479 (defconst pi 3.1415 "Pi to five places.")
4486 - Function: user-variable-p variable
4487 This function returns `t' if VARIABLE is a user option--a variable
4488 intended to be set by the user for customization--and `nil'
4489 otherwise. (Variables other than user options exist for the
4490 internal purposes of Lisp programs, and users need not know about
4493 User option variables are distinguished from other variables by the
4494 first character of the `variable-documentation' property. If the
4495 property exists and is a string, and its first character is `*',
4496 then the variable is a user option.
4498 If a user option variable has a `variable-interactive' property, the
4499 `set-variable' command uses that value to control reading the new value
4500 for the variable. The property's value is used as if it were the
4501 argument to `interactive'.
4503 *Warning:* If the `defconst' and `defvar' special forms are used
4504 while the variable has a local binding, they set the local binding's
4505 value; the global binding is not changed. This is not what we really
4506 want. To prevent it, use these special forms at top level in a file,
4507 where normally no local binding is in effect, and make sure to load the
4508 file before making a local binding for the variable.
4511 File: lispref.info, Node: Accessing Variables, Next: Setting Variables, Prev: Defining Variables, Up: Variables
4513 Accessing Variable Values
4514 =========================
4516 The usual way to reference a variable is to write the symbol which
4517 names it (*note Symbol Forms::). This requires you to specify the
4518 variable name when you write the program. Usually that is exactly what
4519 you want to do. Occasionally you need to choose at run time which
4520 variable to reference; then you can use `symbol-value'.
4522 - Function: symbol-value symbol
4523 This function returns the value of SYMBOL. This is the value in
4524 the innermost local binding of the symbol, or its global value if
4525 it has no local bindings.
4527 (setq abracadabra 5)
4532 ;; Here the symbol `abracadabra'
4533 ;; is the symbol whose value is examined.
4534 (let ((abracadabra 'foo))
4535 (symbol-value 'abracadabra))
4538 ;; Here the value of `abracadabra',
4540 ;; is the symbol whose value is examined.
4541 (let ((abracadabra 'foo))
4542 (symbol-value abracadabra))
4545 (symbol-value 'abracadabra)
4548 A `void-variable' error is signaled if SYMBOL has neither a local
4549 binding nor a global value.
4552 File: lispref.info, Node: Setting Variables, Next: Variable Scoping, Prev: Accessing Variables, Up: Variables
4554 How to Alter a Variable Value
4555 =============================
4557 The usual way to change the value of a variable is with the special
4558 form `setq'. When you need to compute the choice of variable at run
4559 time, use the function `set'.
4561 - Special Form: setq [symbol form]...
4562 This special form is the most common method of changing a
4563 variable's value. Each SYMBOL is given a new value, which is the
4564 result of evaluating the corresponding FORM. The most-local
4565 existing binding of the symbol is changed.
4567 `setq' does not evaluate SYMBOL; it sets the symbol that you
4568 write. We say that this argument is "automatically quoted". The
4569 `q' in `setq' stands for "quoted."
4571 The value of the `setq' form is the value of the last FORM.
4575 x ; `x' now has a global value.
4578 (setq x 6) ; The local binding of `x' is set.
4581 x ; The global value is unchanged.
4584 Note that the first FORM is evaluated, then the first SYMBOL is
4585 set, then the second FORM is evaluated, then the second SYMBOL is
4588 (setq x 10 ; Notice that `x' is set before
4589 y (1+ x)) ; the value of `y' is computed.
4592 - Function: set symbol value
4593 This function sets SYMBOL's value to VALUE, then returns VALUE.
4594 Since `set' is a function, the expression written for SYMBOL is
4595 evaluated to obtain the symbol to set.
4597 The most-local existing binding of the variable is the binding
4598 that is set; shadowed bindings are not affected.
4601 error--> Symbol's value as variable is void: one
4606 (set two 2) ; `two' evaluates to symbol `one'.
4608 one ; So it is `one' that was set.
4610 (let ((one 1)) ; This binding of `one' is set,
4611 (set 'one 3) ; not the global value.
4617 If SYMBOL is not actually a symbol, a `wrong-type-argument' error
4621 error--> Wrong type argument: symbolp, (x y)
4623 Logically speaking, `set' is a more fundamental primitive than
4624 `setq'. Any use of `setq' can be trivially rewritten to use
4625 `set'; `setq' could even be defined as a macro, given the
4626 availability of `set'. However, `set' itself is rarely used;
4627 beginners hardly need to know about it. It is useful only for
4628 choosing at run time which variable to set. For example, the
4629 command `set-variable', which reads a variable name from the user
4630 and then sets the variable, needs to use `set'.
4632 Common Lisp note: In Common Lisp, `set' always changes the
4633 symbol's special value, ignoring any lexical bindings. In
4634 XEmacs Lisp, all variables and all bindings are (in effect)
4635 special, so `set' always affects the most local existing
4638 One other function for setting a variable is designed to add an
4639 element to a list if it is not already present in the list.
4641 - Function: add-to-list symbol element
4642 This function sets the variable SYMBOL by consing ELEMENT onto the
4643 old value, if ELEMENT is not already a member of that value. It
4644 returns the resulting list, whether updated or not. The value of
4645 SYMBOL had better be a list already before the call.
4647 The argument SYMBOL is not implicitly quoted; `add-to-list' is an
4648 ordinary function, like `set' and unlike `setq'. Quote the
4649 argument yourself if that is what you want.
4651 Here's a scenario showing how to use `add-to-list':
4656 (add-to-list 'foo 'c) ;; Add `c'.
4659 (add-to-list 'foo 'b) ;; No effect.
4662 foo ;; `foo' was changed.
4665 An equivalent expression for `(add-to-list 'VAR VALUE)' is this:
4667 (or (member VALUE VAR)
4668 (setq VAR (cons VALUE VAR)))
4671 File: lispref.info, Node: Variable Scoping, Next: Buffer-Local Variables, Prev: Setting Variables, Up: Variables
4673 Scoping Rules for Variable Bindings
4674 ===================================
4676 A given symbol `foo' may have several local variable bindings,
4677 established at different places in the Lisp program, as well as a global
4678 binding. The most recently established binding takes precedence over
4681 Local bindings in XEmacs Lisp have "indefinite scope" and "dynamic
4682 extent". "Scope" refers to _where_ textually in the source code the
4683 binding can be accessed. Indefinite scope means that any part of the
4684 program can potentially access the variable binding. "Extent" refers
4685 to _when_, as the program is executing, the binding exists. Dynamic
4686 extent means that the binding lasts as long as the activation of the
4687 construct that established it.
4689 The combination of dynamic extent and indefinite scope is called
4690 "dynamic scoping". By contrast, most programming languages use
4691 "lexical scoping", in which references to a local variable must be
4692 located textually within the function or block that binds the variable.
4694 Common Lisp note: Variables declared "special" in Common Lisp are
4695 dynamically scoped, like variables in XEmacs Lisp.
4699 * Scope:: Scope means where in the program a value is visible.
4700 Comparison with other languages.
4701 * Extent:: Extent means how long in time a value exists.
4702 * Impl of Scope:: Two ways to implement dynamic scoping.
4703 * Using Scoping:: How to use dynamic scoping carefully and avoid problems.
4706 File: lispref.info, Node: Scope, Next: Extent, Up: Variable Scoping
4711 XEmacs Lisp uses "indefinite scope" for local variable bindings. This
4712 means that any function anywhere in the program text might access a
4713 given binding of a variable. Consider the following function
4716 (defun binder (x) ; `x' is bound in `binder'.
4717 (foo 5)) ; `foo' is some other function.
4719 (defun user () ; `x' is used in `user'.
4722 In a lexically scoped language, the binding of `x' in `binder' would
4723 never be accessible in `user', because `user' is not textually
4724 contained within the function `binder'. However, in dynamically scoped
4725 XEmacs Lisp, `user' may or may not refer to the binding of `x'
4726 established in `binder', depending on circumstances:
4728 * If we call `user' directly without calling `binder' at all, then
4729 whatever binding of `x' is found, it cannot come from `binder'.
4731 * If we define `foo' as follows and call `binder', then the binding
4732 made in `binder' will be seen in `user':
4737 * If we define `foo' as follows and call `binder', then the binding
4738 made in `binder' _will not_ be seen in `user':
4743 Here, when `foo' is called by `binder', it binds `x'. (The
4744 binding in `foo' is said to "shadow" the one made in `binder'.)
4745 Therefore, `user' will access the `x' bound by `foo' instead of
4746 the one bound by `binder'.
4749 File: lispref.info, Node: Extent, Next: Impl of Scope, Prev: Scope, Up: Variable Scoping
4754 "Extent" refers to the time during program execution that a variable
4755 name is valid. In XEmacs Lisp, a variable is valid only while the form
4756 that bound it is executing. This is called "dynamic extent". "Local"
4757 or "automatic" variables in most languages, including C and Pascal,
4758 have dynamic extent.
4760 One alternative to dynamic extent is "indefinite extent". This
4761 means that a variable binding can live on past the exit from the form
4762 that made the binding. Common Lisp and Scheme, for example, support
4763 this, but XEmacs Lisp does not.
4765 To illustrate this, the function below, `make-add', returns a
4766 function that purports to add N to its own argument M. This would work
4767 in Common Lisp, but it does not work as intended in XEmacs Lisp,
4768 because after the call to `make-add' exits, the variable `n' is no
4769 longer bound to the actual argument 2.
4772 (function (lambda (m) (+ n m)))) ; Return a function.
4774 (fset 'add2 (make-add 2)) ; Define function `add2'
4775 ; with `(make-add 2)'.
4776 => (lambda (m) (+ n m))
4777 (add2 4) ; Try to add 2 to 4.
4778 error--> Symbol's value as variable is void: n
4780 Some Lisp dialects have "closures", objects that are like functions
4781 but record additional variable bindings. XEmacs Lisp does not have
4785 File: lispref.info, Node: Impl of Scope, Next: Using Scoping, Prev: Extent, Up: Variable Scoping
4787 Implementation of Dynamic Scoping
4788 ---------------------------------
4790 A simple sample implementation (which is not how XEmacs Lisp actually
4791 works) may help you understand dynamic binding. This technique is
4792 called "deep binding" and was used in early Lisp systems.
4794 Suppose there is a stack of bindings: variable-value pairs. At entry
4795 to a function or to a `let' form, we can push bindings on the stack for
4796 the arguments or local variables created there. We can pop those
4797 bindings from the stack at exit from the binding construct.
4799 We can find the value of a variable by searching the stack from top
4800 to bottom for a binding for that variable; the value from that binding
4801 is the value of the variable. To set the variable, we search for the
4802 current binding, then store the new value into that binding.
4804 As you can see, a function's bindings remain in effect as long as it
4805 continues execution, even during its calls to other functions. That is
4806 why we say the extent of the binding is dynamic. And any other function
4807 can refer to the bindings, if it uses the same variables while the
4808 bindings are in effect. That is why we say the scope is indefinite.
4810 The actual implementation of variable scoping in XEmacs Lisp uses a
4811 technique called "shallow binding". Each variable has a standard place
4812 in which its current value is always found--the value cell of the
4815 In shallow binding, setting the variable works by storing a value in
4816 the value cell. Creating a new binding works by pushing the old value
4817 (belonging to a previous binding) on a stack, and storing the local
4818 value in the value cell. Eliminating a binding works by popping the
4819 old value off the stack, into the value cell.
4821 We use shallow binding because it has the same results as deep
4822 binding, but runs faster, since there is never a need to search for a
4826 File: lispref.info, Node: Using Scoping, Prev: Impl of Scope, Up: Variable Scoping
4828 Proper Use of Dynamic Scoping
4829 -----------------------------
4831 Binding a variable in one function and using it in another is a
4832 powerful technique, but if used without restraint, it can make programs
4833 hard to understand. There are two clean ways to use this technique:
4835 * Use or bind the variable only in a few related functions, written
4836 close together in one file. Such a variable is used for
4837 communication within one program.
4839 You should write comments to inform other programmers that they
4840 can see all uses of the variable before them, and to advise them
4841 not to add uses elsewhere.
4843 * Give the variable a well-defined, documented meaning, and make all
4844 appropriate functions refer to it (but not bind it or set it)
4845 wherever that meaning is relevant. For example, the variable
4846 `case-fold-search' is defined as "non-`nil' means ignore case when
4847 searching"; various search and replace functions refer to it
4848 directly or through their subroutines, but do not bind or set it.
4850 Then you can bind the variable in other programs, knowing reliably
4851 what the effect will be.
4853 In either case, you should define the variable with `defvar'. This
4854 helps other people understand your program by telling them to look for
4855 inter-function usage. It also avoids a warning from the byte compiler.
4856 Choose the variable's name to avoid name conflicts--don't use short
4860 File: lispref.info, Node: Buffer-Local Variables, Next: Variable Aliases, Prev: Variable Scoping, Up: Variables
4862 Buffer-Local Variables
4863 ======================
4865 Global and local variable bindings are found in most programming
4866 languages in one form or another. XEmacs also supports another, unusual
4867 kind of variable binding: "buffer-local" bindings, which apply only to
4868 one buffer. XEmacs Lisp is meant for programming editing commands, and
4869 having different values for a variable in different buffers is an
4870 important customization method.
4874 * Intro to Buffer-Local:: Introduction and concepts.
4875 * Creating Buffer-Local:: Creating and destroying buffer-local bindings.
4876 * Default Value:: The default value is seen in buffers
4877 that don't have their own local values.
4880 File: lispref.info, Node: Intro to Buffer-Local, Next: Creating Buffer-Local, Up: Buffer-Local Variables
4882 Introduction to Buffer-Local Variables
4883 --------------------------------------
4885 A buffer-local variable has a buffer-local binding associated with a
4886 particular buffer. The binding is in effect when that buffer is
4887 current; otherwise, it is not in effect. If you set the variable while
4888 a buffer-local binding is in effect, the new value goes in that binding,
4889 so the global binding is unchanged; this means that the change is
4890 visible in that buffer alone.
4892 A variable may have buffer-local bindings in some buffers but not in
4893 others. The global binding is shared by all the buffers that don't have
4894 their own bindings. Thus, if you set the variable in a buffer that does
4895 not have a buffer-local binding for it, the new value is visible in all
4896 buffers except those with buffer-local bindings. (Here we are assuming
4897 that there are no `let'-style local bindings to complicate the issue.)
4899 The most common use of buffer-local bindings is for major modes to
4900 change variables that control the behavior of commands. For example, C
4901 mode and Lisp mode both set the variable `paragraph-start' to specify
4902 that only blank lines separate paragraphs. They do this by making the
4903 variable buffer-local in the buffer that is being put into C mode or
4904 Lisp mode, and then setting it to the new value for that mode.
4906 The usual way to make a buffer-local binding is with
4907 `make-local-variable', which is what major mode commands use. This
4908 affects just the current buffer; all other buffers (including those yet
4909 to be created) continue to share the global value.
4911 A more powerful operation is to mark the variable as "automatically
4912 buffer-local" by calling `make-variable-buffer-local'. You can think
4913 of this as making the variable local in all buffers, even those yet to
4914 be created. More precisely, the effect is that setting the variable
4915 automatically makes the variable local to the current buffer if it is
4916 not already so. All buffers start out by sharing the global value of
4917 the variable as usual, but any `setq' creates a buffer-local binding
4918 for the current buffer. The new value is stored in the buffer-local
4919 binding, leaving the (default) global binding untouched. The global
4920 value can no longer be changed with `setq'; you need to use
4921 `setq-default' to do that.
4923 Local variables in a file you edit are also represented by
4924 buffer-local bindings for the buffer that holds the file within XEmacs.
4925 *Note Auto Major Mode::.
4928 File: lispref.info, Node: Creating Buffer-Local, Next: Default Value, Prev: Intro to Buffer-Local, Up: Buffer-Local Variables
4930 Creating and Deleting Buffer-Local Bindings
4931 -------------------------------------------
4933 - Command: make-local-variable variable
4934 This function creates a buffer-local binding in the current buffer
4935 for VARIABLE (a symbol). Other buffers are not affected. The
4936 value returned is VARIABLE.
4938 The buffer-local value of VARIABLE starts out as the same value
4939 VARIABLE previously had. If VARIABLE was void, it remains void.
4942 (setq foo 5) ; Affects all buffers.
4944 (make-local-variable 'foo) ; Now it is local in `b1'.
4946 foo ; That did not change
4948 (setq foo 6) ; Change the value
4953 ;; In buffer `b2', the value hasn't changed.
4959 Making a variable buffer-local within a `let'-binding for that
4960 variable does not work. This is because `let' does not distinguish
4961 between different kinds of bindings; it knows only which variable
4962 the binding was made for.
4964 *Please note:* do not use `make-local-variable' for a hook
4965 variable. Instead, use `make-local-hook'. *Note Hooks::.
4967 - Command: make-variable-buffer-local variable
4968 This function marks VARIABLE (a symbol) automatically
4969 buffer-local, so that any subsequent attempt to set it will make it
4970 local to the current buffer at the time.
4972 The value returned is VARIABLE.
4974 - Function: local-variable-p variable buffer &optional after-set
4975 This returns `t' if VARIABLE is buffer-local in buffer BUFFER;
4978 If optional third arg AFTER-SET is non-`nil', return `t' if SYMBOL
4979 would be buffer-local after it is set, regardless of whether it is
4982 A `nil' value for BUFFER is _not_ the same as `(current-buffer)',
4983 but means "no buffer". Specifically:
4985 If BUFFER is `nil' and AFTER-SET is `nil', a return value of `t'
4986 indicates that the variable is one of the special built-in
4987 variables that is always buffer-local. (This includes
4988 `buffer-file-name', `buffer-read-only', `buffer-undo-list', and
4991 If BUFFER is `nil' and AFTER-SET is `t', a return value of `t'
4992 indicates that the variable has had `make-variable-buffer-local'
4995 - Function: buffer-local-variables &optional buffer
4996 This function returns a list describing the buffer-local variables
4997 in buffer BUFFER. It returns an association list (*note
4998 Association Lists::) in which each association contains one
4999 buffer-local variable and its value. When a buffer-local variable
5000 is void in BUFFER, then it appears directly in the resulting list.
5001 If BUFFER is omitted, the current buffer is used.
5003 (make-local-variable 'foobar)
5004 (makunbound 'foobar)
5005 (make-local-variable 'bind-me)
5007 (setq lcl (buffer-local-variables))
5008 ;; First, built-in variables local in all buffers:
5009 => ((mark-active . nil)
5010 (buffer-undo-list nil)
5011 (mode-name . "Fundamental")
5013 ;; Next, non-built-in local variables.
5014 ;; This one is local and void:
5016 ;; This one is local and nonvoid:
5019 Note that storing new values into the CDRs of cons cells in this
5020 list does _not_ change the local values of the variables.
5022 - Command: kill-local-variable variable
5023 This function deletes the buffer-local binding (if any) for
5024 VARIABLE (a symbol) in the current buffer. As a result, the
5025 global (default) binding of VARIABLE becomes visible in this
5026 buffer. Usually this results in a change in the value of
5027 VARIABLE, since the global value is usually different from the
5028 buffer-local value just eliminated.
5030 If you kill the local binding of a variable that automatically
5031 becomes local when set, this makes the global value visible in the
5032 current buffer. However, if you set the variable again, that will
5033 once again create a local binding for it.
5035 `kill-local-variable' returns VARIABLE.
5037 This function is a command because it is sometimes useful to kill
5038 one buffer-local variable interactively, just as it is useful to
5039 create buffer-local variables interactively.
5041 - Function: kill-all-local-variables
5042 This function eliminates all the buffer-local variable bindings of
5043 the current buffer except for variables marked as "permanent". As
5044 a result, the buffer will see the default values of most variables.
5046 This function also resets certain other information pertaining to
5047 the buffer: it sets the local keymap to `nil', the syntax table to
5048 the value of `standard-syntax-table', and the abbrev table to the
5049 value of `fundamental-mode-abbrev-table'.
5051 Every major mode command begins by calling this function, which
5052 has the effect of switching to Fundamental mode and erasing most
5053 of the effects of the previous major mode. To ensure that this
5054 does its job, the variables that major modes set should not be
5057 `kill-all-local-variables' returns `nil'.
5059 A local variable is "permanent" if the variable name (a symbol) has a
5060 `permanent-local' property that is non-`nil'. Permanent locals are
5061 appropriate for data pertaining to where the file came from or how to
5062 save it, rather than with how to edit the contents.
5065 File: lispref.info, Node: Default Value, Prev: Creating Buffer-Local, Up: Buffer-Local Variables
5067 The Default Value of a Buffer-Local Variable
5068 --------------------------------------------
5070 The global value of a variable with buffer-local bindings is also
5071 called the "default" value, because it is the value that is in effect
5072 except when specifically overridden.
5074 The functions `default-value' and `setq-default' access and change a
5075 variable's default value regardless of whether the current buffer has a
5076 buffer-local binding. For example, you could use `setq-default' to
5077 change the default setting of `paragraph-start' for most buffers; and
5078 this would work even when you are in a C or Lisp mode buffer that has a
5079 buffer-local value for this variable.
5081 The special forms `defvar' and `defconst' also set the default value
5082 (if they set the variable at all), rather than any local value.
5084 - Function: default-value symbol
5085 This function returns SYMBOL's default value. This is the value
5086 that is seen in buffers that do not have their own values for this
5087 variable. If SYMBOL is not buffer-local, this is equivalent to
5088 `symbol-value' (*note Accessing Variables::).
5090 - Function: default-boundp symbol
5091 The function `default-boundp' tells you whether SYMBOL's default
5092 value is nonvoid. If `(default-boundp 'foo)' returns `nil', then
5093 `(default-value 'foo)' would get an error.
5095 `default-boundp' is to `default-value' as `boundp' is to
5098 - Special Form: setq-default symbol value
5099 This sets the default value of SYMBOL to VALUE. It does not
5100 evaluate SYMBOL, but does evaluate VALUE. The value of the
5101 `setq-default' form is VALUE.
5103 If a SYMBOL is not buffer-local for the current buffer, and is not
5104 marked automatically buffer-local, `setq-default' has the same
5105 effect as `setq'. If SYMBOL is buffer-local for the current
5106 buffer, then this changes the value that other buffers will see
5107 (as long as they don't have a buffer-local value), but not the
5108 value that the current buffer sees.
5111 (make-local-variable 'local)
5113 (setq local 'value-in-foo)
5115 (setq-default local 'new-default)
5119 (default-value 'local)
5122 ;; In (the new) buffer `bar':
5125 (default-value 'local)
5127 (setq local 'another-default)
5129 (default-value 'local)
5132 ;; Back in buffer `foo':
5135 (default-value 'local)
5138 - Function: set-default symbol value
5139 This function is like `setq-default', except that SYMBOL is
5142 (set-default (car '(a b c)) 23)
5148 File: lispref.info, Node: Variable Aliases, Prev: Buffer-Local Variables, Up: Variables
5153 You can define a variable as an "alias" for another. Any time you
5154 reference the former variable, the current value of the latter is
5155 returned. Any time you change the value of the former variable, the
5156 value of the latter is actually changed. This is useful in cases where
5157 you want to rename a variable but still make old code work (*note
5160 - Function: defvaralias variable alias
5161 This function defines VARIABLE as an alias for ALIAS.
5162 Thenceforth, any operations performed on VARIABLE will actually be
5163 performed on ALIAS. Both VARIABLE and ALIAS should be symbols.
5164 If ALIAS is `nil', remove any aliases for VARIABLE. ALIAS can
5165 itself be aliased, and the chain of variable aliases will be
5166 followed appropriately. If VARIABLE already has a value, this
5167 value will be shadowed until the alias is removed, at which point
5168 it will be restored. Currently VARIABLE cannot be a built-in
5169 variable, a variable that has a buffer-local value in any buffer,
5170 or the symbols `nil' or `t'.
5172 - Function: variable-alias variable &optional follow-past-lisp-magic
5173 If VARIABLE is aliased to another variable, this function returns
5174 that variable. VARIABLE should be a symbol. If VARIABLE is not
5175 aliased, this function returns `nil'.
5177 - Function: indirect-variable object &optional follow-past-lisp-magic
5178 This function returns the variable at the end of OBJECT's
5179 variable-alias chain. If OBJECT is a symbol, follow all variable
5180 aliases and return the final (non-aliased) symbol. If OBJECT is
5181 not a symbol, just return it. Signal a
5182 `cyclic-variable-indirection' error if there is a loop in the
5183 variable chain of symbols.
5186 File: lispref.info, Node: Functions, Next: Macros, Prev: Variables, Up: Top
5191 A Lisp program is composed mainly of Lisp functions. This chapter
5192 explains what functions are, how they accept arguments, and how to
5197 * What Is a Function:: Lisp functions vs. primitives; terminology.
5198 * Lambda Expressions:: How functions are expressed as Lisp objects.
5199 * Function Names:: A symbol can serve as the name of a function.
5200 * Defining Functions:: Lisp expressions for defining functions.
5201 * Calling Functions:: How to use an existing function.
5202 * Mapping Functions:: Applying a function to each element of a list, etc.
5203 * Anonymous Functions:: Lambda expressions are functions with no names.
5204 * Function Cells:: Accessing or setting the function definition
5206 * Inline Functions:: Defining functions that the compiler will open code.
5207 * Related Topics:: Cross-references to specific Lisp primitives
5208 that have a special bearing on how functions work.
5211 File: lispref.info, Node: What Is a Function, Next: Lambda Expressions, Up: Functions
5216 In a general sense, a function is a rule for carrying on a computation
5217 given several values called "arguments". The result of the computation
5218 is called the value of the function. The computation can also have
5219 side effects: lasting changes in the values of variables or the
5220 contents of data structures.
5222 Here are important terms for functions in XEmacs Lisp and for other
5223 function-like objects.
5226 In XEmacs Lisp, a "function" is anything that can be applied to
5227 arguments in a Lisp program. In some cases, we use it more
5228 specifically to mean a function written in Lisp. Special forms and
5229 macros are not functions.
5232 A "primitive" is a function callable from Lisp that is written in
5233 C, such as `car' or `append'. These functions are also called
5234 "built-in" functions or "subrs". (Special forms are also
5235 considered primitives.)
5237 Usually the reason that a function is a primitives is because it is
5238 fundamental, because it provides a low-level interface to operating
5239 system services, or because it needs to run fast. Primitives can
5240 be modified or added only by changing the C sources and
5241 recompiling the editor. See *Note Writing Lisp Primitives:
5242 (internals)Writing Lisp Primitives.
5245 A "lambda expression" is a function written in Lisp. These are
5246 described in the following section. *Note Lambda Expressions::.
5249 A "special form" is a primitive that is like a function but does
5250 not evaluate all of its arguments in the usual way. It may
5251 evaluate only some of the arguments, or may evaluate them in an
5252 unusual order, or several times. Many special forms are described
5253 in *Note Control Structures::.
5256 A "macro" is a construct defined in Lisp by the programmer. It
5257 differs from a function in that it translates a Lisp expression
5258 that you write into an equivalent expression to be evaluated
5259 instead of the original expression. Macros enable Lisp
5260 programmers to do the sorts of things that special forms can do.
5261 *Note Macros::, for how to define and use macros.
5264 A "command" is an object that `command-execute' can invoke; it is
5265 a possible definition for a key sequence. Some functions are
5266 commands; a function written in Lisp is a command if it contains an
5267 interactive declaration (*note Defining Commands::). Such a
5268 function can be called from Lisp expressions like other functions;
5269 in this case, the fact that the function is a command makes no
5272 Keyboard macros (strings and vectors) are commands also, even
5273 though they are not functions. A symbol is a command if its
5274 function definition is a command; such symbols can be invoked with
5275 `M-x'. The symbol is a function as well if the definition is a
5276 function. *Note Command Overview::.
5279 A "keystroke command" is a command that is bound to a key sequence
5280 (typically one to three keystrokes). The distinction is made here
5281 merely to avoid confusion with the meaning of "command" in
5282 non-Emacs editors; for Lisp programs, the distinction is normally
5286 A "compiled function" is a function that has been compiled by the
5287 byte compiler. *Note Compiled-Function Type::.
5289 - Function: subrp object
5290 This function returns `t' if OBJECT is a built-in function (i.e.,
5293 (subrp 'message) ; `message' is a symbol,
5294 => nil ; not a subr object.
5295 (subrp (symbol-function 'message))
5298 - Function: compiled-function-p object
5299 This function returns `t' if OBJECT is a compiled function. For
5302 (compiled-function-p (symbol-function 'next-line))
5306 File: lispref.info, Node: Lambda Expressions, Next: Function Names, Prev: What Is a Function, Up: Functions
5311 A function written in Lisp is a list that looks like this:
5313 (lambda (ARG-VARIABLES...)
5314 [DOCUMENTATION-STRING]
5315 [INTERACTIVE-DECLARATION]
5318 Such a list is called a "lambda expression". In XEmacs Lisp, it
5319 actually is valid as an expression--it evaluates to itself. In some
5320 other Lisp dialects, a lambda expression is not a valid expression at
5321 all. In either case, its main use is not to be evaluated as an
5322 expression, but to be called as a function.
5326 * Lambda Components:: The parts of a lambda expression.
5327 * Simple Lambda:: A simple example.
5328 * Argument List:: Details and special features of argument lists.
5329 * Function Documentation:: How to put documentation in a function.
5332 File: lispref.info, Node: Lambda Components, Next: Simple Lambda, Up: Lambda Expressions
5334 Components of a Lambda Expression
5335 ---------------------------------
5337 A function written in Lisp (a "lambda expression") is a list that looks
5340 (lambda (ARG-VARIABLES...)
5341 [DOCUMENTATION-STRING]
5342 [INTERACTIVE-DECLARATION]
5345 The first element of a lambda expression is always the symbol `lambda'.
5346 This indicates that the list represents a function. The reason
5347 functions are defined to start with `lambda' is so that other lists,
5348 intended for other uses, will not accidentally be valid as functions.
5350 The second element is a list of symbols-the argument variable names.
5351 This is called the "lambda list". When a Lisp function is called, the
5352 argument values are matched up against the variables in the lambda
5353 list, which are given local bindings with the values provided. *Note
5356 The documentation string is a Lisp string object placed within the
5357 function definition to describe the function for the XEmacs help
5358 facilities. *Note Function Documentation::.
5360 The interactive declaration is a list of the form `(interactive
5361 CODE-STRING)'. This declares how to provide arguments if the function
5362 is used interactively. Functions with this declaration are called
5363 "commands"; they can be called using `M-x' or bound to a key.
5364 Functions not intended to be called in this way should not have
5365 interactive declarations. *Note Defining Commands::, for how to write
5366 an interactive declaration.
5368 The rest of the elements are the "body" of the function: the Lisp
5369 code to do the work of the function (or, as a Lisp programmer would say,
5370 "a list of Lisp forms to evaluate"). The value returned by the
5371 function is the value returned by the last element of the body.
5374 File: lispref.info, Node: Simple Lambda, Next: Argument List, Prev: Lambda Components, Up: Lambda Expressions
5376 A Simple Lambda-Expression Example
5377 ----------------------------------
5379 Consider for example the following function:
5381 (lambda (a b c) (+ a b c))
5383 We can call this function by writing it as the CAR of an expression,
5386 ((lambda (a b c) (+ a b c))
5389 This call evaluates the body of the lambda expression with the variable
5390 `a' bound to 1, `b' bound to 2, and `c' bound to 3. Evaluation of the
5391 body adds these three numbers, producing the result 6; therefore, this
5392 call to the function returns the value 6.
5394 Note that the arguments can be the results of other function calls,
5397 ((lambda (a b c) (+ a b c))
5400 This evaluates the arguments `1', `(* 2 3)', and `(- 5 4)' from left to
5401 right. Then it applies the lambda expression to the argument values 1,
5402 6 and 1 to produce the value 8.
5404 It is not often useful to write a lambda expression as the CAR of a
5405 form in this way. You can get the same result, of making local
5406 variables and giving them values, using the special form `let' (*note
5407 Local Variables::). And `let' is clearer and easier to use. In
5408 practice, lambda expressions are either stored as the function
5409 definitions of symbols, to produce named functions, or passed as
5410 arguments to other functions (*note Anonymous Functions::).
5412 However, calls to explicit lambda expressions were very useful in the
5413 old days of Lisp, before the special form `let' was invented. At that
5414 time, they were the only way to bind and initialize local variables.
5417 File: lispref.info, Node: Argument List, Next: Function Documentation, Prev: Simple Lambda, Up: Lambda Expressions
5419 Advanced Features of Argument Lists
5420 -----------------------------------
5422 Our simple sample function, `(lambda (a b c) (+ a b c))', specifies
5423 three argument variables, so it must be called with three arguments: if
5424 you try to call it with only two arguments or four arguments, you get a
5425 `wrong-number-of-arguments' error.
5427 It is often convenient to write a function that allows certain
5428 arguments to be omitted. For example, the function `substring' accepts
5429 three arguments--a string, the start index and the end index--but the
5430 third argument defaults to the LENGTH of the string if you omit it. It
5431 is also convenient for certain functions to accept an indefinite number
5432 of arguments, as the functions `list' and `+' do.
5434 To specify optional arguments that may be omitted when a function is
5435 called, simply include the keyword `&optional' before the optional
5436 arguments. To specify a list of zero or more extra arguments, include
5437 the keyword `&rest' before one final argument.
5439 Thus, the complete syntax for an argument list is as follows:
5442 [&optional OPTIONAL-VARS...]
5445 The square brackets indicate that the `&optional' and `&rest' clauses,
5446 and the variables that follow them, are optional.
5448 A call to the function requires one actual argument for each of the
5449 REQUIRED-VARS. There may be actual arguments for zero or more of the
5450 OPTIONAL-VARS, and there cannot be any actual arguments beyond that
5451 unless the lambda list uses `&rest'. In that case, there may be any
5452 number of extra actual arguments.
5454 If actual arguments for the optional and rest variables are omitted,
5455 then they always default to `nil'. There is no way for the function to
5456 distinguish between an explicit argument of `nil' and an omitted
5457 argument. However, the body of the function is free to consider `nil'
5458 an abbreviation for some other meaningful value. This is what
5459 `substring' does; `nil' as the third argument to `substring' means to
5460 use the length of the string supplied.
5462 Common Lisp note: Common Lisp allows the function to specify what
5463 default value to use when an optional argument is omitted; XEmacs
5464 Lisp always uses `nil'.
5466 For example, an argument list that looks like this:
5468 (a b &optional c d &rest e)
5470 binds `a' and `b' to the first two actual arguments, which are
5471 required. If one or two more arguments are provided, `c' and `d' are
5472 bound to them respectively; any arguments after the first four are
5473 collected into a list and `e' is bound to that list. If there are only
5474 two arguments, `c' is `nil'; if two or three arguments, `d' is `nil';
5475 if four arguments or fewer, `e' is `nil'.
5477 There is no way to have required arguments following optional
5478 ones--it would not make sense. To see why this must be so, suppose
5479 that `c' in the example were optional and `d' were required. Suppose
5480 three actual arguments are given; which variable would the third
5481 argument be for? Similarly, it makes no sense to have any more
5482 arguments (either required or optional) after a `&rest' argument.
5484 Here are some examples of argument lists and proper calls:
5486 ((lambda (n) (1+ n)) ; One required:
5487 1) ; requires exactly one argument.
5489 ((lambda (n &optional n1) ; One required and one optional:
5490 (if n1 (+ n n1) (1+ n))) ; 1 or 2 arguments.
5493 ((lambda (n &rest ns) ; One required and one rest:
5494 (+ n (apply '+ ns))) ; 1 or more arguments.
5499 File: lispref.info, Node: Function Documentation, Prev: Argument List, Up: Lambda Expressions
5501 Documentation Strings of Functions
5502 ----------------------------------
5504 A lambda expression may optionally have a "documentation string" just
5505 after the lambda list. This string does not affect execution of the
5506 function; it is a kind of comment, but a systematized comment which
5507 actually appears inside the Lisp world and can be used by the XEmacs
5508 help facilities. *Note Documentation::, for how the
5509 DOCUMENTATION-STRING is accessed.
5511 It is a good idea to provide documentation strings for all the
5512 functions in your program, even those that are only called from within
5513 your program. Documentation strings are like comments, except that they
5514 are easier to access.
5516 The first line of the documentation string should stand on its own,
5517 because `apropos' displays just this first line. It should consist of
5518 one or two complete sentences that summarize the function's purpose.
5520 The start of the documentation string is usually indented in the
5521 source file, but since these spaces come before the starting
5522 double-quote, they are not part of the string. Some people make a
5523 practice of indenting any additional lines of the string so that the
5524 text lines up in the program source. _This is a mistake._ The
5525 indentation of the following lines is inside the string; what looks
5526 nice in the source code will look ugly when displayed by the help
5529 You may wonder how the documentation string could be optional, since
5530 there are required components of the function that follow it (the body).
5531 Since evaluation of a string returns that string, without any side
5532 effects, it has no effect if it is not the last form in the body.
5533 Thus, in practice, there is no confusion between the first form of the
5534 body and the documentation string; if the only body form is a string
5535 then it serves both as the return value and as the documentation.
5538 File: lispref.info, Node: Function Names, Next: Defining Functions, Prev: Lambda Expressions, Up: Functions
5543 In most computer languages, every function has a name; the idea of a
5544 function without a name is nonsensical. In Lisp, a function in the
5545 strictest sense has no name. It is simply a list whose first element is
5546 `lambda', or a primitive subr-object.
5548 However, a symbol can serve as the name of a function. This happens
5549 when you put the function in the symbol's "function cell" (*note Symbol
5550 Components::). Then the symbol itself becomes a valid, callable
5551 function, equivalent to the list or subr-object that its function cell
5552 refers to. The contents of the function cell are also called the
5553 symbol's "function definition". The procedure of using a symbol's
5554 function definition in place of the symbol is called "symbol function
5555 indirection"; see *Note Function Indirection::.
5557 In practice, nearly all functions are given names in this way and
5558 referred to through their names. For example, the symbol `car' works
5559 as a function and does what it does because the primitive subr-object
5560 `#<subr car>' is stored in its function cell.
5562 We give functions names because it is convenient to refer to them by
5563 their names in Lisp expressions. For primitive subr-objects such as
5564 `#<subr car>', names are the only way you can refer to them: there is
5565 no read syntax for such objects. For functions written in Lisp, the
5566 name is more convenient to use in a call than an explicit lambda
5567 expression. Also, a function with a name can refer to itself--it can
5568 be recursive. Writing the function's name in its own definition is much
5569 more convenient than making the function definition point to itself
5570 (something that is not impossible but that has various disadvantages in
5573 We often identify functions with the symbols used to name them. For
5574 example, we often speak of "the function `car'", not distinguishing
5575 between the symbol `car' and the primitive subr-object that is its
5576 function definition. For most purposes, there is no need to
5579 Even so, keep in mind that a function need not have a unique name.
5580 While a given function object _usually_ appears in the function cell of
5581 only one symbol, this is just a matter of convenience. It is easy to
5582 store it in several symbols using `fset'; then each of the symbols is
5583 equally well a name for the same function.
5585 A symbol used as a function name may also be used as a variable;
5586 these two uses of a symbol are independent and do not conflict.
5589 File: lispref.info, Node: Defining Functions, Next: Calling Functions, Prev: Function Names, Up: Functions
5594 We usually give a name to a function when it is first created. This is
5595 called "defining a function", and it is done with the `defun' special
5598 - Special Form: defun name argument-list body-forms
5599 `defun' is the usual way to define new Lisp functions. It defines
5600 the symbol NAME as a function that looks like this:
5602 (lambda ARGUMENT-LIST . BODY-FORMS)
5604 `defun' stores this lambda expression in the function cell of
5605 NAME. It returns the value NAME, but usually we ignore this value.
5607 As described previously (*note Lambda Expressions::),
5608 ARGUMENT-LIST is a list of argument names and may include the
5609 keywords `&optional' and `&rest'. Also, the first two forms in
5610 BODY-FORMS may be a documentation string and an interactive
5613 There is no conflict if the same symbol NAME is also used as a
5614 variable, since the symbol's value cell is independent of the
5615 function cell. *Note Symbol Components::.
5617 Here are some examples:
5624 (defun bar (a &optional b &rest c)
5632 error--> Wrong number of arguments.
5634 (defun capitalize-backwards ()
5635 "Upcase the last letter of a word."
5640 (capitalize-word 1))
5641 => capitalize-backwards
5643 Be careful not to redefine existing functions unintentionally.
5644 `defun' redefines even primitive functions such as `car' without
5645 any hesitation or notification. Redefining a function already
5646 defined is often done deliberately, and there is no way to
5647 distinguish deliberate redefinition from unintentional
5650 - Function: define-function name definition
5651 - Function: defalias name definition
5652 These equivalent special forms define the symbol NAME as a
5653 function, with definition DEFINITION (which can be any valid Lisp
5656 The proper place to use `define-function' or `defalias' is where a
5657 specific function name is being defined--especially where that
5658 name appears explicitly in the source file being loaded. This is
5659 because `define-function' and `defalias' record which file defined
5660 the function, just like `defun'. (*note Unloading::).
5662 By contrast, in programs that manipulate function definitions for
5663 other purposes, it is better to use `fset', which does not keep
5666 See also `defsubst', which defines a function like `defun' and tells
5667 the Lisp compiler to open-code it. *Note Inline Functions::.
5670 File: lispref.info, Node: Calling Functions, Next: Mapping Functions, Prev: Defining Functions, Up: Functions
5675 Defining functions is only half the battle. Functions don't do
5676 anything until you "call" them, i.e., tell them to run. Calling a
5677 function is also known as "invocation".
5679 The most common way of invoking a function is by evaluating a list.
5680 For example, evaluating the list `(concat "a" "b")' calls the function
5681 `concat' with arguments `"a"' and `"b"'. *Note Evaluation::, for a
5682 description of evaluation.
5684 When you write a list as an expression in your program, the function
5685 name is part of the program. This means that you choose which function
5686 to call, and how many arguments to give it, when you write the program.
5687 Usually that's just what you want. Occasionally you need to decide at
5688 run time which function to call. To do that, use the functions
5689 `funcall' and `apply'.
5691 - Function: funcall function &rest arguments
5692 `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
5695 Since `funcall' is a function, all of its arguments, including
5696 FUNCTION, are evaluated before `funcall' is called. This means
5697 that you can use any expression to obtain the function to be
5698 called. It also means that `funcall' does not see the expressions
5699 you write for the ARGUMENTS, only their values. These values are
5700 _not_ evaluated a second time in the act of calling FUNCTION;
5701 `funcall' enters the normal procedure for calling a function at the
5702 place where the arguments have already been evaluated.
5704 The argument FUNCTION must be either a Lisp function or a
5705 primitive function. Special forms and macros are not allowed,
5706 because they make sense only when given the "unevaluated" argument
5707 expressions. `funcall' cannot provide these because, as we saw
5708 above, it never knows them in the first place.
5712 (funcall f 'x 'y 'z)
5714 (funcall f 'x 'y '(z))
5716 (funcall 'and t nil)
5717 error--> Invalid function: #<subr and>
5719 Compare these example with the examples of `apply'.
5721 - Function: apply function &rest arguments
5722 `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but
5723 with one difference: the last of ARGUMENTS is a list of arguments
5724 to give to FUNCTION, rather than a single argument. We also say
5725 that `apply' "spreads" this list so that each individual element
5726 becomes an argument.
5728 `apply' returns the result of calling FUNCTION. As with
5729 `funcall', FUNCTION must either be a Lisp function or a primitive
5730 function; special forms and macros do not make sense in `apply'.
5735 error--> Wrong type argument: listp, z
5736 (apply '+ 1 2 '(3 4))
5738 (apply '+ '(1 2 3 4))
5741 (apply 'append '((a b c) nil (x y z) nil))
5744 For an interesting example of using `apply', see the description of
5745 `mapcar', in *Note Mapping Functions::.
5747 It is common for Lisp functions to accept functions as arguments or
5748 find them in data structures (especially in hook variables and property
5749 lists) and call them using `funcall' or `apply'. Functions that accept
5750 function arguments are often called "functionals".
5752 Sometimes, when you call a functional, it is useful to supply a no-op
5753 function as the argument. Here are two different kinds of no-op
5756 - Function: identity arg
5757 This function returns ARG and has no side effects.
5759 - Command: ignore &rest args
5760 This function ignores any arguments and returns `nil'.
5763 File: lispref.info, Node: Mapping Functions, Next: Anonymous Functions, Prev: Calling Functions, Up: Functions
5768 A "mapping function" applies a given function to each element of a list
5769 or other collection. XEmacs Lisp has several such functions; `mapcar'
5770 and `mapconcat', which scan a list, are described here. *Note
5771 Creating Symbols::, for the function `mapatoms' which maps over the
5772 symbols in an obarray.
5774 Mapping functions should never modify the sequence being mapped over.
5775 The results are unpredictable.
5777 - Function: mapcar function sequence
5778 `mapcar' applies FUNCTION to each element of SEQUENCE in turn, and
5779 returns a list of the results.
5781 The argument SEQUENCE can be any kind of sequence; that is, a
5782 list, a vector, a bit vector, or a string. The result is always a
5783 list. The length of the result is the same as the length of
5788 (mapcar 'car '((a b) (c d) (e f)))
5790 (mapcar '1+ [1 2 3])
5792 (mapcar 'char-to-string "abc")
5795 ;; Call each function in `my-hooks'.
5796 (mapcar 'funcall my-hooks)
5798 (defun mapcar* (f &rest args)
5799 "Apply FUNCTION to successive cars of all ARGS.
5800 Return the list of results."
5801 ;; If no list is exhausted,
5802 (if (not (memq 'nil args))
5803 ;; apply function to CARs.
5804 (cons (apply f (mapcar 'car args))
5806 ;; Recurse for rest of elements.
5807 (mapcar 'cdr args)))))
5809 (mapcar* 'cons '(a b c) '(1 2 3 4))
5810 => ((a . 1) (b . 2) (c . 3))
5812 - Function: mapconcat function sequence separator
5813 `mapconcat' applies FUNCTION to each element of SEQUENCE: the
5814 results, which must be strings, are concatenated. Between each
5815 pair of result strings, `mapconcat' inserts the string SEPARATOR.
5816 Usually SEPARATOR contains a space or comma or other suitable
5819 The argument FUNCTION must be a function that can take one
5820 argument and return a string. The argument SEQUENCE can be any
5821 kind of sequence; that is, a list, a vector, a bit vector, or a
5824 (mapconcat 'symbol-name
5825 '(The cat in the hat)
5827 => "The cat in the hat"
5829 (mapconcat (function (lambda (x) (format "%c" (1+ x))))
5835 File: lispref.info, Node: Anonymous Functions, Next: Function Cells, Prev: Mapping Functions, Up: Functions
5840 In Lisp, a function is a list that starts with `lambda', a byte-code
5841 function compiled from such a list, or alternatively a primitive
5842 subr-object; names are "extra". Although usually functions are defined
5843 with `defun' and given names at the same time, it is occasionally more
5844 concise to use an explicit lambda expression--an anonymous function.
5845 Such a list is valid wherever a function name is.
5847 Any method of creating such a list makes a valid function. Even
5850 (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
5851 => (lambda (x) (+ 12 x))
5853 This computes a list that looks like `(lambda (x) (+ 12 x))' and makes
5854 it the value (_not_ the function definition!) of `silly'.
5856 Here is how we might call this function:
5861 (It does _not_ work to write `(silly 1)', because this function is not
5862 the _function definition_ of `silly'. We have not given `silly' any
5863 function definition, just a value as a variable.)
5865 Most of the time, anonymous functions are constants that appear in
5866 your program. For example, you might want to pass one as an argument
5867 to the function `mapcar', which applies any given function to each
5868 element of a list. Here we pass an anonymous function that multiplies
5871 (defun double-each (list)
5872 (mapcar '(lambda (x) (* 2 x)) list))
5874 (double-each '(2 11))
5877 In such cases, we usually use the special form `function' instead of
5878 simple quotation to quote the anonymous function.
5880 - Special Form: function function-object
5881 This special form returns FUNCTION-OBJECT without evaluating it.
5882 In this, it is equivalent to `quote'. However, it serves as a
5883 note to the XEmacs Lisp compiler that FUNCTION-OBJECT is intended
5884 to be used only as a function, and therefore can safely be
5885 compiled. Contrast this with `quote', in *Note Quoting::.
5887 Using `function' instead of `quote' makes a difference inside a
5888 function or macro that you are going to compile. For example:
5890 (defun double-each (list)
5891 (mapcar (function (lambda (x) (* 2 x))) list))
5893 (double-each '(2 11))
5896 If this definition of `double-each' is compiled, the anonymous function
5897 is compiled as well. By contrast, in the previous definition where
5898 ordinary `quote' is used, the argument passed to `mapcar' is the
5901 (lambda (x) (* x 2))
5903 The Lisp compiler cannot assume this list is a function, even though it
5904 looks like one, since it does not know what `mapcar' does with the
5905 list. Perhaps `mapcar' will check that the CAR of the third element is
5906 the symbol `*'! The advantage of `function' is that it tells the
5907 compiler to go ahead and compile the constant function.
5909 We sometimes write `function' instead of `quote' when quoting the
5910 name of a function, but this usage is just a sort of comment.
5912 (function SYMBOL) == (quote SYMBOL) == 'SYMBOL
5914 See `documentation' in *Note Accessing Documentation::, for a
5915 realistic example using `function' and an anonymous function.
5918 File: lispref.info, Node: Function Cells, Next: Inline Functions, Prev: Anonymous Functions, Up: Functions
5920 Accessing Function Cell Contents
5921 ================================
5923 The "function definition" of a symbol is the object stored in the
5924 function cell of the symbol. The functions described here access, test,
5925 and set the function cell of symbols.
5927 See also the function `indirect-function' in *Note Function
5930 - Function: symbol-function symbol
5931 This returns the object in the function cell of SYMBOL. If the
5932 symbol's function cell is void, a `void-function' error is
5935 This function does not check that the returned object is a
5936 legitimate function.
5938 (defun bar (n) (+ n 2))
5940 (symbol-function 'bar)
5941 => (lambda (n) (+ n 2))
5944 (symbol-function 'baz)
5947 If you have never given a symbol any function definition, we say that
5948 that symbol's function cell is "void". In other words, the function
5949 cell does not have any Lisp object in it. If you try to call such a
5950 symbol as a function, it signals a `void-function' error.
5952 Note that void is not the same as `nil' or the symbol `void'. The
5953 symbols `nil' and `void' are Lisp objects, and can be stored into a
5954 function cell just as any other object can be (and they can be valid
5955 functions if you define them in turn with `defun'). A void function
5956 cell contains no object whatsoever.
5958 You can test the voidness of a symbol's function definition with
5959 `fboundp'. After you have given a symbol a function definition, you
5960 can make it void once more using `fmakunbound'.
5962 - Function: fboundp symbol
5963 This function returns `t' if SYMBOL has an object in its function
5964 cell, `nil' otherwise. It does not check that the object is a
5965 legitimate function.
5967 - Function: fmakunbound symbol
5968 This function makes SYMBOL's function cell void, so that a
5969 subsequent attempt to access this cell will cause a `void-function'
5970 error. (See also `makunbound', in *Note Local Variables::.)
5979 error--> Symbol's function definition is void: foo
5981 - Function: fset symbol object
5982 This function stores OBJECT in the function cell of SYMBOL. The
5983 result is OBJECT. Normally OBJECT should be a function or the
5984 name of a function, but this is not checked.
5986 There are three normal uses of this function:
5988 * Copying one symbol's function definition to another. (In
5989 other words, making an alternate name for a function.)
5991 * Giving a symbol a function definition that is not a list and
5992 therefore cannot be made with `defun'. For example, you can
5993 use `fset' to give a symbol SYMBOL1 a function definition
5994 which is another symbol SYMBOL2; then SYMBOL1 serves as an
5995 alias for whatever definition SYMBOL2 presently has.
5997 * In constructs for defining or altering functions. If `defun'
5998 were not a primitive, it could be written in Lisp (as a
5999 macro) using `fset'.
6001 Here are examples of the first two uses:
6003 ;; Give `first' the same definition `car' has.
6004 (fset 'first (symbol-function 'car))
6009 ;; Make the symbol `car' the function definition of `xfirst'.
6014 (symbol-function 'xfirst)
6016 (symbol-function (symbol-function 'xfirst))
6019 ;; Define a named keyboard macro.
6020 (fset 'kill-two-lines "\^u2\^k")
6023 See also the related functions `define-function' and `defalias',
6024 in *Note Defining Functions::.
6026 When writing a function that extends a previously defined function,
6027 the following idiom is sometimes used:
6029 (fset 'old-foo (symbol-function 'foo))
6031 "Just like old-foo, except more so."
6035 This does not work properly if `foo' has been defined to autoload. In
6036 such a case, when `foo' calls `old-foo', Lisp attempts to define
6037 `old-foo' by loading a file. Since this presumably defines `foo'
6038 rather than `old-foo', it does not produce the proper results. The
6039 only way to avoid this problem is to make sure the file is loaded
6040 before moving aside the old definition of `foo'.
6042 But it is unmodular and unclean, in any case, for a Lisp file to
6043 redefine a function defined elsewhere.
6046 File: lispref.info, Node: Inline Functions, Next: Related Topics, Prev: Function Cells, Up: Functions
6051 You can define an "inline function" by using `defsubst' instead of
6052 `defun'. An inline function works just like an ordinary function
6053 except for one thing: when you compile a call to the function, the
6054 function's definition is open-coded into the caller.
6056 Making a function inline makes explicit calls run faster. But it
6057 also has disadvantages. For one thing, it reduces flexibility; if you
6058 change the definition of the function, calls already inlined still use
6059 the old definition until you recompile them. Since the flexibility of
6060 redefining functions is an important feature of XEmacs, you should not
6061 make a function inline unless its speed is really crucial.
6063 Another disadvantage is that making a large function inline can
6064 increase the size of compiled code both in files and in memory. Since
6065 the speed advantage of inline functions is greatest for small
6066 functions, you generally should not make large functions inline.
6068 It's possible to define a macro to expand into the same code that an
6069 inline function would execute. But the macro would have a limitation:
6070 you can use it only explicitly--a macro cannot be called with `apply',
6071 `mapcar' and so on. Also, it takes some work to convert an ordinary
6072 function into a macro. (*Note Macros::.) To convert it into an inline
6073 function is very easy; simply replace `defun' with `defsubst'. Since
6074 each argument of an inline function is evaluated exactly once, you
6075 needn't worry about how many times the body uses the arguments, as you
6076 do for macros. (*Note Argument Evaluation::.)
6078 Inline functions can be used and open-coded later on in the same
6079 file, following the definition, just like macros.
6082 File: lispref.info, Node: Related Topics, Prev: Inline Functions, Up: Functions
6084 Other Topics Related to Functions
6085 =================================
6087 Here is a table of several functions that do things related to function
6088 calling and function definitions. They are documented elsewhere, but
6089 we provide cross references here.
6092 See *Note Calling Functions::.
6095 See *Note Autoload::.
6097 `call-interactively'
6098 See *Note Interactive Call::.
6101 See *Note Interactive Call::.
6104 See *Note Accessing Documentation::.
6110 See *Note Calling Functions::.
6113 See *Note Calling Functions::.
6116 See *Note Function Indirection::.
6119 See *Note Using Interactive::.
6122 See *Note Interactive Call::.
6125 See *Note Creating Symbols::.
6128 See *Note Mapping Functions::.
6131 See *Note Mapping Functions::.
6134 See *Note Key Lookup::.
6137 File: lispref.info, Node: Macros, Next: Loading, Prev: Functions, Up: Top
6142 "Macros" enable you to define new control constructs and other language
6143 features. A macro is defined much like a function, but instead of
6144 telling how to compute a value, it tells how to compute another Lisp
6145 expression which will in turn compute the value. We call this
6146 expression the "expansion" of the macro.
6148 Macros can do this because they operate on the unevaluated
6149 expressions for the arguments, not on the argument values as functions
6150 do. They can therefore construct an expansion containing these
6151 argument expressions or parts of them.
6153 If you are using a macro to do something an ordinary function could
6154 do, just for the sake of speed, consider using an inline function
6155 instead. *Note Inline Functions::.
6159 * Simple Macro:: A basic example.
6160 * Expansion:: How, when and why macros are expanded.
6161 * Compiling Macros:: How macros are expanded by the compiler.
6162 * Defining Macros:: How to write a macro definition.
6163 * Backquote:: Easier construction of list structure.
6164 * Problems with Macros:: Don't evaluate the macro arguments too many times.
6165 Don't hide the user's variables.
6168 File: lispref.info, Node: Simple Macro, Next: Expansion, Up: Macros
6170 A Simple Example of a Macro
6171 ===========================
6173 Suppose we would like to define a Lisp construct to increment a
6174 variable value, much like the `++' operator in C. We would like to
6175 write `(inc x)' and have the effect of `(setq x (1+ x))'. Here's a
6176 macro definition that does the job:
6179 (list 'setq var (list '1+ var)))
6181 When this is called with `(inc x)', the argument `var' has the value
6182 `x'--_not_ the _value_ of `x'. The body of the macro uses this to
6183 construct the expansion, which is `(setq x (1+ x))'. Once the macro
6184 definition returns this expansion, Lisp proceeds to evaluate it, thus
6188 File: lispref.info, Node: Expansion, Next: Compiling Macros, Prev: Simple Macro, Up: Macros
6190 Expansion of a Macro Call
6191 =========================
6193 A macro call looks just like a function call in that it is a list which
6194 starts with the name of the macro. The rest of the elements of the list
6195 are the arguments of the macro.
6197 Evaluation of the macro call begins like evaluation of a function
6198 call except for one crucial difference: the macro arguments are the
6199 actual expressions appearing in the macro call. They are not evaluated
6200 before they are given to the macro definition. By contrast, the
6201 arguments of a function are results of evaluating the elements of the
6204 Having obtained the arguments, Lisp invokes the macro definition just
6205 as a function is invoked. The argument variables of the macro are bound
6206 to the argument values from the macro call, or to a list of them in the
6207 case of a `&rest' argument. And the macro body executes and returns
6208 its value just as a function body does.
6210 The second crucial difference between macros and functions is that
6211 the value returned by the macro body is not the value of the macro call.
6212 Instead, it is an alternate expression for computing that value, also
6213 known as the "expansion" of the macro. The Lisp interpreter proceeds
6214 to evaluate the expansion as soon as it comes back from the macro.
6216 Since the expansion is evaluated in the normal manner, it may contain
6217 calls to other macros. It may even be a call to the same macro, though
6220 You can see the expansion of a given macro call by calling
6223 - Function: macroexpand form &optional environment
6224 This function expands FORM, if it is a macro call. If the result
6225 is another macro call, it is expanded in turn, until something
6226 which is not a macro call results. That is the value returned by
6227 `macroexpand'. If FORM is not a macro call to begin with, it is
6230 Note that `macroexpand' does not look at the subexpressions of
6231 FORM (although some macro definitions may do so). Even if they
6232 are macro calls themselves, `macroexpand' does not expand them.
6234 The function `macroexpand' does not expand calls to inline
6235 functions. Normally there is no need for that, since a call to an
6236 inline function is no harder to understand than a call to an
6239 If ENVIRONMENT is provided, it specifies an alist of macro
6240 definitions that shadow the currently defined macros. Byte
6241 compilation uses this feature.
6244 (list 'setq var (list '1+ var)))
6247 (macroexpand '(inc r))
6250 (defmacro inc2 (var1 var2)
6251 (list 'progn (list 'inc var1) (list 'inc var2)))
6254 (macroexpand '(inc2 r s))
6255 => (progn (inc r) (inc s)) ; `inc' not expanded here.
6258 File: lispref.info, Node: Compiling Macros, Next: Defining Macros, Prev: Expansion, Up: Macros
6260 Macros and Byte Compilation
6261 ===========================
6263 You might ask why we take the trouble to compute an expansion for a
6264 macro and then evaluate the expansion. Why not have the macro body
6265 produce the desired results directly? The reason has to do with
6268 When a macro call appears in a Lisp program being compiled, the Lisp
6269 compiler calls the macro definition just as the interpreter would, and
6270 receives an expansion. But instead of evaluating this expansion, it
6271 compiles the expansion as if it had appeared directly in the program.
6272 As a result, the compiled code produces the value and side effects
6273 intended for the macro, but executes at full compiled speed. This would
6274 not work if the macro body computed the value and side effects
6275 itself--they would be computed at compile time, which is not useful.
6277 In order for compilation of macro calls to work, the macros must be
6278 defined in Lisp when the calls to them are compiled. The compiler has a
6279 special feature to help you do this: if a file being compiled contains a
6280 `defmacro' form, the macro is defined temporarily for the rest of the
6281 compilation of that file. To use this feature, you must define the
6282 macro in the same file where it is used and before its first use.
6284 Byte-compiling a file executes any `require' calls at top-level in
6285 the file. This is in case the file needs the required packages for
6286 proper compilation. One way to ensure that necessary macro definitions
6287 are available during compilation is to require the files that define
6288 them (*note Named Features::). To avoid loading the macro definition
6289 files when someone _runs_ the compiled program, write
6290 `eval-when-compile' around the `require' calls (*note Eval During
6294 File: lispref.info, Node: Defining Macros, Next: Backquote, Prev: Compiling Macros, Up: Macros
6299 A Lisp macro is a list whose CAR is `macro'. Its CDR should be a
6300 function; expansion of the macro works by applying the function (with
6301 `apply') to the list of unevaluated argument-expressions from the macro
6304 It is possible to use an anonymous Lisp macro just like an anonymous
6305 function, but this is never done, because it does not make sense to pass
6306 an anonymous macro to functionals such as `mapcar'. In practice, all
6307 Lisp macros have names, and they are usually defined with the special
6310 - Special Form: defmacro name argument-list body-forms...
6311 `defmacro' defines the symbol NAME as a macro that looks like this:
6313 (macro lambda ARGUMENT-LIST . BODY-FORMS)
6315 This macro object is stored in the function cell of NAME. The
6316 value returned by evaluating the `defmacro' form is NAME, but
6317 usually we ignore this value.
6319 The shape and meaning of ARGUMENT-LIST is the same as in a
6320 function, and the keywords `&rest' and `&optional' may be used
6321 (*note Argument List::). Macros may have a documentation string,
6322 but any `interactive' declaration is ignored since macros cannot be
6323 called interactively.
6326 File: lispref.info, Node: Backquote, Next: Problems with Macros, Prev: Defining Macros, Up: Macros
6331 Macros often need to construct large list structures from a mixture of
6332 constants and nonconstant parts. To make this easier, use the macro
6333 ``' (often called "backquote").
6335 Backquote allows you to quote a list, but selectively evaluate
6336 elements of that list. In the simplest case, it is identical to the
6337 special form `quote' (*note Quoting::). For example, these two forms
6338 yield identical results:
6340 `(a list of (+ 2 3) elements)
6341 => (a list of (+ 2 3) elements)
6342 '(a list of (+ 2 3) elements)
6343 => (a list of (+ 2 3) elements)
6345 The special marker `,' inside of the argument to backquote indicates
6346 a value that isn't constant. Backquote evaluates the argument of `,'
6347 and puts the value in the list structure:
6349 (list 'a 'list 'of (+ 2 3) 'elements)
6350 => (a list of 5 elements)
6351 `(a list of ,(+ 2 3) elements)
6352 => (a list of 5 elements)
6354 You can also "splice" an evaluated value into the resulting list,
6355 using the special marker `,@'. The elements of the spliced list become
6356 elements at the same level as the other elements of the resulting list.
6357 The equivalent code without using ``' is often unreadable. Here are
6360 (setq some-list '(2 3))
6362 (cons 1 (append some-list '(4) some-list))
6364 `(1 ,@some-list 4 ,@some-list)
6367 (setq list '(hack foo bar))
6371 (cons 'words (append (cdr list) '(as elements)))))
6372 => (use the words foo bar as elements)
6373 `(use the words ,@(cdr list) as elements)
6374 => (use the words foo bar as elements)
6376 In older versions of Emacs (before XEmacs 19.12 or FSF Emacs
6377 version 19.29), ``' used a different syntax which required an
6378 extra level of parentheses around the entire backquote construct.
6379 Likewise, each `,' or `,@' substitution required an extra level of
6380 parentheses surrounding both the `,' or `,@' and the following
6381 expression. The old syntax required whitespace between the ``',
6382 `,' or `,@' and the following expression.
6384 This syntax is still accepted, but no longer recommended except for
6385 compatibility with old Emacs versions.
6388 File: lispref.info, Node: Problems with Macros, Prev: Backquote, Up: Macros
6390 Common Problems Using Macros
6391 ============================
6393 The basic facts of macro expansion have counterintuitive consequences.
6394 This section describes some important consequences that can lead to
6395 trouble, and rules to follow to avoid trouble.
6399 * Argument Evaluation:: The expansion should evaluate each macro arg once.
6400 * Surprising Local Vars:: Local variable bindings in the expansion
6401 require special care.
6402 * Eval During Expansion:: Don't evaluate them; put them in the expansion.
6403 * Repeated Expansion:: Avoid depending on how many times expansion is done.
6406 File: lispref.info, Node: Argument Evaluation, Next: Surprising Local Vars, Up: Problems with Macros
6408 Evaluating Macro Arguments Repeatedly
6409 -------------------------------------
6411 When defining a macro you must pay attention to the number of times the
6412 arguments will be evaluated when the expansion is executed. The
6413 following macro (used to facilitate iteration) illustrates the problem.
6414 This macro allows us to write a simple "for" loop such as one might
6417 (defmacro for (var from init to final do &rest body)
6418 "Execute a simple \"for\" loop.
6419 For example, (for i from 1 to 10 do (print i))."
6420 (list 'let (list (list var init))
6421 (cons 'while (cons (list '<= var final)
6422 (append body (list (list 'inc var)))))))
6425 (for i from 1 to 3 do
6426 (setq square (* i i))
6427 (princ (format "\n%d %d" i square)))
6431 (setq square (* i i))
6432 (princ (format "%d %d" i square))
6440 (The arguments `from', `to', and `do' in this macro are "syntactic
6441 sugar"; they are entirely ignored. The idea is that you will write
6442 noise words (such as `from', `to', and `do') in those positions in the
6445 Here's an equivalent definition simplified through use of backquote:
6447 (defmacro for (var from init to final do &rest body)
6448 "Execute a simple \"for\" loop.
6449 For example, (for i from 1 to 10 do (print i))."
6450 `(let ((,var ,init))
6451 (while (<= ,var ,final)
6455 Both forms of this definition (with backquote and without) suffer
6456 from the defect that FINAL is evaluated on every iteration. If FINAL
6457 is a constant, this is not a problem. If it is a more complex form,
6458 say `(long-complex-calculation x)', this can slow down the execution
6459 significantly. If FINAL has side effects, executing it more than once
6460 is probably incorrect.
6462 A well-designed macro definition takes steps to avoid this problem by
6463 producing an expansion that evaluates the argument expressions exactly
6464 once unless repeated evaluation is part of the intended purpose of the
6465 macro. Here is a correct expansion for the `for' macro:
6470 (setq square (* i i))
6471 (princ (format "%d %d" i square))
6474 Here is a macro definition that creates this expansion:
6476 (defmacro for (var from init to final do &rest body)
6477 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
6480 (while (<= ,var max)
6484 Unfortunately, this introduces another problem. Proceed to the
6488 File: lispref.info, Node: Surprising Local Vars, Next: Eval During Expansion, Prev: Argument Evaluation, Up: Problems with Macros
6490 Local Variables in Macro Expansions
6491 -----------------------------------
6493 In the previous section, the definition of `for' was fixed as follows
6494 to make the expansion evaluate the macro arguments the proper number of
6497 (defmacro for (var from init to final do &rest body)
6498 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
6501 (while (<= ,var max)
6505 The new definition of `for' has a new problem: it introduces a local
6506 variable named `max' which the user does not expect. This causes
6507 trouble in examples such as the following:
6510 (for x from 0 to 10 do
6511 (let ((this (frob x)))
6515 The references to `max' inside the body of the `for', which are
6516 supposed to refer to the user's binding of `max', really access the
6517 binding made by `for'.
6519 The way to correct this is to use an uninterned symbol instead of
6520 `max' (*note Creating Symbols::). The uninterned symbol can be bound
6521 and referred to just like any other symbol, but since it is created by
6522 `for', we know that it cannot already appear in the user's program.
6523 Since it is not interned, there is no way the user can put it into the
6524 program later. It will never appear anywhere except where put by
6525 `for'. Here is a definition of `for' that works this way:
6527 (defmacro for (var from init to final do &rest body)
6528 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
6529 (let ((tempvar (make-symbol "max")))
6532 (while (<= ,var ,tempvar)
6536 This creates an uninterned symbol named `max' and puts it in the
6537 expansion instead of the usual interned symbol `max' that appears in
6538 expressions ordinarily.
6541 File: lispref.info, Node: Eval During Expansion, Next: Repeated Expansion, Prev: Surprising Local Vars, Up: Problems with Macros
6543 Evaluating Macro Arguments in Expansion
6544 ---------------------------------------
6546 Another problem can happen if you evaluate any of the macro argument
6547 expressions during the computation of the expansion, such as by calling
6548 `eval' (*note Eval::). If the argument is supposed to refer to the
6549 user's variables, you may have trouble if the user happens to use a
6550 variable with the same name as one of the macro arguments. Inside the
6551 macro body, the macro argument binding is the most local binding of this
6552 variable, so any references inside the form being evaluated do refer to
6553 it. Here is an example:
6556 (list 'setq (eval a) t))
6559 (foo x) ==> (setq b t)
6560 => t ; and `b' has been set.
6563 (foo a) ==> (setq a t)
6564 => t ; but this set `a', not `c'.
6566 It makes a difference whether the user's variable is named `a' or
6567 `x', because `a' conflicts with the macro argument variable `a'.
6569 Another reason not to call `eval' in a macro definition is that it
6570 probably won't do what you intend in a compiled program. The
6571 byte-compiler runs macro definitions while compiling the program, when
6572 the program's own computations (which you might have wished to access
6573 with `eval') don't occur and its local variable bindings don't exist.
6575 The safe way to work with the run-time value of an expression is to
6576 put the expression into the macro expansion, so that its value is
6577 computed as part of executing the expansion.
6580 File: lispref.info, Node: Repeated Expansion, Prev: Eval During Expansion, Up: Problems with Macros
6582 How Many Times is the Macro Expanded?
6583 -------------------------------------
6585 Occasionally problems result from the fact that a macro call is
6586 expanded each time it is evaluated in an interpreted function, but is
6587 expanded only once (during compilation) for a compiled function. If the
6588 macro definition has side effects, they will work differently depending
6589 on how many times the macro is expanded.
6591 In particular, constructing objects is a kind of side effect. If the
6592 macro is called once, then the objects are constructed only once. In
6593 other words, the same structure of objects is used each time the macro
6594 call is executed. In interpreted operation, the macro is reexpanded
6595 each time, producing a fresh collection of objects each time. Usually
6596 this does not matter--the objects have the same contents whether they
6597 are shared or not. But if the surrounding program does side effects on
6598 the objects, it makes a difference whether they are shared. Here is an
6601 (defmacro empty-object ()
6602 (list 'quote (cons nil nil)))
6604 (defun initialize (condition)
6605 (let ((object (empty-object)))
6607 (setcar object condition))
6610 If `initialize' is interpreted, a new list `(nil)' is constructed each
6611 time `initialize' is called. Thus, no side effect survives between
6612 calls. If `initialize' is compiled, then the macro `empty-object' is
6613 expanded during compilation, producing a single "constant" `(nil)' that
6614 is reused and altered each time `initialize' is called.
6616 One way to avoid pathological cases like this is to think of
6617 `empty-object' as a funny kind of constant, not as a memory allocation
6618 construct. You wouldn't use `setcar' on a constant such as `'(nil)',
6619 so naturally you won't use it on `(empty-object)' either.
6622 File: lispref.info, Node: Customization, Up: Top
6624 Writing Customization Definitions
6625 *********************************
6627 This chapter describes how to declare user options for customization,
6628 and also customization groups for classifying them. We use the term
6629 "customization item" to include both kinds of customization
6630 definitions--as well as face definitions.
6635 * Group Definitions::
6636 * Variable Definitions::
6637 * Customization Types::
6640 File: lispref.info, Node: Common Keywords, Next: Group Definitions, Up: Customization
6642 Common Keywords for All Kinds of Items
6643 ======================================
6645 All kinds of customization declarations (for variables and groups, and
6646 for faces) accept keyword arguments for specifying various information.
6647 This section describes some keywords that apply to all kinds.
6649 All of these keywords, except `:tag', can be used more than once in
6650 a given item. Each use of the keyword has an independent effect. The
6651 keyword `:tag' is an exception because any given item can only display
6655 Use NAME, a string, instead of the item's name, to label the item
6656 in customization menus and buffers.
6659 Put this customization item in group GROUP. When you use `:group'
6660 in a `defgroup', it makes the new group a subgroup of GROUP.
6662 If you use this keyword more than once, you can put a single item
6663 into more than one group. Displaying any of those groups will
6664 show this item. Be careful not to overdo this!
6667 Include an external link after the documentation string for this
6668 item. This is a sentence containing an active field which
6669 references some other documentation.
6671 There are three alternatives you can use for LINK-DATA:
6673 `(custom-manual INFO-NODE)'
6674 Link to an Info node; INFO-NODE is a string which specifies
6675 the node name, as in `"(emacs)Top"'. The link appears as
6676 `[manual]' in the customization buffer.
6678 `(info-link INFO-NODE)'
6679 Like `custom-manual' except that the link appears in the
6680 customization buffer with the Info node name.
6683 Link to a web page; URL is a string which specifies the URL.
6684 The link appears in the customization buffer as URL.
6686 You can specify the text to use in the customization buffer by
6687 adding `:tag NAME' after the first element of the LINK-DATA; for
6688 example, `(info-link :tag "foo" "(emacs)Top")' makes a link to the
6689 Emacs manual which appears in the buffer as `foo'.
6691 An item can have more than one external link; however, most items
6695 Load file FILE (a string) before displaying this customization
6696 item. Loading is done with `load-library', and only if the file is
6700 Require feature FEATURE (a symbol) when installing a value for
6701 this item (an option or a face) that was saved using the
6702 customization feature. This is done by calling `require'.
6704 The most common reason to use `:require' is when a variable enables
6705 a feature such as a minor mode, and just setting the variable
6706 won't have any effect unless the code which implements the mode is
6710 File: lispref.info, Node: Group Definitions, Next: Variable Definitions, Prev: Common Keywords, Up: Customization
6712 Defining Custom Groups
6713 ======================
6715 Each Emacs Lisp package should have one main customization group which
6716 contains all the options, faces and other groups in the package. If the
6717 package has a small number of options and faces, use just one group and
6718 put everything in it. When there are more than twelve or so options and
6719 faces, then you should structure them into subgroups, and put the
6720 subgroups under the package's main customization group. It is OK to
6721 put some of the options and faces in the package's main group alongside
6724 The package's main or only group should be a member of one or more of
6725 the standard customization groups. (To display the full list of them,
6726 use `M-x customize'.) Choose one or more of them (but not too many),
6727 and add your group to each of them using the `:group' keyword.
6729 The way to declare new customization groups is with `defgroup'.
6731 - Macro: defgroup group members doc [keyword value]...
6732 Declare GROUP as a customization group containing MEMBERS. Do not
6733 quote the symbol GROUP. The argument DOC specifies the
6734 documentation string for the group.
6736 The argument MEMBERS is a list specifying an initial set of
6737 customization items to be members of the group. However, most
6738 often MEMBERS is `nil', and you specify the group's members by
6739 using the `:group' keyword when defining those members.
6741 If you want to specify group members through MEMBERS, each element
6742 should have the form `(NAME WIDGET)'. Here NAME is a symbol, and
6743 WIDGET is a widget type for editing that symbol. Useful widgets
6744 are `custom-variable' for a variable, `custom-face' for a face,
6745 and `custom-group' for a group.
6747 In addition to the common keywords (*note Common Keywords::), you
6748 can use this keyword in `defgroup':
6751 If the name of an item in the group starts with PREFIX, then
6752 the tag for that item is constructed (by default) by omitting
6755 One group can have any number of prefixes.
6758 File: lispref.info, Node: Variable Definitions, Next: Customization Types, Prev: Group Definitions, Up: Customization
6760 Defining Customization Variables
6761 ================================
6763 Use `defcustom' to declare user-editable variables.
6765 - Macro: defcustom option default doc [keyword value]...
6766 Declare OPTION as a customizable user option variable. Do not
6767 quote OPTION. The argument DOC specifies the documentation string
6770 If OPTION is void, `defcustom' initializes it to DEFAULT. DEFAULT
6771 should be an expression to compute the value; be careful in
6772 writing it, because it can be evaluated on more than one occasion.
6774 The following additional keywords are defined:
6777 Use TYPE as the data type for this option. It specifies which
6778 values are legitimate, and how to display the value. *Note
6779 Customization Types::, for more information.
6782 Specify LIST as the list of reasonable values for use in this
6785 Currently this is meaningful only when the type is `hook'.
6786 In that case, the elements of LIST should be functions that
6787 are useful as elements of the hook value. The user is not
6788 restricted to using only these functions, but they are
6789 offered as convenient alternatives.
6792 This option specifies that the variable was first introduced,
6793 or its default value was changed, in Emacs version VERSION.
6794 The value VERSION must be a string. For example,
6796 (defcustom foo-max 34
6797 "*Maximum number of foo's allowed."
6803 Specify SETFUNCTION as the way to change the value of this
6804 option. The function SETFUNCTION should take two arguments,
6805 a symbol and the new value, and should do whatever is
6806 necessary to update the value properly for this option (which
6807 may not mean simply setting the option as a Lisp variable).
6808 The default for SETFUNCTION is `set-default'.
6811 Specify GETFUNCTION as the way to extract the value of this
6812 option. The function GETFUNCTION should take one argument, a
6813 symbol, and should return the "current value" for that symbol
6814 (which need not be the symbol's Lisp value). The default is
6817 `:initialize FUNCTION'
6818 FUNCTION should be a function used to initialize the variable
6819 when the `defcustom' is evaluated. It should take two
6820 arguments, the symbol and value. Here are some predefined
6821 functions meant for use in this way:
6823 `custom-initialize-set'
6824 Use the variable's `:set' function to initialize the
6825 variable, but do not reinitialize it if it is already
6826 non-void. This is the default `:initialize' function.
6828 `custom-initialize-default'
6829 Like `custom-initialize-set', but use the function
6830 `set-default' to set the variable, instead of the
6831 variable's `:set' function. This is the usual choice
6832 for a variable whose `:set' function enables or disables
6833 a minor mode; with this choice, defining the variable
6834 will not call the minor mode function, but customizing
6835 the variable will do so.
6837 `custom-initialize-reset'
6838 Always use the `:set' function to initialize the
6839 variable. If the variable is already non-void, reset it
6840 by calling the `:set' function using the current value
6841 (returned by the `:get' method).
6843 `custom-initialize-changed'
6844 Use the `:set' function to initialize the variable, if
6845 it is already set or has been customized; otherwise,
6846 just use `set-default'.
6848 The `:require' option is useful for an option that turns on the
6849 operation of a certain feature. Assuming that the package is coded to
6850 check the value of the option, you still need to arrange for the package
6851 to be loaded. You can do that with `:require'. *Note Common
6852 Keywords::. Here is an example, from the library `paren.el':
6854 (defcustom show-paren-mode nil
6855 "Toggle Show Paren mode...."
6856 :set (lambda (symbol value)
6857 (show-paren-mode (or value 0)))
6858 :initialize 'custom-initialize-default
6860 :group 'paren-showing
6863 Internally, `defcustom' uses the symbol property `standard-value' to
6864 record the expression for the default value, and `saved-value' to
6865 record the value saved by the user with the customization buffer. The
6866 `saved-value' property is actually a list whose car is an expression
6867 which evaluates to the value.
6870 File: lispref.info, Node: Customization Types, Prev: Variable Definitions, Up: Customization
6875 When you define a user option with `defcustom', you must specify its
6876 "customization type". That is a Lisp object which describes (1) which
6877 values are legitimate and (2) how to display the value in the
6878 customization buffer for editing.
6880 You specify the customization type in `defcustom' with the `:type'
6881 keyword. The argument of `:type' is evaluated; since types that vary
6882 at run time are rarely useful, normally you use a quoted constant. For
6885 (defcustom diff-command "diff"
6886 "*The command to use to run diff."
6890 In general, a customization type is a list whose first element is a
6891 symbol, one of the customization type names defined in the following
6892 sections. After this symbol come a number of arguments, depending on
6893 the symbol. Between the type symbol and its arguments, you can
6894 optionally write keyword-value pairs (*note Type Keywords::).
6896 Some of the type symbols do not use any arguments; those are called
6897 "simple types". For a simple type, if you do not use any keyword-value
6898 pairs, you can omit the parentheses around the type symbol. For
6899 example just `string' as a customization type is equivalent to
6906 * Splicing into Lists::
6910 File: lispref.info, Node: Simple Types, Next: Composite Types, Up: Customization Types
6915 This section describes all the simple customization types.
6918 The value may be any Lisp object that can be printed and read
6919 back. You can use `sexp' as a fall-back for any option, if you
6920 don't want to take the time to work out a more specific type to
6924 The value must be an integer, and is represented textually in the
6925 customization buffer.
6928 The value must be a number, and is represented textually in the
6929 customization buffer.
6932 The value must be a string, and the customization buffer shows
6933 just the contents, with no delimiting `"' characters and no
6937 Like `string' except that the string must be a valid regular
6941 The value must be a character code. A character code is actually
6942 an integer, but this type shows the value by inserting the
6943 character in the buffer, rather than by showing the number.
6946 The value must be a file name, and you can do completion with
6949 `(file :must-match t)'
6950 The value must be a file name for an existing file, and you can do
6951 completion with `M-<TAB>'.
6954 The value must be a directory name, and you can do completion with
6958 The value must be a symbol. It appears in the customization
6959 buffer as the name of the symbol.
6962 The value must be either a lambda expression or a function name.
6963 When it is a function name, you can do completion with `M-<TAB>'.
6966 The value must be a variable name, and you can do completion with
6970 The value must be a symbol which is a face name.
6973 The value is boolean--either `nil' or `t'. Note that by using
6974 `choice' and `const' together (see the next section), you can
6975 specify that the value must be `nil' or `t', but also specify the
6976 text to describe each value in a way that fits the specific
6977 meaning of the alternative.
6980 File: lispref.info, Node: Composite Types, Next: Splicing into Lists, Prev: Simple Types, Up: Customization Types
6985 When none of the simple types is appropriate, you can use composite
6986 types, which build new types from other types. Here are several ways of
6989 `(restricted-sexp :match-alternatives CRITERIA)'
6990 The value may be any Lisp object that satisfies one of CRITERIA.
6991 CRITERIA should be a list, and each elements should be one of
6992 these possibilities:
6994 * A predicate--that is, a function of one argument that returns
6995 non-`nil' if the argument fits a certain type. This means
6996 that objects of that type are acceptable.
6998 * A quoted constant--that is, `'OBJECT'. This means that
6999 OBJECT itself is an acceptable value.
7003 (restricted-sexp :match-alternatives (integerp 't 'nil))
7005 allows integers, `t' and `nil' as legitimate values.
7007 The customization buffer shows all legitimate values using their
7008 read syntax, and the user edits them textually.
7010 `(cons CAR-TYPE CDR-TYPE)'
7011 The value must be a cons cell, its CAR must fit CAR-TYPE, and its
7012 CDR must fit CDR-TYPE. For example, `(cons string symbol)' is a
7013 customization type which matches values such as `("foo" . foo)'.
7015 In the customization buffer, the CAR and the CDR are displayed and
7016 edited separately, each according to the type that you specify for
7019 `(list ELEMENT-TYPES...)'
7020 The value must be a list with exactly as many elements as the
7021 ELEMENT-TYPES you have specified; and each element must fit the
7022 corresponding ELEMENT-TYPE.
7024 For example, `(list integer string function)' describes a list of
7025 three elements; the first element must be an integer, the second a
7026 string, and the third a function.
7028 In the customization buffer, the each element is displayed and
7029 edited separately, according to the type specified for it.
7031 `(vector ELEMENT-TYPES...)'
7032 Like `list' except that the value must be a vector instead of a
7033 list. The elements work the same as in `list'.
7035 `(choice ALTERNATIVE-TYPES...)'
7036 The value must fit at least one of ALTERNATIVE-TYPES. For
7037 example, `(choice integer string)' allows either an integer or a
7040 In the customization buffer, the user selects one of the
7041 alternatives using a menu, and can then edit the value in the
7042 usual way for that alternative.
7044 Normally the strings in this menu are determined automatically
7045 from the choices; however, you can specify different strings for
7046 the menu by including the `:tag' keyword in the alternatives. For
7047 example, if an integer stands for a number of spaces, while a
7048 string is text to use verbatim, you might write the customization
7051 (choice (integer :tag "Number of spaces")
7052 (string :tag "Literal text"))
7054 so that the menu offers `Number of spaces' and `Literal Text'.
7056 In any alternative for which `nil' is not a valid value, other than
7057 a `const', you should specify a valid default for that alternative
7058 using the `:value' keyword. *Note Type Keywords::.
7061 The value must be VALUE--nothing else is allowed.
7063 The main use of `const' is inside of `choice'. For example,
7064 `(choice integer (const nil))' allows either an integer or `nil'.
7066 `:tag' is often used with `const', inside of `choice'. For
7069 (choice (const :tag "Yes" t)
7070 (const :tag "No" nil)
7071 (const :tag "Ask" foo))
7073 `(function-item FUNCTION)'
7074 Like `const', but used for values which are functions. This
7075 displays the documentation string as well as the function name.
7076 The documentation string is either the one you specify with
7077 `:doc', or FUNCTION's own documentation string.
7079 `(variable-item VARIABLE)'
7080 Like `const', but used for values which are variable names. This
7081 displays the documentation string as well as the variable name.
7082 The documentation string is either the one you specify with
7083 `:doc', or VARIABLE's own documentation string.
7086 The value must be a list and each element of the list must be one
7087 of the ELEMENTS specified. This appears in the customization
7088 buffer as a checklist.
7090 `(repeat ELEMENT-TYPE)'
7091 The value must be a list and each element of the list must fit the
7092 type ELEMENT-TYPE. This appears in the customization buffer as a
7093 list of elements, with `[INS]' and `[DEL]' buttons for adding more
7094 elements or removing elements.
7097 File: lispref.info, Node: Splicing into Lists, Next: Type Keywords, Prev: Composite Types, Up: Customization Types
7102 The `:inline' feature lets you splice a variable number of elements
7103 into the middle of a list or vector. You use it in a `set', `choice'
7104 or `repeat' type which appears among the element-types of a `list' or
7107 Normally, each of the element-types in a `list' or `vector'
7108 describes one and only one element of the list or vector. Thus, if an
7109 element-type is a `repeat', that specifies a list of unspecified length
7110 which appears as one element.
7112 But when the element-type uses `:inline', the value it matches is
7113 merged directly into the containing sequence. For example, if it
7114 matches a list with three elements, those become three elements of the
7115 overall sequence. This is analogous to using `,@' in the backquote
7118 For example, to specify a list whose first element must be `t' and
7119 whose remaining arguments should be zero or more of `foo' and `bar',
7120 use this customization type:
7122 (list (const t) (set :inline t foo bar))
7124 This matches values such as `(t)', `(t foo)', `(t bar)' and `(t foo
7127 When the element-type is a `choice', you use `:inline' not in the
7128 `choice' itself, but in (some of) the alternatives of the `choice'.
7129 For example, to match a list which must start with a file name,
7130 followed either by the symbol `t' or two strings, use this
7135 (list :inline t string string)))
7137 If the user chooses the first alternative in the choice, then the
7138 overall list has two elements and the second element is `t'. If the
7139 user chooses the second alternative, then the overall list has three
7140 elements and the second and third must be strings.
7143 File: lispref.info, Node: Type Keywords, Prev: Splicing into Lists, Up: Customization Types
7148 You can specify keyword-argument pairs in a customization type after the
7149 type name symbol. Here are the keywords you can use, and their
7153 This is used for a type that appears as an alternative inside of
7154 `choice'; it specifies the default value to use, at first, if and
7155 when the user selects this alternative with the menu in the
7156 customization buffer.
7158 Of course, if the actual value of the option fits this
7159 alternative, it will appear showing the actual value, not DEFAULT.
7161 If `nil' is not a valid value for the alternative, then it is
7162 essential to specify a valid default with `:value'.
7164 `:format FORMAT-STRING'
7165 This string will be inserted in the buffer to represent the value
7166 corresponding to the type. The following `%' escapes are available
7167 for use in FORMAT-STRING:
7170 Display the text BUTTON marked as a button. The `:action'
7171 attribute specifies what the button will do if the user
7172 invokes it; its value is a function which takes two
7173 arguments--the widget which the button appears in, and the
7176 There is no way to specify two different buttons with
7180 Show SAMPLE in a special face specified by `:sample-face'.
7183 Substitute the item's value. How the value is represented
7184 depends on the kind of item, and (for variables) on the
7188 Substitute the item's documentation string.
7191 Like `%d', but if the documentation string is more than one
7192 line, add an active field to control whether to show all of
7193 it or just the first line.
7196 Substitute the tag here. You specify the tag with the `:tag'
7200 Display a literal `%'.
7203 Perform ACTION if the user clicks on a button.
7206 Use the face FACE (a face name or a list of face names) for button
7207 text displayed with `%[...%]'.
7209 `:button-prefix PREFIX'
7210 `:button-suffix SUFFIX'
7211 These specify the text to display before and after a button. Each
7215 No text is inserted.
7218 The string is inserted literally.
7221 The symbol's value is used.
7224 Use TAG (a string) as the tag for the value (or part of the value)
7225 that corresponds to this type.
7228 Use DOC as the documentation string for this value (or part of the
7229 value) that corresponds to this type. In order for this to work,
7230 you must specify a value for `:format', and use `%d' or `%h' in
7233 The usual reason to specify a documentation string for a type is to
7234 provide more information about the meanings of alternatives inside
7235 a `:choice' type or the parts of some other composite type.
7237 `:help-echo MOTION-DOC'
7238 When you move to this item with `widget-forward' or
7239 `widget-backward', it will display the string MOTION-DOC in the
7243 Specify how to decide whether a value matches the type. The
7244 corresponding value, FUNCTION, should be a function that accepts
7245 two arguments, a widget and a value; it should return non-`nil' if
7246 the value is acceptable.
7250 File: lispref.info, Node: Loading, Next: Byte Compilation, Prev: Macros, Up: Top
7255 Loading a file of Lisp code means bringing its contents into the Lisp
7256 environment in the form of Lisp objects. XEmacs finds and opens the
7257 file, reads the text, evaluates each form, and then closes the file.
7259 The load functions evaluate all the expressions in a file just as
7260 the `eval-current-buffer' function evaluates all the expressions in a
7261 buffer. The difference is that the load functions read and evaluate
7262 the text in the file as found on disk, not the text in an Emacs buffer.
7264 The loaded file must contain Lisp expressions, either as source code
7265 or as byte-compiled code. Each form in the file is called a "top-level
7266 form". There is no special format for the forms in a loadable file;
7267 any form in a file may equally well be typed directly into a buffer and
7268 evaluated there. (Indeed, most code is tested this way.) Most often,
7269 the forms are function definitions and variable definitions.
7271 A file containing Lisp code is often called a "library". Thus, the
7272 "Rmail library" is a file containing code for Rmail mode. Similarly, a
7273 "Lisp library directory" is a directory of files containing Lisp code.
7277 * How Programs Do Loading:: The `load' function and others.
7278 * Autoload:: Setting up a function to autoload.
7279 * Repeated Loading:: Precautions about loading a file twice.
7280 * Named Features:: Loading a library if it isn't already loaded.
7281 * Unloading:: How to ``unload'' a library that was loaded.
7282 * Hooks for Loading:: Providing code to be run when
7283 particular libraries are loaded.
7286 File: lispref.info, Node: How Programs Do Loading, Next: Autoload, Up: Loading
7288 How Programs Do Loading
7289 =======================
7291 XEmacs Lisp has several interfaces for loading. For example,
7292 `autoload' creates a placeholder object for a function in a file;
7293 trying to call the autoloading function loads the file to get the
7294 function's real definition (*note Autoload::). `require' loads a file
7295 if it isn't already loaded (*note Named Features::). Ultimately, all
7296 these facilities call the `load' function to do the work.
7298 - Function: load filename &optional missing-ok nomessage nosuffix
7299 This function finds and opens a file of Lisp code, evaluates all
7300 the forms in it, and closes the file.
7302 To find the file, `load' first looks for a file named
7303 `FILENAME.elc', that is, for a file whose name is FILENAME with
7304 `.elc' appended. If such a file exists, it is loaded. If there
7305 is no file by that name, then `load' looks for a file named
7306 `FILENAME.el'. If that file exists, it is loaded. Finally, if
7307 neither of those names is found, `load' looks for a file named
7308 FILENAME with nothing appended, and loads it if it exists. (The
7309 `load' function is not clever about looking at FILENAME. In the
7310 perverse case of a file named `foo.el.el', evaluation of `(load
7311 "foo.el")' will indeed find it.)
7313 If the optional argument NOSUFFIX is non-`nil', then the suffixes
7314 `.elc' and `.el' are not tried. In this case, you must specify
7315 the precise file name you want.
7317 If FILENAME is a relative file name, such as `foo' or
7318 `baz/foo.bar', `load' searches for the file using the variable
7319 `load-path'. It appends FILENAME to each of the directories
7320 listed in `load-path', and loads the first file it finds whose name
7321 matches. The current default directory is tried only if it is
7322 specified in `load-path', where `nil' stands for the default
7323 directory. `load' tries all three possible suffixes in the first
7324 directory in `load-path', then all three suffixes in the second
7325 directory, and so on.
7327 If you get a warning that `foo.elc' is older than `foo.el', it
7328 means you should consider recompiling `foo.el'. *Note Byte
7331 Messages like `Loading foo...' and `Loading foo...done' appear in
7332 the echo area during loading unless NOMESSAGE is non-`nil'.
7334 Any unhandled errors while loading a file terminate loading. If
7335 the load was done for the sake of `autoload', any function
7336 definitions made during the loading are undone.
7338 If `load' can't find the file to load, then normally it signals the
7339 error `file-error' (with `Cannot open load file FILENAME'). But
7340 if MISSING-OK is non-`nil', then `load' just returns `nil'.
7342 You can use the variable `load-read-function' to specify a function
7343 for `load' to use instead of `read' for reading expressions. See
7346 `load' returns `t' if the file loads successfully.
7348 - User Option: load-path
7349 The value of this variable is a list of directories to search when
7350 loading files with `load'. Each element is a string (which must be
7351 a directory name) or `nil' (which stands for the current working
7352 directory). The value of `load-path' is initialized from the
7353 environment variable `EMACSLOADPATH', if that exists; otherwise its
7354 default value is specified in `emacs/src/paths.h' when XEmacs is
7357 The syntax of `EMACSLOADPATH' is the same as used for `PATH'; `:'
7358 (or `;', according to the operating system) separates directory
7359 names, and `.' is used for the current default directory. Here is
7360 an example of how to set your `EMACSLOADPATH' variable from a
7361 `csh' `.login' file:
7363 setenv EMACSLOADPATH .:/user/bil/emacs:/usr/lib/emacs/lisp
7365 Here is how to set it using `sh':
7367 export EMACSLOADPATH
7368 EMACSLOADPATH=.:/user/bil/emacs:/usr/local/lib/emacs/lisp
7370 Here is an example of code you can place in a `.emacs' file to add
7371 several directories to the front of your default `load-path':
7374 (append (list nil "/user/bil/emacs"
7375 "/usr/local/lisplib"
7379 In this example, the path searches the current working directory
7380 first, followed then by the `/user/bil/emacs' directory, the
7381 `/usr/local/lisplib' directory, and the `~/emacs' directory, which
7382 are then followed by the standard directories for Lisp code.
7384 The command line options `-l' or `-load' specify a Lisp library to
7385 load as part of Emacs startup. Since this file might be in the
7386 current directory, Emacs 18 temporarily adds the current directory
7387 to the front of `load-path' so the file can be found there. Newer
7388 Emacs versions also find such files in the current directory, but
7389 without altering `load-path'.
7391 Dumping Emacs uses a special value of `load-path'. If the value of
7392 `load-path' at the end of dumping is unchanged (that is, still the
7393 same special value), the dumped Emacs switches to the ordinary
7394 `load-path' value when it starts up, as described above. But if
7395 `load-path' has any other value at the end of dumping, that value
7396 is used for execution of the dumped Emacs also.
7398 Therefore, if you want to change `load-path' temporarily for
7399 loading a few libraries in `site-init.el' or `site-load.el', you
7400 should bind `load-path' locally with `let' around the calls to
7403 - Function: locate-file filename path-list &optional suffixes mode
7404 This function searches for a file in the same way that `load' does,
7405 and returns the file found (if any). (In fact, `load' uses this
7406 function to search through `load-path'.) It searches for FILENAME
7407 through PATH-LIST, expanded by one of the optional SUFFIXES
7408 (string of suffixes separated by `:'s), checking for access MODE
7409 (0|1|2|4 = exists|executable|writable|readable), default readable.
7411 `locate-file' keeps hash tables of the directories it searches
7412 through, in order to speed things up. It tries valiantly to not
7413 get confused in the face of a changing and unpredictable
7414 environment, but can occasionally get tripped up. In this case,
7415 you will have to call `locate-file-clear-hashing' to get it back
7416 on track. See that function for details.
7418 - Function: locate-file-clear-hashing path
7419 This function clears the hash records for the specified list of
7420 directories. `locate-file' uses a hashing scheme to speed lookup,
7421 and will correctly track the following environmental changes:
7423 * changes of any sort to the list of directories to be searched.
7425 * addition and deletion of non-shadowing files (see below) from
7426 the directories in the list.
7428 * byte-compilation of a .el file into a .elc file.
7430 `locate-file' will primarily get confused if you add a file that
7431 shadows (i.e. has the same name as) another file further down in
7432 the directory list. In this case, you must call
7433 `locate-file-clear-hashing'.
7435 - Variable: load-in-progress
7436 This variable is non-`nil' if Emacs is in the process of loading a
7437 file, and it is `nil' otherwise.
7439 - Variable: load-read-function
7440 This variable specifies an alternate expression-reading function
7441 for `load' and `eval-region' to use instead of `read'. The
7442 function should accept one argument, just as `read' does.
7444 Normally, the variable's value is `nil', which means those
7445 functions should use `read'.
7447 - User Option: load-warn-when-source-newer
7448 This variable specifies whether `load' should check whether the
7449 source is newer than the binary. If this variable is true, then
7450 when a `.elc' file is being loaded and the corresponding `.el' is
7451 newer, a warning message will be printed. The default is `nil',
7452 but it is bound to `t' during the initial loadup.
7454 - User Option: load-warn-when-source-only
7455 This variable specifies whether `load' should warn when loading a
7456 `.el' file instead of an `.elc'. If this variable is true, then
7457 when `load' is called with a filename without an extension, and
7458 the `.elc' version doesn't exist but the `.el' version does, then
7459 a message will be printed. If an explicit extension is passed to
7460 `load', no warning will be printed. The default is `nil', but it
7461 is bound to `t' during the initial loadup.
7463 - User Option: load-ignore-elc-files
7464 This variable specifies whether `load' should ignore `.elc' files
7465 when a suffix is not given. This is normally used only to
7466 bootstrap the `.elc' files when building XEmacs, when you use the
7467 command `make all-elc'. (This forces the `.el' versions to be
7468 loaded in the process of compiling those same files, so that
7469 existing out-of-date `.elc' files do not make it mess things up.)
7471 To learn how `load' is used to build XEmacs, see *Note Building