1 This is ../info/lispref.info, produced by makeinfo version 3.12s 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: Symbol Forms, Next: Classifying Lists, Prev: Self-Evaluating Forms, Up: Forms
58 When a symbol is evaluated, it is treated as a variable. The result
59 is the variable's value, if it has one. If it has none (if its value
60 cell is void), an error is signaled. For more information on the use of
61 variables, see *Note Variables::.
63 In the following example, we set the value of a symbol with `setq'.
64 Then we evaluate the symbol, and get back the value that `setq' stored.
73 The symbols `nil' and `t' are treated specially, so that the value
74 of `nil' is always `nil', and the value of `t' is always `t'; you
75 cannot set or bind them to any other values. Thus, these two symbols
76 act like self-evaluating forms, even though `eval' treats them like any
80 File: lispref.info, Node: Classifying Lists, Next: Function Indirection, Prev: Symbol Forms, Up: Forms
82 Classification of List Forms
83 ----------------------------
85 A form that is a nonempty list is either a function call, a macro
86 call, or a special form, according to its first element. These three
87 kinds of forms are evaluated in different ways, described below. The
88 remaining list elements constitute the "arguments" for the function,
89 macro, or special form.
91 The first step in evaluating a nonempty list is to examine its first
92 element. This element alone determines what kind of form the list is
93 and how the rest of the list is to be processed. The first element is
94 _not_ evaluated, as it would be in some Lisp dialects such as Scheme.
97 File: lispref.info, Node: Function Indirection, Next: Function Forms, Prev: Classifying Lists, Up: Forms
99 Symbol Function Indirection
100 ---------------------------
102 If the first element of the list is a symbol then evaluation examines
103 the symbol's function cell, and uses its contents instead of the
104 original symbol. If the contents are another symbol, this process,
105 called "symbol function indirection", is repeated until it obtains a
106 non-symbol. *Note Function Names::, for more information about using a
107 symbol as a name for a function stored in the function cell of the
110 One possible consequence of this process is an infinite loop, in the
111 event that a symbol's function cell refers to the same symbol. Or a
112 symbol may have a void function cell, in which case the subroutine
113 `symbol-function' signals a `void-function' error. But if neither of
114 these things happens, we eventually obtain a non-symbol, which ought to
115 be a function or other suitable object.
117 More precisely, we should now have a Lisp function (a lambda
118 expression), a byte-code function, a primitive function, a Lisp macro, a
119 special form, or an autoload object. Each of these types is a case
120 described in one of the following sections. If the object is not one of
121 these types, the error `invalid-function' is signaled.
123 The following example illustrates the symbol indirection process. We
124 use `fset' to set the function cell of a symbol and `symbol-function'
125 to get the function cell contents (*note Function Cells::).
126 Specifically, we store the symbol `car' into the function cell of
127 `first', and the symbol `first' into the function cell of `erste'.
129 ;; Build this function cell linkage:
130 ;; ------------- ----- ------- -------
131 ;; | #<subr car> | <-- | car | <-- | first | <-- | erste |
132 ;; ------------- ----- ------- -------
134 (symbol-function 'car)
140 (erste '(1 2 3)) ; Call the function referenced by `erste'.
143 By contrast, the following example calls a function without any
144 symbol function indirection, because the first element is an anonymous
145 Lisp function, not a symbol.
147 ((lambda (arg) (erste arg))
151 Executing the function itself evaluates its body; this does involve
152 symbol function indirection when calling `erste'.
154 The built-in function `indirect-function' provides an easy way to
155 perform symbol function indirection explicitly.
157 - Function: indirect-function function
158 This function returns the meaning of FUNCTION as a function. If
159 FUNCTION is a symbol, then it finds FUNCTION's function definition
160 and starts over with that value. If FUNCTION is not a symbol,
161 then it returns FUNCTION itself.
163 Here is how you could define `indirect-function' in Lisp:
165 (defun indirect-function (function)
166 (if (symbolp function)
167 (indirect-function (symbol-function function))
171 File: lispref.info, Node: Function Forms, Next: Macro Forms, Prev: Function Indirection, Up: Forms
173 Evaluation of Function Forms
174 ----------------------------
176 If the first element of a list being evaluated is a Lisp function
177 object, byte-code object or primitive function object, then that list is
178 a "function call". For example, here is a call to the function `+':
182 The first step in evaluating a function call is to evaluate the
183 remaining elements of the list from left to right. The results are the
184 actual argument values, one value for each list element. The next step
185 is to call the function with this list of arguments, effectively using
186 the function `apply' (*note Calling Functions::). If the function is
187 written in Lisp, the arguments are used to bind the argument variables
188 of the function (*note Lambda Expressions::); then the forms in the
189 function body are evaluated in order, and the value of the last body
190 form becomes the value of the function call.
193 File: lispref.info, Node: Macro Forms, Next: Special Forms, Prev: Function Forms, Up: Forms
195 Lisp Macro Evaluation
196 ---------------------
198 If the first element of a list being evaluated is a macro object,
199 then the list is a "macro call". When a macro call is evaluated, the
200 elements of the rest of the list are _not_ initially evaluated.
201 Instead, these elements themselves are used as the arguments of the
202 macro. The macro definition computes a replacement form, called the
203 "expansion" of the macro, to be evaluated in place of the original
204 form. The expansion may be any sort of form: a self-evaluating
205 constant, a symbol, or a list. If the expansion is itself a macro call,
206 this process of expansion repeats until some other sort of form results.
208 Ordinary evaluation of a macro call finishes by evaluating the
209 expansion. However, the macro expansion is not necessarily evaluated
210 right away, or at all, because other programs also expand macro calls,
211 and they may or may not evaluate the expansions.
213 Normally, the argument expressions are not evaluated as part of
214 computing the macro expansion, but instead appear as part of the
215 expansion, so they are computed when the expansion is computed.
217 For example, given a macro defined as follows:
220 (list 'car (list 'cdr x)))
222 an expression such as `(cadr (assq 'handler list))' is a macro call,
223 and its expansion is:
225 (car (cdr (assq 'handler list)))
227 Note that the argument `(assq 'handler list)' appears in the expansion.
229 *Note Macros::, for a complete description of XEmacs Lisp macros.
232 File: lispref.info, Node: Special Forms, Next: Autoloading, Prev: Macro Forms, Up: Forms
237 A "special form" is a primitive function specially marked so that
238 its arguments are not all evaluated. Most special forms define control
239 structures or perform variable bindings--things which functions cannot
242 Each special form has its own rules for which arguments are evaluated
243 and which are used without evaluation. Whether a particular argument is
244 evaluated may depend on the results of evaluating other arguments.
246 Here is a list, in alphabetical order, of all of the special forms in
247 XEmacs Lisp with a reference to where each is described.
250 *note Combining Conditions::
253 *note Catch and Throw::
259 *note Handling Errors::
262 *note Defining Variables::
265 *note Defining Macros::
268 *note Defining Functions::
271 *note Defining Variables::
274 *note Anonymous Functions::
280 *note Interactive Call::
284 *note Local Variables::
287 *note Combining Conditions::
297 `save-current-buffer'
306 `save-selected-window'
309 `save-window-excursion'
310 *note Window Configurations::
313 *note Setting Variables::
316 *note Creating Buffer-Local::
319 *note Nonlocal Exits::
324 `with-output-to-temp-buffer'
325 *note Temporary Displays::
327 Common Lisp note: here are some comparisons of special forms in
328 XEmacs Lisp and Common Lisp. `setq', `if', and `catch' are
329 special forms in both XEmacs Lisp and Common Lisp. `defun' is a
330 special form in XEmacs Lisp, but a macro in Common Lisp.
331 `save-excursion' is a special form in XEmacs Lisp, but doesn't
332 exist in Common Lisp. `throw' is a special form in Common Lisp
333 (because it must be able to throw multiple values), but it is a
334 function in XEmacs Lisp (which doesn't have multiple values).
337 File: lispref.info, Node: Autoloading, Prev: Special Forms, Up: Forms
342 The "autoload" feature allows you to call a function or macro whose
343 function definition has not yet been loaded into XEmacs. It specifies
344 which file contains the definition. When an autoload object appears as
345 a symbol's function definition, calling that symbol as a function
346 automatically loads the specified file; then it calls the real
347 definition loaded from that file. *Note Autoload::.
350 File: lispref.info, Node: Quoting, Prev: Forms, Up: Evaluation
355 The special form `quote' returns its single argument, as written,
356 without evaluating it. This provides a way to include constant symbols
357 and lists, which are not self-evaluating objects, in a program. (It is
358 not necessary to quote self-evaluating objects such as numbers, strings,
361 - Special Form: quote object
362 This special form returns OBJECT, without evaluating it.
364 Because `quote' is used so often in programs, Lisp provides a
365 convenient read syntax for it. An apostrophe character (`'') followed
366 by a Lisp object (in read syntax) expands to a list whose first element
367 is `quote', and whose second element is the object. Thus, the read
368 syntax `'x' is an abbreviation for `(quote x)'.
370 Here are some examples of expressions that use `quote':
385 Other quoting constructs include `function' (*note Anonymous
386 Functions::), which causes an anonymous lambda expression written in
387 Lisp to be compiled, and ``' (*note Backquote::), which is used to quote
388 only part of a list, while computing and substituting other parts.
391 File: lispref.info, Node: Control Structures, Next: Variables, Prev: Evaluation, Up: Top
396 A Lisp program consists of expressions or "forms" (*note Forms::).
397 We control the order of execution of the forms by enclosing them in
398 "control structures". Control structures are special forms which
399 control when, whether, or how many times to execute the forms they
402 The simplest order of execution is sequential execution: first form
403 A, then form B, and so on. This is what happens when you write several
404 forms in succession in the body of a function, or at top level in a
405 file of Lisp code--the forms are executed in the order written. We
406 call this "textual order". For example, if a function body consists of
407 two forms A and B, evaluation of the function evaluates first A and
408 then B, and the function's value is the value of B.
410 Explicit control structures make possible an order of execution other
413 XEmacs Lisp provides several kinds of control structure, including
414 other varieties of sequencing, conditionals, iteration, and (controlled)
415 jumps--all discussed below. The built-in control structures are
416 special forms since their subforms are not necessarily evaluated or not
417 evaluated sequentially. You can use macros to define your own control
418 structure constructs (*note Macros::).
422 * Sequencing:: Evaluation in textual order.
423 * Conditionals:: `if', `cond'.
424 * Combining Conditions:: `and', `or', `not'.
425 * Iteration:: `while' loops.
426 * Nonlocal Exits:: Jumping out of a sequence.
429 File: lispref.info, Node: Sequencing, Next: Conditionals, Up: Control Structures
434 Evaluating forms in the order they appear is the most common way
435 control passes from one form to another. In some contexts, such as in a
436 function body, this happens automatically. Elsewhere you must use a
437 control structure construct to do this: `progn', the simplest control
440 A `progn' special form looks like this:
444 and it says to execute the forms A, B, C and so on, in that order.
445 These forms are called the body of the `progn' form. The value of the
446 last form in the body becomes the value of the entire `progn'.
448 In the early days of Lisp, `progn' was the only way to execute two
449 or more forms in succession and use the value of the last of them. But
450 programmers found they often needed to use a `progn' in the body of a
451 function, where (at that time) only one form was allowed. So the body
452 of a function was made into an "implicit `progn'": several forms are
453 allowed just as in the body of an actual `progn'. Many other control
454 structures likewise contain an implicit `progn'. As a result, `progn'
455 is not used as often as it used to be. It is needed now most often
456 inside an `unwind-protect', `and', `or', or in the THEN-part of an `if'.
458 - Special Form: progn forms...
459 This special form evaluates all of the FORMS, in textual order,
460 returning the result of the final form.
462 (progn (print "The first form")
463 (print "The second form")
464 (print "The third form"))
470 Two other control constructs likewise evaluate a series of forms but
471 return a different value:
473 - Special Form: prog1 form1 forms...
474 This special form evaluates FORM1 and all of the FORMS, in textual
475 order, returning the result of FORM1.
477 (prog1 (print "The first form")
478 (print "The second form")
479 (print "The third form"))
485 Here is a way to remove the first element from a list in the
486 variable `x', then return the value of that former element:
488 (prog1 (car x) (setq x (cdr x)))
490 - Special Form: prog2 form1 form2 forms...
491 This special form evaluates FORM1, FORM2, and all of the following
492 FORMS, in textual order, returning the result of FORM2.
494 (prog2 (print "The first form")
495 (print "The second form")
496 (print "The third form"))
503 File: lispref.info, Node: Conditionals, Next: Combining Conditions, Prev: Sequencing, Up: Control Structures
508 Conditional control structures choose among alternatives. XEmacs
509 Lisp has two conditional forms: `if', which is much the same as in other
510 languages, and `cond', which is a generalized case statement.
512 - Special Form: if condition then-form else-forms...
513 `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
514 value of CONDITION. If the evaluated CONDITION is non-`nil',
515 THEN-FORM is evaluated and the result returned. Otherwise, the
516 ELSE-FORMS are evaluated in textual order, and the value of the
517 last one is returned. (The ELSE part of `if' is an example of an
518 implicit `progn'. *Note Sequencing::.)
520 If CONDITION has the value `nil', and no ELSE-FORMS are given,
523 `if' is a special form because the branch that is not selected is
524 never evaluated--it is ignored. Thus, in the example below,
525 `true' is not printed because `print' is never called.
532 - Special Form: cond clause...
533 `cond' chooses among an arbitrary number of alternatives. Each
534 CLAUSE in the `cond' must be a list. The CAR of this list is the
535 CONDITION; the remaining elements, if any, the BODY-FORMS. Thus,
536 a clause looks like this:
538 (CONDITION BODY-FORMS...)
540 `cond' tries the clauses in textual order, by evaluating the
541 CONDITION of each clause. If the value of CONDITION is non-`nil',
542 the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and
543 the value of the last of BODY-FORMS becomes the value of the
544 `cond'. The remaining clauses are ignored.
546 If the value of CONDITION is `nil', the clause "fails", so the
547 `cond' moves on to the following clause, trying its CONDITION.
549 If every CONDITION evaluates to `nil', so that every clause fails,
550 `cond' returns `nil'.
552 A clause may also look like this:
556 Then, if CONDITION is non-`nil' when tested, the value of
557 CONDITION becomes the value of the `cond' form.
559 The following example has four clauses, which test for the cases
560 where the value of `x' is a number, string, buffer and symbol,
563 (cond ((numberp x) x)
566 (setq temporary-hack x) ; multiple body-forms
567 (buffer-name x)) ; in one clause
568 ((symbolp x) (symbol-value x)))
570 Often we want to execute the last clause whenever none of the
571 previous clauses was successful. To do this, we use `t' as the
572 CONDITION of the last clause, like this: `(t BODY-FORMS)'. The
573 form `t' evaluates to `t', which is never `nil', so this clause
574 never fails, provided the `cond' gets to it at all.
578 (cond ((eq a 'hack) 'foo)
582 This expression is a `cond' which returns `foo' if the value of
583 `a' is 1, and returns the string `"default"' otherwise.
585 Any conditional construct can be expressed with `cond' or with `if'.
586 Therefore, the choice between them is a matter of style. For example:
593 File: lispref.info, Node: Combining Conditions, Next: Iteration, Prev: Conditionals, Up: Control Structures
595 Constructs for Combining Conditions
596 ===================================
598 This section describes three constructs that are often used together
599 with `if' and `cond' to express complicated conditions. The constructs
600 `and' and `or' can also be used individually as kinds of multiple
601 conditional constructs.
603 - Function: not condition
604 This function tests for the falsehood of CONDITION. It returns
605 `t' if CONDITION is `nil', and `nil' otherwise. The function
606 `not' is identical to `null', and we recommend using the name
607 `null' if you are testing for an empty list.
609 - Special Form: and conditions...
610 The `and' special form tests whether all the CONDITIONS are true.
611 It works by evaluating the CONDITIONS one by one in the order
614 If any of the CONDITIONS evaluates to `nil', then the result of
615 the `and' must be `nil' regardless of the remaining CONDITIONS; so
616 `and' returns right away, ignoring the remaining CONDITIONS.
618 If all the CONDITIONS turn out non-`nil', then the value of the
619 last of them becomes the value of the `and' form.
621 Here is an example. The first condition returns the integer 1,
622 which is not `nil'. Similarly, the second condition returns the
623 integer 2, which is not `nil'. The third condition is `nil', so
624 the remaining condition is never evaluated.
626 (and (print 1) (print 2) nil (print 3))
631 Here is a more realistic example of using `and':
633 (if (and (consp foo) (eq (car foo) 'x))
634 (message "foo is a list starting with x"))
636 Note that `(car foo)' is not executed if `(consp foo)' returns
637 `nil', thus avoiding an error.
639 `and' can be expressed in terms of either `if' or `cond'. For
644 (if ARG1 (if ARG2 ARG3))
646 (cond (ARG1 (cond (ARG2 ARG3))))
648 - Special Form: or conditions...
649 The `or' special form tests whether at least one of the CONDITIONS
650 is true. It works by evaluating all the CONDITIONS one by one in
653 If any of the CONDITIONS evaluates to a non-`nil' value, then the
654 result of the `or' must be non-`nil'; so `or' returns right away,
655 ignoring the remaining CONDITIONS. The value it returns is the
656 non-`nil' value of the condition just evaluated.
658 If all the CONDITIONS turn out `nil', then the `or' expression
661 For example, this expression tests whether `x' is either 0 or
664 (or (eq x nil) (eq x 0))
666 Like the `and' construct, `or' can be written in terms of `cond'.
675 You could almost write `or' in terms of `if', but not quite:
681 This is not completely equivalent because it can evaluate ARG1 or
682 ARG2 twice. By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
683 any argument more than once.
686 File: lispref.info, Node: Iteration, Next: Nonlocal Exits, Prev: Combining Conditions, Up: Control Structures
691 Iteration means executing part of a program repetitively. For
692 example, you might want to repeat some computation once for each element
693 of a list, or once for each integer from 0 to N. You can do this in
694 XEmacs Lisp with the special form `while':
696 - Special Form: while condition forms...
697 `while' first evaluates CONDITION. If the result is non-`nil', it
698 evaluates FORMS in textual order. Then it reevaluates CONDITION,
699 and if the result is non-`nil', it evaluates FORMS again. This
700 process repeats until CONDITION evaluates to `nil'.
702 There is no limit on the number of iterations that may occur. The
703 loop will continue until either CONDITION evaluates to `nil' or
704 until an error or `throw' jumps out of it (*note Nonlocal Exits::).
706 The value of a `while' form is always `nil'.
711 (princ (format "Iteration %d." num))
719 If you would like to execute something on each iteration before the
720 end-test, put it together with the end-test in a `progn' as the
721 first argument of `while', as shown here:
725 (not (looking-at "^$"))))
727 This moves forward one line and continues moving by lines until it
728 reaches an empty. It is unusual in that the `while' has no body,
729 just the end test (which also does the real work of moving point).
732 File: lispref.info, Node: Nonlocal Exits, Prev: Iteration, Up: Control Structures
737 A "nonlocal exit" is a transfer of control from one point in a
738 program to another remote point. Nonlocal exits can occur in XEmacs
739 Lisp as a result of errors; you can also use them under explicit
740 control. Nonlocal exits unbind all variable bindings made by the
741 constructs being exited.
745 * Catch and Throw:: Nonlocal exits for the program's own purposes.
746 * Examples of Catch:: Showing how such nonlocal exits can be written.
747 * Errors:: How errors are signaled and handled.
748 * Cleanups:: Arranging to run a cleanup form if an error happens.
751 File: lispref.info, Node: Catch and Throw, Next: Examples of Catch, Up: Nonlocal Exits
753 Explicit Nonlocal Exits: `catch' and `throw'
754 --------------------------------------------
756 Most control constructs affect only the flow of control within the
757 construct itself. The function `throw' is the exception to this rule
758 of normal program execution: it performs a nonlocal exit on request.
759 (There are other exceptions, but they are for error handling only.)
760 `throw' is used inside a `catch', and jumps back to that `catch'. For
769 The `throw' transfers control straight back to the corresponding
770 `catch', which returns immediately. The code following the `throw' is
771 not executed. The second argument of `throw' is used as the return
772 value of the `catch'.
774 The `throw' and the `catch' are matched through the first argument:
775 `throw' searches for a `catch' whose first argument is `eq' to the one
776 specified. Thus, in the above example, the `throw' specifies `foo',
777 and the `catch' specifies the same symbol, so that `catch' is
778 applicable. If there is more than one applicable `catch', the
779 innermost one takes precedence.
781 Executing `throw' exits all Lisp constructs up to the matching
782 `catch', including function calls. When binding constructs such as
783 `let' or function calls are exited in this way, the bindings are
784 unbound, just as they are when these constructs exit normally (*note
785 Local Variables::). Likewise, `throw' restores the buffer and position
786 saved by `save-excursion' (*note Excursions::), and the narrowing
787 status saved by `save-restriction' and the window selection saved by
788 `save-window-excursion' (*note Window Configurations::). It also runs
789 any cleanups established with the `unwind-protect' special form when it
790 exits that form (*note Cleanups::).
792 The `throw' need not appear lexically within the `catch' that it
793 jumps to. It can equally well be called from another function called
794 within the `catch'. As long as the `throw' takes place chronologically
795 after entry to the `catch', and chronologically before exit from it, it
796 has access to that `catch'. This is why `throw' can be used in
797 commands such as `exit-recursive-edit' that throw back to the editor
798 command loop (*note Recursive Editing::).
800 Common Lisp note: Most other versions of Lisp, including Common
801 Lisp, have several ways of transferring control nonsequentially:
802 `return', `return-from', and `go', for example. XEmacs Lisp has
805 - Special Form: catch tag body...
806 `catch' establishes a return point for the `throw' function. The
807 return point is distinguished from other such return points by TAG,
808 which may be any Lisp object. The argument TAG is evaluated
809 normally before the return point is established.
811 With the return point in effect, `catch' evaluates the forms of the
812 BODY in textual order. If the forms execute normally, without
813 error or nonlocal exit, the value of the last body form is
814 returned from the `catch'.
816 If a `throw' is done within BODY specifying the same value TAG,
817 the `catch' exits immediately; the value it returns is whatever
818 was specified as the second argument of `throw'.
820 - Function: throw tag value
821 The purpose of `throw' is to return from a return point previously
822 established with `catch'. The argument TAG is used to choose
823 among the various existing return points; it must be `eq' to the
824 value specified in the `catch'. If multiple return points match
825 TAG, the innermost one is used.
827 The argument VALUE is used as the value to return from that
830 If no return point is in effect with tag TAG, then a `no-catch'
831 error is signaled with data `(TAG VALUE)'.
834 File: lispref.info, Node: Examples of Catch, Next: Errors, Prev: Catch and Throw, Up: Nonlocal Exits
836 Examples of `catch' and `throw'
837 -------------------------------
839 One way to use `catch' and `throw' is to exit from a doubly nested
840 loop. (In most languages, this would be done with a "go to".) Here we
841 compute `(foo I J)' for I and J varying from 0 to 9:
850 (throw 'loop (list i j)))
854 If `foo' ever returns non-`nil', we stop immediately and return a list
855 of I and J. If `foo' always returns `nil', the `catch' returns
856 normally, and the value is `nil', since that is the result of the
859 Here are two tricky examples, slightly different, showing two return
860 points at once. First, two return points with the same tag, `hack':
868 (print (catch2 'hack))
873 Since both return points have tags that match the `throw', it goes to
874 the inner one, the one established in `catch2'. Therefore, `catch2'
875 returns normally with value `yes', and this value is printed. Finally
876 the second body form in the outer `catch', which is `'no', is evaluated
877 and returned from the outer `catch'.
879 Now let's change the argument given to `catch2':
887 (print (catch2 'quux))
891 We still have two return points, but this time only the outer one has
892 the tag `hack'; the inner one has the tag `quux' instead. Therefore,
893 `throw' makes the outer `catch' return the value `yes'. The function
894 `print' is never called, and the body-form `'no' is never evaluated.
897 File: lispref.info, Node: Errors, Next: Cleanups, Prev: Examples of Catch, Up: Nonlocal Exits
902 When XEmacs Lisp attempts to evaluate a form that, for some reason,
903 cannot be evaluated, it "signals" an "error".
905 When an error is signaled, XEmacs's default reaction is to print an
906 error message and terminate execution of the current command. This is
907 the right thing to do in most cases, such as if you type `C-f' at the
910 In complicated programs, simple termination may not be what you want.
911 For example, the program may have made temporary changes in data
912 structures, or created temporary buffers that should be deleted before
913 the program is finished. In such cases, you would use `unwind-protect'
914 to establish "cleanup expressions" to be evaluated in case of error.
915 (*Note Cleanups::.) Occasionally, you may wish the program to continue
916 execution despite an error in a subroutine. In these cases, you would
917 use `condition-case' to establish "error handlers" to recover control
920 Resist the temptation to use error handling to transfer control from
921 one part of the program to another; use `catch' and `throw' instead.
922 *Note Catch and Throw::.
926 * Signaling Errors:: How to report an error.
927 * Processing of Errors:: What XEmacs does when you report an error.
928 * Handling Errors:: How you can trap errors and continue execution.
929 * Error Symbols:: How errors are classified for trapping them.
932 File: lispref.info, Node: Signaling Errors, Next: Processing of Errors, Up: Errors
934 How to Signal an Error
935 ......................
937 Most errors are signaled "automatically" within Lisp primitives
938 which you call for other purposes, such as if you try to take the CAR
939 of an integer or move forward a character at the end of the buffer; you
940 can also signal errors explicitly with the functions `error' and
943 Quitting, which happens when the user types `C-g', is not considered
944 an error, but it is handled almost like an error. *Note Quitting::.
946 - Function: error format-string &rest args
947 This function signals an error with an error message constructed by
948 applying `format' (*note String Conversion::) to FORMAT-STRING and
951 These examples show typical uses of `error':
953 (error "You have committed an error.
954 Try something else.")
955 error--> You have committed an error.
958 (error "You have committed %d errors." 10)
959 error--> You have committed 10 errors.
961 `error' works by calling `signal' with two arguments: the error
962 symbol `error', and a list containing the string returned by
965 If you want to use your own string as an error message verbatim,
966 don't just write `(error STRING)'. If STRING contains `%', it
967 will be interpreted as a format specifier, with undesirable
968 results. Instead, use `(error "%s" STRING)'.
970 - Function: signal error-symbol data
971 This function signals an error named by ERROR-SYMBOL. The
972 argument DATA is a list of additional Lisp objects relevant to the
973 circumstances of the error.
975 The argument ERROR-SYMBOL must be an "error symbol"--a symbol
976 bearing a property `error-conditions' whose value is a list of
977 condition names. This is how XEmacs Lisp classifies different
980 The number and significance of the objects in DATA depends on
981 ERROR-SYMBOL. For example, with a `wrong-type-arg' error, there
982 are two objects in the list: a predicate that describes the type
983 that was expected, and the object that failed to fit that type.
984 *Note Error Symbols::, for a description of error symbols.
986 Both ERROR-SYMBOL and DATA are available to any error handlers
987 that handle the error: `condition-case' binds a local variable to
988 a list of the form `(ERROR-SYMBOL . DATA)' (*note Handling
989 Errors::). If the error is not handled, these two values are used
990 in printing the error message.
992 The function `signal' never returns (though in older Emacs versions
993 it could sometimes return).
995 (signal 'wrong-number-of-arguments '(x y))
996 error--> Wrong number of arguments: x, y
998 (signal 'no-such-error '("My unknown error condition."))
999 error--> peculiar error: "My unknown error condition."
1001 Common Lisp note: XEmacs Lisp has nothing like the Common Lisp
1002 concept of continuable errors.
1005 File: lispref.info, Node: Processing of Errors, Next: Handling Errors, Prev: Signaling Errors, Up: Errors
1007 How XEmacs Processes Errors
1008 ...........................
1010 When an error is signaled, `signal' searches for an active "handler"
1011 for the error. A handler is a sequence of Lisp expressions designated
1012 to be executed if an error happens in part of the Lisp program. If the
1013 error has an applicable handler, the handler is executed, and control
1014 resumes following the handler. The handler executes in the environment
1015 of the `condition-case' that established it; all functions called
1016 within that `condition-case' have already been exited, and the handler
1017 cannot return to them.
1019 If there is no applicable handler for the error, the current command
1020 is terminated and control returns to the editor command loop, because
1021 the command loop has an implicit handler for all kinds of errors. The
1022 command loop's handler uses the error symbol and associated data to
1023 print an error message.
1025 An error that has no explicit handler may call the Lisp debugger.
1026 The debugger is enabled if the variable `debug-on-error' (*note Error
1027 Debugging::) is non-`nil'. Unlike error handlers, the debugger runs in
1028 the environment of the error, so that you can examine values of
1029 variables precisely as they were at the time of the error.
1032 File: lispref.info, Node: Handling Errors, Next: Error Symbols, Prev: Processing of Errors, Up: Errors
1034 Writing Code to Handle Errors
1035 .............................
1037 The usual effect of signaling an error is to terminate the command
1038 that is running and return immediately to the XEmacs editor command
1039 loop. You can arrange to trap errors occurring in a part of your
1040 program by establishing an error handler, with the special form
1041 `condition-case'. A simple example looks like this:
1044 (delete-file filename)
1047 This deletes the file named FILENAME, catching any error and returning
1048 `nil' if an error occurs.
1050 The second argument of `condition-case' is called the "protected
1051 form". (In the example above, the protected form is a call to
1052 `delete-file'.) The error handlers go into effect when this form
1053 begins execution and are deactivated when this form returns. They
1054 remain in effect for all the intervening time. In particular, they are
1055 in effect during the execution of functions called by this form, in
1056 their subroutines, and so on. This is a good thing, since, strictly
1057 speaking, errors can be signaled only by Lisp primitives (including
1058 `signal' and `error') called by the protected form, not by the
1059 protected form itself.
1061 The arguments after the protected form are handlers. Each handler
1062 lists one or more "condition names" (which are symbols) to specify
1063 which errors it will handle. The error symbol specified when an error
1064 is signaled also defines a list of condition names. A handler applies
1065 to an error if they have any condition names in common. In the example
1066 above, there is one handler, and it specifies one condition name,
1067 `error', which covers all errors.
1069 The search for an applicable handler checks all the established
1070 handlers starting with the most recently established one. Thus, if two
1071 nested `condition-case' forms offer to handle the same error, the inner
1072 of the two will actually handle it.
1074 When an error is handled, control returns to the handler. Before
1075 this happens, XEmacs unbinds all variable bindings made by binding
1076 constructs that are being exited and executes the cleanups of all
1077 `unwind-protect' forms that are exited. Once control arrives at the
1078 handler, the body of the handler is executed.
1080 After execution of the handler body, execution continues by returning
1081 from the `condition-case' form. Because the protected form is exited
1082 completely before execution of the handler, the handler cannot resume
1083 execution at the point of the error, nor can it examine variable
1084 bindings that were made within the protected form. All it can do is
1085 clean up and proceed.
1087 `condition-case' is often used to trap errors that are predictable,
1088 such as failure to open a file in a call to `insert-file-contents'. It
1089 is also used to trap errors that are totally unpredictable, such as
1090 when the program evaluates an expression read from the user.
1092 Error signaling and handling have some resemblance to `throw' and
1093 `catch', but they are entirely separate facilities. An error cannot be
1094 caught by a `catch', and a `throw' cannot be handled by an error
1095 handler (though using `throw' when there is no suitable `catch' signals
1096 an error that can be handled).
1098 - Special Form: condition-case var protected-form handlers...
1099 This special form establishes the error handlers HANDLERS around
1100 the execution of PROTECTED-FORM. If PROTECTED-FORM executes
1101 without error, the value it returns becomes the value of the
1102 `condition-case' form; in this case, the `condition-case' has no
1103 effect. The `condition-case' form makes a difference when an
1104 error occurs during PROTECTED-FORM.
1106 Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
1107 Here CONDITIONS is an error condition name to be handled, or a
1108 list of condition names; BODY is one or more Lisp expressions to
1109 be executed when this handler handles an error. Here are examples
1114 (arith-error (message "Division by zero"))
1116 ((arith-error file-error)
1118 "Either division by zero or failure to open a file"))
1120 Each error that occurs has an "error symbol" that describes what
1121 kind of error it is. The `error-conditions' property of this
1122 symbol is a list of condition names (*note Error Symbols::). Emacs
1123 searches all the active `condition-case' forms for a handler that
1124 specifies one or more of these condition names; the innermost
1125 matching `condition-case' handles the error. Within this
1126 `condition-case', the first applicable handler handles the error.
1128 After executing the body of the handler, the `condition-case'
1129 returns normally, using the value of the last form in the handler
1130 body as the overall value.
1132 The argument VAR is a variable. `condition-case' does not bind
1133 this variable when executing the PROTECTED-FORM, only when it
1134 handles an error. At that time, it binds VAR locally to a list of
1135 the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
1136 error. The handler can refer to this list to decide what to do.
1137 For example, if the error is for failure opening a file, the file
1138 name is the second element of DATA--the third element of VAR.
1140 If VAR is `nil', that means no variable is bound. Then the error
1141 symbol and associated data are not available to the handler.
1143 Here is an example of using `condition-case' to handle the error
1144 that results from dividing by zero. The handler prints out a warning
1145 message and returns a very large number.
1147 (defun safe-divide (dividend divisor)
1150 (/ dividend divisor)
1152 (arith-error ; Condition.
1153 (princ (format "Arithmetic error: %s" err))
1158 -| Arithmetic error: (arith-error)
1161 The handler specifies condition name `arith-error' so that it will
1162 handle only division-by-zero errors. Other kinds of errors will not be
1163 handled, at least not by this `condition-case'. Thus,
1166 error--> Wrong type argument: integer-or-marker-p, nil
1168 Here is a `condition-case' that catches all kinds of errors,
1169 including those signaled with `error':
1177 ;; This is a call to the function `error'.
1178 (error "Rats! The variable %s was %s, not 35" 'baz baz))
1179 ;; This is the handler; it is not a form.
1180 (error (princ (format "The error was: %s" err))
1182 -| The error was: (error "Rats! The variable baz was 34, not 35")
1186 File: lispref.info, Node: Error Symbols, Prev: Handling Errors, Up: Errors
1188 Error Symbols and Condition Names
1189 .................................
1191 When you signal an error, you specify an "error symbol" to specify
1192 the kind of error you have in mind. Each error has one and only one
1193 error symbol to categorize it. This is the finest classification of
1194 errors defined by the XEmacs Lisp language.
1196 These narrow classifications are grouped into a hierarchy of wider
1197 classes called "error conditions", identified by "condition names".
1198 The narrowest such classes belong to the error symbols themselves: each
1199 error symbol is also a condition name. There are also condition names
1200 for more extensive classes, up to the condition name `error' which
1201 takes in all kinds of errors. Thus, each error has one or more
1202 condition names: `error', the error symbol if that is distinct from
1203 `error', and perhaps some intermediate classifications.
1205 In order for a symbol to be an error symbol, it must have an
1206 `error-conditions' property which gives a list of condition names.
1207 This list defines the conditions that this kind of error belongs to.
1208 (The error symbol itself, and the symbol `error', should always be
1209 members of this list.) Thus, the hierarchy of condition names is
1210 defined by the `error-conditions' properties of the error symbols.
1212 In addition to the `error-conditions' list, the error symbol should
1213 have an `error-message' property whose value is a string to be printed
1214 when that error is signaled but not handled. If the `error-message'
1215 property exists, but is not a string, the error message `peculiar
1218 Here is how we define a new error symbol, `new-error':
1222 '(error my-own-errors new-error))
1223 => (error my-own-errors new-error)
1224 (put 'new-error 'error-message "A new error")
1227 This error has three condition names: `new-error', the narrowest
1228 classification; `my-own-errors', which we imagine is a wider
1229 classification; and `error', which is the widest of all.
1231 The error string should start with a capital letter but it should
1232 not end with a period. This is for consistency with the rest of Emacs.
1234 Naturally, XEmacs will never signal `new-error' on its own; only an
1235 explicit call to `signal' (*note Signaling Errors::) in your code can
1238 (signal 'new-error '(x y))
1239 error--> A new error: x, y
1241 This error can be handled through any of the three condition names.
1242 This example handles `new-error' and any other errors in the class
1247 (my-own-errors nil))
1249 The significant way that errors are classified is by their condition
1250 names--the names used to match errors with handlers. An error symbol
1251 serves only as a convenient way to specify the intended error message
1252 and list of condition names. It would be cumbersome to give `signal' a
1253 list of condition names rather than one error symbol.
1255 By contrast, using only error symbols without condition names would
1256 seriously decrease the power of `condition-case'. Condition names make
1257 it possible to categorize errors at various levels of generality when
1258 you write an error handler. Using error symbols alone would eliminate
1259 all but the narrowest level of classification.
1261 *Note Standard Errors::, for a list of all the standard error symbols
1262 and their conditions.