1 @c -*- mode: texinfo; coding: utf-8 -*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2018 Free Software
5 @c See the file elisp.texi for copying conditions.
6 @node Control Structures
7 @chapter Control Structures
8 @cindex special forms for control structures
9 @cindex control structures
11 A Lisp program consists of a set of @dfn{expressions}, or
12 @dfn{forms} (@pxref{Forms}). We control the order of execution of
13 these forms by enclosing them in @dfn{control structures}. Control
14 structures are special forms which control when, whether, or how many
15 times to execute the forms they contain.
18 The simplest order of execution is sequential execution: first form
19 @var{a}, then form @var{b}, and so on. This is what happens when you
20 write several forms in succession in the body of a function, or at top
21 level in a file of Lisp code---the forms are executed in the order
22 written. We call this @dfn{textual order}. For example, if a function
23 body consists of two forms @var{a} and @var{b}, evaluation of the
24 function evaluates first @var{a} and then @var{b}. The result of
25 evaluating @var{b} becomes the value of the function.
27 Explicit control structures make possible an order of execution other
30 Emacs Lisp provides several kinds of control structure, including
31 other varieties of sequencing, conditionals, iteration, and (controlled)
32 jumps---all discussed below. The built-in control structures are
33 special forms since their subforms are not necessarily evaluated or not
34 evaluated sequentially. You can use macros to define your own control
35 structure constructs (@pxref{Macros}).
38 * Sequencing:: Evaluation in textual order.
39 * Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}.
40 * Combining Conditions:: @code{and}, @code{or}, @code{not}.
41 * Iteration:: @code{while} loops.
42 * Generators:: Generic sequences and coroutines.
43 * Nonlocal Exits:: Jumping out of a sequence.
49 @cindex sequential execution
51 Evaluating forms in the order they appear is the most common way
52 control passes from one form to another. In some contexts, such as in a
53 function body, this happens automatically. Elsewhere you must use a
54 control structure construct to do this: @code{progn}, the simplest
55 control construct of Lisp.
57 A @code{progn} special form looks like this:
61 (progn @var{a} @var{b} @var{c} @dots{})
66 and it says to execute the forms @var{a}, @var{b}, @var{c}, and so on, in
67 that order. These forms are called the @dfn{body} of the @code{progn} form.
68 The value of the last form in the body becomes the value of the entire
69 @code{progn}. @code{(progn)} returns @code{nil}.
71 @cindex implicit @code{progn}
72 In the early days of Lisp, @code{progn} was the only way to execute
73 two or more forms in succession and use the value of the last of them.
74 But programmers found they often needed to use a @code{progn} in the
75 body of a function, where (at that time) only one form was allowed. So
76 the body of a function was made into an implicit @code{progn}:
77 several forms are allowed just as in the body of an actual @code{progn}.
78 Many other control structures likewise contain an implicit @code{progn}.
79 As a result, @code{progn} is not used as much as it was many years ago.
80 It is needed now most often inside an @code{unwind-protect}, @code{and},
81 @code{or}, or in the @var{then}-part of an @code{if}.
83 @defspec progn forms@dots{}
84 This special form evaluates all of the @var{forms}, in textual
85 order, returning the result of the final form.
89 (progn (print "The first form")
90 (print "The second form")
91 (print "The third form"))
92 @print{} "The first form"
93 @print{} "The second form"
94 @print{} "The third form"
95 @result{} "The third form"
100 Two other constructs likewise evaluate a series of forms but return
103 @defspec prog1 form1 forms@dots{}
104 This special form evaluates @var{form1} and all of the @var{forms}, in
105 textual order, returning the result of @var{form1}.
109 (prog1 (print "The first form")
110 (print "The second form")
111 (print "The third form"))
112 @print{} "The first form"
113 @print{} "The second form"
114 @print{} "The third form"
115 @result{} "The first form"
119 Here is a way to remove the first element from a list in the variable
120 @code{x}, then return the value of that former element:
123 (prog1 (car x) (setq x (cdr x)))
127 @defspec prog2 form1 form2 forms@dots{}
128 This special form evaluates @var{form1}, @var{form2}, and all of the
129 following @var{forms}, in textual order, returning the result of
134 (prog2 (print "The first form")
135 (print "The second form")
136 (print "The third form"))
137 @print{} "The first form"
138 @print{} "The second form"
139 @print{} "The third form"
140 @result{} "The second form"
146 @section Conditionals
147 @cindex conditional evaluation
149 Conditional control structures choose among alternatives. Emacs Lisp
150 has four conditional forms: @code{if}, which is much the same as in
151 other languages; @code{when} and @code{unless}, which are variants of
152 @code{if}; and @code{cond}, which is a generalized case statement.
154 @defspec if condition then-form else-forms@dots{}
155 @code{if} chooses between the @var{then-form} and the @var{else-forms}
156 based on the value of @var{condition}. If the evaluated @var{condition} is
157 non-@code{nil}, @var{then-form} is evaluated and the result returned.
158 Otherwise, the @var{else-forms} are evaluated in textual order, and the
159 value of the last one is returned. (The @var{else} part of @code{if} is
160 an example of an implicit @code{progn}. @xref{Sequencing}.)
162 If @var{condition} has the value @code{nil}, and no @var{else-forms} are
163 given, @code{if} returns @code{nil}.
165 @code{if} is a special form because the branch that is not selected is
166 never evaluated---it is ignored. Thus, in this example,
167 @code{true} is not printed because @code{print} is never called:
179 @defmac when condition then-forms@dots{}
180 This is a variant of @code{if} where there are no @var{else-forms},
181 and possibly several @var{then-forms}. In particular,
184 (when @var{condition} @var{a} @var{b} @var{c})
188 is entirely equivalent to
191 (if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
195 @defmac unless condition forms@dots{}
196 This is a variant of @code{if} where there is no @var{then-form}:
199 (unless @var{condition} @var{a} @var{b} @var{c})
203 is entirely equivalent to
206 (if @var{condition} nil
207 @var{a} @var{b} @var{c})
211 @defspec cond clause@dots{}
212 @code{cond} chooses among an arbitrary number of alternatives. Each
213 @var{clause} in the @code{cond} must be a list. The @sc{car} of this
214 list is the @var{condition}; the remaining elements, if any, the
215 @var{body-forms}. Thus, a clause looks like this:
218 (@var{condition} @var{body-forms}@dots{})
221 @code{cond} tries the clauses in textual order, by evaluating the
222 @var{condition} of each clause. If the value of @var{condition} is
223 non-@code{nil}, the clause succeeds; then @code{cond} evaluates its
224 @var{body-forms}, and returns the value of the last of @var{body-forms}.
225 Any remaining clauses are ignored.
227 If the value of @var{condition} is @code{nil}, the clause fails, so
228 the @code{cond} moves on to the following clause, trying its @var{condition}.
230 A clause may also look like this:
237 Then, if @var{condition} is non-@code{nil} when tested, the @code{cond}
238 form returns the value of @var{condition}.
240 If every @var{condition} evaluates to @code{nil}, so that every clause
241 fails, @code{cond} returns @code{nil}.
243 The following example has four clauses, which test for the cases where
244 the value of @code{x} is a number, string, buffer and symbol,
249 (cond ((numberp x) x)
252 (setq temporary-hack x) ; @r{multiple body-forms}
253 (buffer-name x)) ; @r{in one clause}
254 ((symbolp x) (symbol-value x)))
258 Often we want to execute the last clause whenever none of the previous
259 clauses was successful. To do this, we use @code{t} as the
260 @var{condition} of the last clause, like this: @code{(t
261 @var{body-forms})}. The form @code{t} evaluates to @code{t}, which is
262 never @code{nil}, so this clause never fails, provided the @code{cond}
263 gets to it at all. For example:
268 (cond ((eq a 'hack) 'foo)
275 This @code{cond} expression returns @code{foo} if the value of @code{a}
276 is @code{hack}, and returns the string @code{"default"} otherwise.
279 Any conditional construct can be expressed with @code{cond} or with
280 @code{if}. Therefore, the choice between them is a matter of style.
285 (if @var{a} @var{b} @var{c})
287 (cond (@var{a} @var{b}) (t @var{c}))
292 * Pattern matching case statement::
295 @node Pattern matching case statement
296 @subsection Pattern matching case statement
298 @cindex pattern matching
300 The @code{cond} form lets you choose between alternatives using
301 predicate conditions that compare values of expressions against
302 specific values known and written in advance. However, sometimes it
303 is useful to select alternatives based on more general conditions that
304 distinguish between broad classes of values. The @code{pcase} macro
305 allows you to choose between alternatives based on matching the value
306 of an expression against a series of patterns. A pattern can be a
307 literal value (for comparisons to literal values you'd use
308 @code{cond}), or it can be a more general description of the expected
309 structure of the expression's value.
311 @defmac pcase expression &rest clauses
312 Evaluate @var{expression} and choose among an arbitrary number of
313 alternatives based on the value of @var{expression}. The possible
314 alternatives are specified by @var{clauses}, each of which must be a
315 list of the form @code{(@var{pattern} @var{body-forms}@dots{})}.
316 @code{pcase} tries to match the value of @var{expression} to the
317 @var{pattern} of each clause, in textual order. If the value matches,
318 the clause succeeds; @code{pcase} then evaluates its @var{body-forms},
319 and returns the value of the last of @var{body-forms}. Any remaining
320 @var{clauses} are ignored.
322 The @var{pattern} part of a clause can be of one of two types:
323 @dfn{QPattern}, a pattern quoted with a backquote; or a
324 @dfn{UPattern}, which is not quoted. UPatterns are simpler, so we
327 Note: In the description of the patterns below, we use ``the value
328 being matched'' to refer to the value of the @var{expression} that is
329 the first argument of @code{pcase}.
331 A UPattern can have the following forms:
336 Matches if the value being matched is @code{equal} to @var{val}.
338 Matches any @var{atom}, which can be a keyword, a number, or a string.
339 (These are self-quoting, so this kind of UPattern is actually a
340 shorthand for @code{'@var{atom}}.) Note that a string or a float
341 matches any string or float with the same contents/value.
343 Matches any value. This is known as @dfn{don't care} or @dfn{wildcard}.
345 Matches any value, and additionally let-binds @var{symbol} to the
346 value it matched, so that you can later refer to it, either in the
347 @var{body-forms} or also later in the pattern.
348 @item (pred @var{predfun})
349 Matches if the predicate function @var{predfun} returns non-@code{nil}
350 when called with the value being matched as its argument.
351 @var{predfun} can be one of the possible forms described below.
352 @item (guard @var{boolean-expression})
353 Matches if @var{boolean-expression} evaluates to non-@code{nil}. This
354 allows you to include in a UPattern boolean conditions that refer to
355 symbols bound to values (including the value being matched) by
356 previous UPatterns. Typically used inside an @code{and} UPattern, see
357 below. For example, @w{@code{(and x (guard (< x 10)))}} is a pattern
358 which matches any number smaller than 10 and let-binds the variable
359 @code{x} to that number.
360 @item (let @var{upattern} @var{expression})
361 Matches if the specified @var{expression} matches the specified
362 @var{upattern}. This allows matching a pattern against the value of
363 an @emph{arbitrary} expression, not just the expression that is the
364 first argument to @code{pcase}. (It is called @code{let} because
365 @var{upattern} can bind symbols to values using the @var{symbol}
366 UPattern. For example:
367 @w{@code{((or `(key . ,val) (let val 5)) val)}}.)
368 @item (app @var{function} @var{upattern})
369 Matches if @var{function} applied to the value being matched returns a
370 value that matches @var{upattern}. This is like the @code{pred}
371 UPattern, except that it tests the result against @var{upattern},
372 rather than against a boolean truth value. The @var{function} call can
373 use one of the forms described below.
374 @item (or @var{upattern1} @var{upattern2}@dots{})
375 Matches if one the argument UPatterns matches. As soon as the first
376 matching UPattern is found, the rest are not tested. For this reason,
377 if any of the UPatterns let-bind symbols to the matched value, they
378 should all bind the same symbols.
379 @item (and @var{upattern1} @var{upattern2}@dots{})
380 Matches if all the argument UPatterns match.
383 The function calls used in the @code{pred} and @code{app} UPatterns
384 can have one of the following forms:
387 @item function symbol, like @code{integerp}
388 In this case, the named function is applied to the value being
390 @item lambda-function @code{(lambda (@var{arg}) @var{body})}
391 In this case, the lambda-function is called with one argument, the
393 @item @code{(@var{func} @var{args}@dots{})}
394 This is a function call with @var{n} specified arguments; the function
395 is called with these @var{n} arguments and an additional @var{n}+1-th
396 argument that is the value being matched.
399 Here's an illustrative example of using UPatterns:
401 @c FIXME: This example should use every one of the UPatterns described
402 @c above at least once.
404 (pcase (get-return-code x)
405 ('success (message "Done!"))
406 ('would-block (message "Sorry, can't do it now"))
407 ('read-only (message "The shmliblick is read-only"))
408 ('access-denied (message "You do not have the needed rights"))
409 (code (message "Unknown return code %S" code)))
412 In addition, you can use backquoted patterns that are more powerful.
413 They allow matching the value of the @var{expression} that is the
414 first argument of @code{pcase} against specifications of its
415 @emph{structure}. For example, you can specify that the value must be
416 a list of 2 elements whose first element is a specific string and the
417 second element is any value with a backquoted pattern like
418 @code{`("first" ,second-elem)}.
420 Backquoted patterns have the form @code{`@var{qpattern}} where
421 @var{qpattern} can have the following forms:
424 @item (@var{qpattern1} . @var{qpattern2})
425 Matches if the value being matched is a cons cell whose @code{car}
426 matches @var{qpattern1} and whose @code{cdr} matches @var{qpattern2}.
427 This readily generalizes to backquoted lists as in
428 @w{@code{(@var{qpattern1} @var{qpattern2} @dots{})}}.
429 @item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}]
430 Matches if the value being matched is a vector of length @var{m} whose
431 @code{0}..@code{(@var{m}-1)}th elements match @var{qpattern1},
432 @var{qpattern2} @dots{} @var{qpatternm}, respectively.
434 Matches if corresponding element of the value being matched is
435 @code{equal} to the specified @var{atom}.
436 @item ,@var{upattern}
437 Matches if the corresponding element of the value being matched
438 matches the specified @var{upattern}.
441 Note that uses of QPatterns can be expressed using only UPatterns, as
442 QPatterns are implemented on top of UPatterns using
443 @code{pcase-defmacro}, described below. However, using QPatterns will
444 in many cases lead to a more readable code.
445 @c FIXME: There should be an example here showing how a 'pcase' that
446 @c uses QPatterns can be rewritten using UPatterns.
450 Here is an example of using @code{pcase} to implement a simple
451 interpreter for a little expression language (note that this example
452 requires lexical binding, @pxref{Lexical Binding}):
455 (defun evaluate (exp env)
457 (`(add ,x ,y) (+ (evaluate x env) (evaluate y env)))
458 (`(call ,fun ,arg) (funcall (evaluate fun env) (evaluate arg env)))
459 (`(fn ,arg ,body) (lambda (val)
460 (evaluate body (cons (cons arg val) env))))
462 ((pred symbolp) (cdr (assq exp env)))
463 (_ (error "Unknown expression %S" exp))))
466 Here @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a
467 three-element list starting with the literal symbol @code{add}, then
468 extracts the second and third elements and binds them to the variables
469 @code{x} and @code{y}. Then it evaluates @code{x} and @code{y} and
470 adds the results. The @code{call} and @code{fn} patterns similarly
471 implement two flavors of function calls. @code{(pred numberp)} is a
472 pattern that simply checks that @code{exp} is a number and if so,
473 evaluates it. @code{(pred symbolp)} matches symbols, and returns
474 their association. Finally, @code{_} is the catch-all pattern that
475 matches anything, so it's suitable for reporting syntax errors.
477 Here are some sample programs in this small language, including their
481 (evaluate '(add 1 2) nil) ;=> 3
482 (evaluate '(add x y) '((x . 1) (y . 2))) ;=> 3
483 (evaluate '(call (fn x (add 1 x)) 2) nil) ;=> 3
484 (evaluate '(sub 1 2) nil) ;=> error
487 Additional UPatterns can be defined using the @code{pcase-defmacro}
490 @defmac pcase-defmacro name args &rest body
491 Define a new kind of UPattern for @code{pcase}. The new UPattern will
492 be invoked as @code{(@var{name} @var{actual-args})}. The @var{body}
493 should describe how to rewrite the UPattern @var{name} into some other
494 UPattern. The rewriting will be the result of evaluating @var{body}
495 in an environment where @var{args} are bound to @var{actual-args}.
498 @node Combining Conditions
499 @section Constructs for Combining Conditions
500 @cindex combining conditions
502 This section describes three constructs that are often used together
503 with @code{if} and @code{cond} to express complicated conditions. The
504 constructs @code{and} and @code{or} can also be used individually as
505 kinds of multiple conditional constructs.
508 This function tests for the falsehood of @var{condition}. It returns
509 @code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
510 The function @code{not} is identical to @code{null}, and we recommend
511 using the name @code{null} if you are testing for an empty list.
514 @defspec and conditions@dots{}
515 The @code{and} special form tests whether all the @var{conditions} are
516 true. It works by evaluating the @var{conditions} one by one in the
519 If any of the @var{conditions} evaluates to @code{nil}, then the result
520 of the @code{and} must be @code{nil} regardless of the remaining
521 @var{conditions}; so @code{and} returns @code{nil} right away, ignoring
522 the remaining @var{conditions}.
524 If all the @var{conditions} turn out non-@code{nil}, then the value of
525 the last of them becomes the value of the @code{and} form. Just
526 @code{(and)}, with no @var{conditions}, returns @code{t}, appropriate
527 because all the @var{conditions} turned out non-@code{nil}. (Think
528 about it; which one did not?)
530 Here is an example. The first condition returns the integer 1, which is
531 not @code{nil}. Similarly, the second condition returns the integer 2,
532 which is not @code{nil}. The third condition is @code{nil}, so the
533 remaining condition is never evaluated.
537 (and (print 1) (print 2) nil (print 3))
544 Here is a more realistic example of using @code{and}:
548 (if (and (consp foo) (eq (car foo) 'x))
549 (message "foo is a list starting with x"))
554 Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
555 @code{nil}, thus avoiding an error.
557 @code{and} expressions can also be written using either @code{if} or
558 @code{cond}. Here's how:
562 (and @var{arg1} @var{arg2} @var{arg3})
564 (if @var{arg1} (if @var{arg2} @var{arg3}))
566 (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
571 @defspec or conditions@dots{}
572 The @code{or} special form tests whether at least one of the
573 @var{conditions} is true. It works by evaluating all the
574 @var{conditions} one by one in the order written.
576 If any of the @var{conditions} evaluates to a non-@code{nil} value, then
577 the result of the @code{or} must be non-@code{nil}; so @code{or} returns
578 right away, ignoring the remaining @var{conditions}. The value it
579 returns is the non-@code{nil} value of the condition just evaluated.
581 If all the @var{conditions} turn out @code{nil}, then the @code{or}
582 expression returns @code{nil}. Just @code{(or)}, with no
583 @var{conditions}, returns @code{nil}, appropriate because all the
584 @var{conditions} turned out @code{nil}. (Think about it; which one
587 For example, this expression tests whether @code{x} is either
588 @code{nil} or the integer zero:
591 (or (eq x nil) (eq x 0))
594 Like the @code{and} construct, @code{or} can be written in terms of
595 @code{cond}. For example:
599 (or @var{arg1} @var{arg2} @var{arg3})
607 You could almost write @code{or} in terms of @code{if}, but not quite:
611 (if @var{arg1} @var{arg1}
612 (if @var{arg2} @var{arg2}
618 This is not completely equivalent because it can evaluate @var{arg1} or
619 @var{arg2} twice. By contrast, @code{(or @var{arg1} @var{arg2}
620 @var{arg3})} never evaluates any argument more than once.
628 Iteration means executing part of a program repetitively. For
629 example, you might want to repeat some computation once for each element
630 of a list, or once for each integer from 0 to @var{n}. You can do this
631 in Emacs Lisp with the special form @code{while}:
633 @defspec while condition forms@dots{}
634 @code{while} first evaluates @var{condition}. If the result is
635 non-@code{nil}, it evaluates @var{forms} in textual order. Then it
636 reevaluates @var{condition}, and if the result is non-@code{nil}, it
637 evaluates @var{forms} again. This process repeats until @var{condition}
638 evaluates to @code{nil}.
640 There is no limit on the number of iterations that may occur. The loop
641 will continue until either @var{condition} evaluates to @code{nil} or
642 until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
644 The value of a @code{while} form is always @code{nil}.
653 (princ (format "Iteration %d." num))
655 @print{} Iteration 0.
656 @print{} Iteration 1.
657 @print{} Iteration 2.
658 @print{} Iteration 3.
663 To write a repeat-until loop, which will execute something on each
664 iteration and then do the end-test, put the body followed by the
665 end-test in a @code{progn} as the first argument of @code{while}, as
672 (not (looking-at "^$"))))
677 This moves forward one line and continues moving by lines until it
678 reaches an empty line. It is peculiar in that the @code{while} has no
679 body, just the end test (which also does the real work of moving point).
682 The @code{dolist} and @code{dotimes} macros provide convenient ways to
683 write two common kinds of loops.
685 @defmac dolist (var list [result]) body@dots{}
686 This construct executes @var{body} once for each element of
687 @var{list}, binding the variable @var{var} locally to hold the current
688 element. Then it returns the value of evaluating @var{result}, or
689 @code{nil} if @var{result} is omitted. For example, here is how you
690 could use @code{dolist} to define the @code{reverse} function:
693 (defun reverse (list)
695 (dolist (elt list value)
696 (setq value (cons elt value)))))
700 @defmac dotimes (var count [result]) body@dots{}
701 This construct executes @var{body} once for each integer from 0
702 (inclusive) to @var{count} (exclusive), binding the variable @var{var}
703 to the integer for the current iteration. Then it returns the value
704 of evaluating @var{result}, or @code{nil} if @var{result} is omitted.
705 Here is an example of using @code{dotimes} to do something 100 times:
709 (insert "I will not obey absurd orders\n"))
717 A @dfn{generator} is a function that produces a potentially-infinite
718 stream of values. Each time the function produces a value, it
719 suspends itself and waits for a caller to request the next value.
721 @defmac iter-defun name args [doc] [declare] [interactive] body@dots{}
722 @code{iter-defun} defines a generator function. A generator function
723 has the same signature as a normal function, but works differently.
724 Instead of executing @var{body} when called, a generator function
725 returns an iterator object. That iterator runs @var{body} to generate
726 values, emitting a value and pausing where @code{iter-yield} or
727 @code{iter-yield-from} appears. When @var{body} returns normally,
728 @code{iter-next} signals @code{iter-end-of-sequence} with @var{body}'s
729 result as its condition data.
731 Any kind of Lisp code is valid inside @var{body}, but
732 @code{iter-yield} and @code{iter-yield-from} cannot appear inside
733 @code{unwind-protect} forms.
737 @defmac iter-lambda args [doc] [interactive] body@dots{}
738 @code{iter-lambda} produces an unnamed generator function that works
739 just like a generator function produced with @code{iter-defun}.
742 @defmac iter-yield value
743 When it appears inside a generator function, @code{iter-yield}
744 indicates that the current iterator should pause and return
745 @var{value} from @code{iter-next}. @code{iter-yield} evaluates to the
746 @code{value} parameter of next call to @code{iter-next}.
749 @defmac iter-yield-from iterator
750 @code{iter-yield-from} yields all the values that @var{iterator}
751 produces and evaluates to the value that @var{iterator}'s generator
752 function returns normally. While it has control, @var{iterator}
753 receives values sent to the iterator using @code{iter-next}.
756 To use a generator function, first call it normally, producing a
757 @dfn{iterator} object. An iterator is a specific instance of a
758 generator. Then use @code{iter-next} to retrieve values from this
759 iterator. When there are no more values to pull from an iterator,
760 @code{iter-next} raises an @code{iter-end-of-sequence} condition with
761 the iterator's final value.
763 It's important to note that generator function bodies only execute
764 inside calls to @code{iter-next}. A call to a function defined with
765 @code{iter-defun} produces an iterator; you must drive this
766 iterator with @code{iter-next} for anything interesting to happen.
767 Each call to a generator function produces a @emph{different}
768 iterator, each with its own state.
770 @defun iter-next iterator value
771 Retrieve the next value from @var{iterator}. If there are no more
772 values to be generated (because @var{iterator}'s generator function
773 returned), @code{iter-next} signals the @code{iter-end-of-sequence}
774 condition; the data value associated with this condition is the value
775 with which @var{iterator}'s generator function returned.
777 @var{value} is sent into the iterator and becomes the value to which
778 @code{iter-yield} evaluates. @var{value} is ignored for the first
779 @code{iter-next} call to a given iterator, since at the start of
780 @var{iterator}'s generator function, the generator function is not
781 evaluating any @code{iter-yield} form.
784 @defun iter-close iterator
785 If @var{iterator} is suspended inside an @code{unwind-protect}'s
786 @code{bodyform} and becomes unreachable, Emacs will eventually run
787 unwind handlers after a garbage collection pass. (Note that
788 @code{iter-yield} is illegal inside an @code{unwind-protect}'s
789 @code{unwindforms}.) To ensure that these handlers are run before
790 then, use @code{iter-close}.
793 Some convenience functions are provided to make working with
796 @defmac iter-do (var iterator) body @dots{}
797 Run @var{body} with @var{var} bound to each value that
798 @var{iterator} produces.
801 The Common Lisp loop facility also contains features for working with
802 iterators. See @xref{Loop Facility,,,cl,Common Lisp Extensions}.
804 The following piece of code demonstrates some important principles of
805 working with iterators.
809 (iter-defun my-iter (x)
810 (iter-yield (1+ (iter-yield (1+ x))))
814 (let* ((iter (my-iter 5))
817 (print (iter-next iter))
819 (print (iter-next iter 8))
820 ;; Prints 1; iter and iter2 have distinct states
821 (print (iter-next iter2 nil))
823 ;; We expect the iter sequence to end now
826 (iter-end-of-sequence
827 ;; Prints -1, which my-iter returned normally
832 @section Nonlocal Exits
833 @cindex nonlocal exits
835 A @dfn{nonlocal exit} is a transfer of control from one point in a
836 program to another remote point. Nonlocal exits can occur in Emacs Lisp
837 as a result of errors; you can also use them under explicit control.
838 Nonlocal exits unbind all variable bindings made by the constructs being
842 * Catch and Throw:: Nonlocal exits for the program's own purposes.
843 * Examples of Catch:: Showing how such nonlocal exits can be written.
844 * Errors:: How errors are signaled and handled.
845 * Cleanups:: Arranging to run a cleanup form if an error happens.
848 @node Catch and Throw
849 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
851 Most control constructs affect only the flow of control within the
852 construct itself. The function @code{throw} is the exception to this
853 rule of normal program execution: it performs a nonlocal exit on
854 request. (There are other exceptions, but they are for error handling
855 only.) @code{throw} is used inside a @code{catch}, and jumps back to
856 that @code{catch}. For example:
873 The @code{throw} form, if executed, transfers control straight back to
874 the corresponding @code{catch}, which returns immediately. The code
875 following the @code{throw} is not executed. The second argument of
876 @code{throw} is used as the return value of the @code{catch}.
878 The function @code{throw} finds the matching @code{catch} based on the
879 first argument: it searches for a @code{catch} whose first argument is
880 @code{eq} to the one specified in the @code{throw}. If there is more
881 than one applicable @code{catch}, the innermost one takes precedence.
882 Thus, in the above example, the @code{throw} specifies @code{foo}, and
883 the @code{catch} in @code{foo-outer} specifies the same symbol, so that
884 @code{catch} is the applicable one (assuming there is no other matching
885 @code{catch} in between).
887 Executing @code{throw} exits all Lisp constructs up to the matching
888 @code{catch}, including function calls. When binding constructs such
889 as @code{let} or function calls are exited in this way, the bindings
890 are unbound, just as they are when these constructs exit normally
891 (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
892 and position saved by @code{save-excursion} (@pxref{Excursions}), and
893 the narrowing status saved by @code{save-restriction}. It also runs
894 any cleanups established with the @code{unwind-protect} special form
895 when it exits that form (@pxref{Cleanups}).
897 The @code{throw} need not appear lexically within the @code{catch}
898 that it jumps to. It can equally well be called from another function
899 called within the @code{catch}. As long as the @code{throw} takes place
900 chronologically after entry to the @code{catch}, and chronologically
901 before exit from it, it has access to that @code{catch}. This is why
902 @code{throw} can be used in commands such as @code{exit-recursive-edit}
903 that throw back to the editor command loop (@pxref{Recursive Editing}).
905 @cindex CL note---only @code{throw} in Emacs
907 @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
908 have several ways of transferring control nonsequentially: @code{return},
909 @code{return-from}, and @code{go}, for example. Emacs Lisp has only
910 @code{throw}. The @file{cl-lib} library provides versions of some of
911 these. @xref{Blocks and Exits,,,cl,Common Lisp Extensions}.
914 @defspec catch tag body@dots{}
915 @cindex tag on run time stack
916 @code{catch} establishes a return point for the @code{throw} function.
917 The return point is distinguished from other such return points by
918 @var{tag}, which may be any Lisp object except @code{nil}. The argument
919 @var{tag} is evaluated normally before the return point is established.
921 With the return point in effect, @code{catch} evaluates the forms of the
922 @var{body} in textual order. If the forms execute normally (without
923 error or nonlocal exit) the value of the last body form is returned from
926 If a @code{throw} is executed during the execution of @var{body},
927 specifying the same value @var{tag}, the @code{catch} form exits
928 immediately; the value it returns is whatever was specified as the
929 second argument of @code{throw}.
932 @defun throw tag value
933 The purpose of @code{throw} is to return from a return point previously
934 established with @code{catch}. The argument @var{tag} is used to choose
935 among the various existing return points; it must be @code{eq} to the value
936 specified in the @code{catch}. If multiple return points match @var{tag},
937 the innermost one is used.
939 The argument @var{value} is used as the value to return from that
943 If no return point is in effect with tag @var{tag}, then a @code{no-catch}
944 error is signaled with data @code{(@var{tag} @var{value})}.
947 @node Examples of Catch
948 @subsection Examples of @code{catch} and @code{throw}
950 One way to use @code{catch} and @code{throw} is to exit from a doubly
951 nested loop. (In most languages, this would be done with a @code{goto}.)
952 Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
964 (throw 'loop (list i j)))
971 If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
972 list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
973 @code{catch} returns normally, and the value is @code{nil}, since that
974 is the result of the @code{while}.
976 Here are two tricky examples, slightly different, showing two
977 return points at once. First, two return points with the same tag,
990 (print (catch2 'hack))
998 Since both return points have tags that match the @code{throw}, it goes to
999 the inner one, the one established in @code{catch2}. Therefore,
1000 @code{catch2} returns normally with value @code{yes}, and this value is
1001 printed. Finally the second body form in the outer @code{catch}, which is
1002 @code{'no}, is evaluated and returned from the outer @code{catch}.
1004 Now let's change the argument given to @code{catch2}:
1009 (print (catch2 'quux))
1016 We still have two return points, but this time only the outer one has
1017 the tag @code{hack}; the inner one has the tag @code{quux} instead.
1018 Therefore, @code{throw} makes the outer @code{catch} return the value
1019 @code{yes}. The function @code{print} is never called, and the
1020 body-form @code{'no} is never evaluated.
1026 When Emacs Lisp attempts to evaluate a form that, for some reason,
1027 cannot be evaluated, it @dfn{signals} an @dfn{error}.
1029 When an error is signaled, Emacs's default reaction is to print an
1030 error message and terminate execution of the current command. This is
1031 the right thing to do in most cases, such as if you type @kbd{C-f} at
1032 the end of the buffer.
1034 In complicated programs, simple termination may not be what you want.
1035 For example, the program may have made temporary changes in data
1036 structures, or created temporary buffers that should be deleted before
1037 the program is finished. In such cases, you would use
1038 @code{unwind-protect} to establish @dfn{cleanup expressions} to be
1039 evaluated in case of error. (@xref{Cleanups}.) Occasionally, you may
1040 wish the program to continue execution despite an error in a subroutine.
1041 In these cases, you would use @code{condition-case} to establish
1042 @dfn{error handlers} to recover control in case of error.
1044 Resist the temptation to use error handling to transfer control from
1045 one part of the program to another; use @code{catch} and @code{throw}
1046 instead. @xref{Catch and Throw}.
1049 * Signaling Errors:: How to report an error.
1050 * Processing of Errors:: What Emacs does when you report an error.
1051 * Handling Errors:: How you can trap errors and continue execution.
1052 * Error Symbols:: How errors are classified for trapping them.
1055 @node Signaling Errors
1056 @subsubsection How to Signal an Error
1057 @cindex signaling errors
1059 @dfn{Signaling} an error means beginning error processing. Error
1060 processing normally aborts all or part of the running program and
1061 returns to a point that is set up to handle the error
1062 (@pxref{Processing of Errors}). Here we describe how to signal an
1065 Most errors are signaled automatically within Lisp primitives
1066 which you call for other purposes, such as if you try to take the
1067 @sc{car} of an integer or move forward a character at the end of the
1068 buffer. You can also signal errors explicitly with the functions
1069 @code{error} and @code{signal}.
1071 Quitting, which happens when the user types @kbd{C-g}, is not
1072 considered an error, but it is handled almost like an error.
1075 Every error specifies an error message, one way or another. The
1076 message should state what is wrong (``File does not exist''), not how
1077 things ought to be (``File must exist''). The convention in Emacs
1078 Lisp is that error messages should start with a capital letter, but
1079 should not end with any sort of punctuation.
1081 @defun error format-string &rest args
1082 This function signals an error with an error message constructed by
1083 applying @code{format-message} (@pxref{Formatting Strings}) to
1084 @var{format-string} and @var{args}.
1086 These examples show typical uses of @code{error}:
1090 (error "That is an error -- try something else")
1091 @error{} That is an error -- try something else
1095 (error "Invalid name `%s'" "A%%B")
1096 @error{} Invalid name ‘A%%B’
1100 @code{error} works by calling @code{signal} with two arguments: the
1101 error symbol @code{error}, and a list containing the string returned by
1102 @code{format-message}.
1104 Typically grave accent and apostrophe in the format translate to
1105 matching curved quotes, e.g., @t{"Missing `%s'"} might result in
1106 @t{"Missing ‘foo’"}. @xref{Text Quoting Style}, for how to influence
1107 or inhibit this translation.
1109 @strong{Warning:} If you want to use your own string as an error message
1110 verbatim, don't just write @code{(error @var{string})}. If @var{string}
1111 @var{string} contains @samp{%}, @samp{`}, or @samp{'} it may be
1112 reformatted, with undesirable results. Instead, use @code{(error "%s"
1116 @defun signal error-symbol data
1117 @anchor{Definition of signal}
1118 This function signals an error named by @var{error-symbol}. The
1119 argument @var{data} is a list of additional Lisp objects relevant to
1120 the circumstances of the error.
1122 The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
1123 defined with @code{define-error}. This is how Emacs Lisp classifies different
1124 sorts of errors. @xref{Error Symbols}, for a description of error symbols,
1125 error conditions and condition names.
1127 If the error is not handled, the two arguments are used in printing
1128 the error message. Normally, this error message is provided by the
1129 @code{error-message} property of @var{error-symbol}. If @var{data} is
1130 non-@code{nil}, this is followed by a colon and a comma separated list
1131 of the unevaluated elements of @var{data}. For @code{error}, the
1132 error message is the @sc{car} of @var{data} (that must be a string).
1133 Subcategories of @code{file-error} are handled specially.
1135 The number and significance of the objects in @var{data} depends on
1136 @var{error-symbol}. For example, with a @code{wrong-type-argument} error,
1137 there should be two objects in the list: a predicate that describes the type
1138 that was expected, and the object that failed to fit that type.
1140 Both @var{error-symbol} and @var{data} are available to any error
1141 handlers that handle the error: @code{condition-case} binds a local
1142 variable to a list of the form @code{(@var{error-symbol} .@:
1143 @var{data})} (@pxref{Handling Errors}).
1145 The function @code{signal} never returns.
1146 @c (though in older Emacs versions it sometimes could).
1150 (signal 'wrong-number-of-arguments '(x y))
1151 @error{} Wrong number of arguments: x, y
1155 (signal 'no-such-error '("My unknown error condition"))
1156 @error{} peculiar error: "My unknown error condition"
1161 @cindex user errors, signaling
1162 @defun user-error format-string &rest args
1163 This function behaves exactly like @code{error}, except that it uses
1164 the error symbol @code{user-error} rather than @code{error}. As the
1165 name suggests, this is intended to report errors on the part of the
1166 user, rather than errors in the code itself. For example,
1167 if you try to use the command @code{Info-history-back} (@kbd{l}) to
1168 move back beyond the start of your Info browsing history, Emacs
1169 signals a @code{user-error}. Such errors do not cause entry to the
1170 debugger, even when @code{debug-on-error} is non-@code{nil}.
1171 @xref{Error Debugging}.
1174 @cindex CL note---no continuable errors
1176 @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
1177 concept of continuable errors.
1180 @node Processing of Errors
1181 @subsubsection How Emacs Processes Errors
1182 @cindex processing of errors
1184 When an error is signaled, @code{signal} searches for an active
1185 @dfn{handler} for the error. A handler is a sequence of Lisp
1186 expressions designated to be executed if an error happens in part of the
1187 Lisp program. If the error has an applicable handler, the handler is
1188 executed, and control resumes following the handler. The handler
1189 executes in the environment of the @code{condition-case} that
1190 established it; all functions called within that @code{condition-case}
1191 have already been exited, and the handler cannot return to them.
1193 If there is no applicable handler for the error, it terminates the
1194 current command and returns control to the editor command loop. (The
1195 command loop has an implicit handler for all kinds of errors.) The
1196 command loop's handler uses the error symbol and associated data to
1197 print an error message. You can use the variable
1198 @code{command-error-function} to control how this is done:
1200 @defvar command-error-function
1201 This variable, if non-@code{nil}, specifies a function to use to
1202 handle errors that return control to the Emacs command loop. The
1203 function should take three arguments: @var{data}, a list of the same
1204 form that @code{condition-case} would bind to its variable;
1205 @var{context}, a string describing the situation in which the error
1206 occurred, or (more often) @code{nil}; and @var{caller}, the Lisp
1207 function which called the primitive that signaled the error.
1210 @cindex @code{debug-on-error} use
1211 An error that has no explicit handler may call the Lisp debugger. The
1212 debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
1213 Debugging}) is non-@code{nil}. Unlike error handlers, the debugger runs
1214 in the environment of the error, so that you can examine values of
1215 variables precisely as they were at the time of the error.
1217 @node Handling Errors
1218 @subsubsection Writing Code to Handle Errors
1219 @cindex error handler
1220 @cindex handling errors
1222 The usual effect of signaling an error is to terminate the command
1223 that is running and return immediately to the Emacs editor command loop.
1224 You can arrange to trap errors occurring in a part of your program by
1225 establishing an error handler, with the special form
1226 @code{condition-case}. A simple example looks like this:
1231 (delete-file filename)
1237 This deletes the file named @var{filename}, catching any error and
1238 returning @code{nil} if an error occurs. (You can use the macro
1239 @code{ignore-errors} for a simple case like this; see below.)
1241 The @code{condition-case} construct is often used to trap errors that
1242 are predictable, such as failure to open a file in a call to
1243 @code{insert-file-contents}. It is also used to trap errors that are
1244 totally unpredictable, such as when the program evaluates an expression
1247 The second argument of @code{condition-case} is called the
1248 @dfn{protected form}. (In the example above, the protected form is a
1249 call to @code{delete-file}.) The error handlers go into effect when
1250 this form begins execution and are deactivated when this form returns.
1251 They remain in effect for all the intervening time. In particular, they
1252 are in effect during the execution of functions called by this form, in
1253 their subroutines, and so on. This is a good thing, since, strictly
1254 speaking, errors can be signaled only by Lisp primitives (including
1255 @code{signal} and @code{error}) called by the protected form, not by the
1256 protected form itself.
1258 The arguments after the protected form are handlers. Each handler
1259 lists one or more @dfn{condition names} (which are symbols) to specify
1260 which errors it will handle. The error symbol specified when an error
1261 is signaled also defines a list of condition names. A handler applies
1262 to an error if they have any condition names in common. In the example
1263 above, there is one handler, and it specifies one condition name,
1264 @code{error}, which covers all errors.
1266 The search for an applicable handler checks all the established handlers
1267 starting with the most recently established one. Thus, if two nested
1268 @code{condition-case} forms offer to handle the same error, the inner of
1269 the two gets to handle it.
1271 If an error is handled by some @code{condition-case} form, this
1272 ordinarily prevents the debugger from being run, even if
1273 @code{debug-on-error} says this error should invoke the debugger.
1275 If you want to be able to debug errors that are caught by a
1276 @code{condition-case}, set the variable @code{debug-on-signal} to a
1277 non-@code{nil} value. You can also specify that a particular handler
1278 should let the debugger run first, by writing @code{debug} among the
1279 conditions, like this:
1284 (delete-file filename)
1285 ((debug error) nil))
1290 The effect of @code{debug} here is only to prevent
1291 @code{condition-case} from suppressing the call to the debugger. Any
1292 given error will invoke the debugger only if @code{debug-on-error} and
1293 the other usual filtering mechanisms say it should. @xref{Error Debugging}.
1295 @defmac condition-case-unless-debug var protected-form handlers@dots{}
1296 The macro @code{condition-case-unless-debug} provides another way to
1297 handle debugging of such forms. It behaves exactly like
1298 @code{condition-case}, unless the variable @code{debug-on-error} is
1299 non-@code{nil}, in which case it does not handle any errors at all.
1302 Once Emacs decides that a certain handler handles the error, it
1303 returns control to that handler. To do so, Emacs unbinds all variable
1304 bindings made by binding constructs that are being exited, and
1305 executes the cleanups of all @code{unwind-protect} forms that are
1306 being exited. Once control arrives at the handler, the body of the
1307 handler executes normally.
1309 After execution of the handler body, execution returns from the
1310 @code{condition-case} form. Because the protected form is exited
1311 completely before execution of the handler, the handler cannot resume
1312 execution at the point of the error, nor can it examine variable
1313 bindings that were made within the protected form. All it can do is
1314 clean up and proceed.
1316 Error signaling and handling have some resemblance to @code{throw} and
1317 @code{catch} (@pxref{Catch and Throw}), but they are entirely separate
1318 facilities. An error cannot be caught by a @code{catch}, and a
1319 @code{throw} cannot be handled by an error handler (though using
1320 @code{throw} when there is no suitable @code{catch} signals an error
1321 that can be handled).
1323 @defspec condition-case var protected-form handlers@dots{}
1324 This special form establishes the error handlers @var{handlers} around
1325 the execution of @var{protected-form}. If @var{protected-form} executes
1326 without error, the value it returns becomes the value of the
1327 @code{condition-case} form; in this case, the @code{condition-case} has
1328 no effect. The @code{condition-case} form makes a difference when an
1329 error occurs during @var{protected-form}.
1331 Each of the @var{handlers} is a list of the form @code{(@var{conditions}
1332 @var{body}@dots{})}. Here @var{conditions} is an error condition name
1333 to be handled, or a list of condition names (which can include @code{debug}
1334 to allow the debugger to run before the handler); @var{body} is one or more
1335 Lisp expressions to be executed when this handler handles an error.
1336 Here are examples of handlers:
1342 (arith-error (message "Division by zero"))
1344 ((arith-error file-error)
1346 "Either division by zero or failure to open a file"))
1350 Each error that occurs has an @dfn{error symbol} that describes what
1351 kind of error it is, and which describes also a list of condition names
1352 (@pxref{Error Symbols}). Emacs
1353 searches all the active @code{condition-case} forms for a handler that
1354 specifies one or more of these condition names; the innermost matching
1355 @code{condition-case} handles the error. Within this
1356 @code{condition-case}, the first applicable handler handles the error.
1358 After executing the body of the handler, the @code{condition-case}
1359 returns normally, using the value of the last form in the handler body
1360 as the overall value.
1362 @cindex error description
1363 The argument @var{var} is a variable. @code{condition-case} does not
1364 bind this variable when executing the @var{protected-form}, only when it
1365 handles an error. At that time, it binds @var{var} locally to an
1366 @dfn{error description}, which is a list giving the particulars of the
1367 error. The error description has the form @code{(@var{error-symbol}
1368 . @var{data})}. The handler can refer to this list to decide what to
1369 do. For example, if the error is for failure opening a file, the file
1370 name is the second element of @var{data}---the third element of the
1373 If @var{var} is @code{nil}, that means no variable is bound. Then the
1374 error symbol and associated data are not available to the handler.
1376 @cindex rethrow a signal
1377 Sometimes it is necessary to re-throw a signal caught by
1378 @code{condition-case}, for some outer-level handler to catch. Here's
1382 (signal (car err) (cdr err))
1386 where @code{err} is the error description variable, the first argument
1387 to @code{condition-case} whose error condition you want to re-throw.
1388 @xref{Definition of signal}.
1391 @defun error-message-string error-descriptor
1392 This function returns the error message string for a given error
1393 descriptor. It is useful if you want to handle an error by printing the
1394 usual error message for that error. @xref{Definition of signal}.
1397 @cindex @code{arith-error} example
1398 Here is an example of using @code{condition-case} to handle the error
1399 that results from dividing by zero. The handler displays the error
1400 message (but without a beep), then returns a very large number.
1404 (defun safe-divide (dividend divisor)
1406 ;; @r{Protected form.}
1407 (/ dividend divisor)
1411 (arith-error ; @r{Condition.}
1412 ;; @r{Display the usual message for this error.}
1413 (message "%s" (error-message-string err))
1415 @result{} safe-divide
1420 @print{} Arithmetic error: (arith-error)
1426 The handler specifies condition name @code{arith-error} so that it
1427 will handle only division-by-zero errors. Other kinds of errors will
1428 not be handled (by this @code{condition-case}). Thus:
1433 @error{} Wrong type argument: number-or-marker-p, nil
1437 Here is a @code{condition-case} that catches all kinds of errors,
1438 including those from @code{error}:
1450 ;; @r{This is a call to the function @code{error}.}
1451 (error "Rats! The variable %s was %s, not 35" 'baz baz))
1452 ;; @r{This is the handler; it is not a form.}
1453 (error (princ (format "The error was: %s" err))
1455 @print{} The error was: (error "Rats! The variable baz was 34, not 35")
1460 @defmac ignore-errors body@dots{}
1461 This construct executes @var{body}, ignoring any errors that occur
1462 during its execution. If the execution is without error,
1463 @code{ignore-errors} returns the value of the last form in @var{body};
1464 otherwise, it returns @code{nil}.
1466 Here's the example at the beginning of this subsection rewritten using
1467 @code{ignore-errors}:
1472 (delete-file filename))
1477 @defmac with-demoted-errors format body@dots{}
1478 This macro is like a milder version of @code{ignore-errors}. Rather
1479 than suppressing errors altogether, it converts them into messages.
1480 It uses the string @var{format} to format the message.
1481 @var{format} should contain a single @samp{%}-sequence; e.g.,
1482 @code{"Error: %S"}. Use @code{with-demoted-errors} around code
1483 that is not expected to signal errors, but
1484 should be robust if one does occur. Note that this macro uses
1485 @code{condition-case-unless-debug} rather than @code{condition-case}.
1489 @subsubsection Error Symbols and Condition Names
1490 @cindex error symbol
1492 @cindex condition name
1493 @cindex user-defined error
1494 @kindex error-conditions
1495 @kindex define-error
1497 When you signal an error, you specify an @dfn{error symbol} to specify
1498 the kind of error you have in mind. Each error has one and only one
1499 error symbol to categorize it. This is the finest classification of
1500 errors defined by the Emacs Lisp language.
1502 These narrow classifications are grouped into a hierarchy of wider
1503 classes called @dfn{error conditions}, identified by @dfn{condition
1504 names}. The narrowest such classes belong to the error symbols
1505 themselves: each error symbol is also a condition name. There are also
1506 condition names for more extensive classes, up to the condition name
1507 @code{error} which takes in all kinds of errors (but not @code{quit}).
1508 Thus, each error has one or more condition names: @code{error}, the
1509 error symbol if that is distinct from @code{error}, and perhaps some
1510 intermediate classifications.
1512 @defun define-error name message &optional parent
1513 In order for a symbol to be an error symbol, it must be defined with
1514 @code{define-error} which takes a parent condition (defaults to @code{error}).
1515 This parent defines the conditions that this kind of error belongs to.
1516 The transitive set of parents always includes the error symbol itself, and the
1517 symbol @code{error}. Because quitting is not considered an error, the set of
1518 parents of @code{quit} is just @code{(quit)}.
1521 @cindex peculiar error
1522 In addition to its parents, the error symbol has a @var{message} which
1523 is a string to be printed when that error is signaled but not handled. If that
1524 message is not valid, the error message @samp{peculiar error} is used.
1525 @xref{Definition of signal}.
1527 Internally, the set of parents is stored in the @code{error-conditions}
1528 property of the error symbol and the message is stored in the
1529 @code{error-message} property of the error symbol.
1531 Here is how we define a new error symbol, @code{new-error}:
1535 (define-error 'new-error "A new error" 'my-own-errors)
1540 This error has several condition names: @code{new-error}, the narrowest
1541 classification; @code{my-own-errors}, which we imagine is a wider
1542 classification; and all the conditions of @code{my-own-errors} which should
1543 include @code{error}, which is the widest of all.
1545 The error string should start with a capital letter but it should
1546 not end with a period. This is for consistency with the rest of Emacs.
1548 Naturally, Emacs will never signal @code{new-error} on its own; only
1549 an explicit call to @code{signal} (@pxref{Definition of signal}) in
1550 your code can do this:
1554 (signal 'new-error '(x y))
1555 @error{} A new error: x, y
1559 This error can be handled through any of its condition names.
1560 This example handles @code{new-error} and any other errors in the class
1561 @code{my-own-errors}:
1567 (my-own-errors nil))
1571 The significant way that errors are classified is by their condition
1572 names---the names used to match errors with handlers. An error symbol
1573 serves only as a convenient way to specify the intended error message
1574 and list of condition names. It would be cumbersome to give
1575 @code{signal} a list of condition names rather than one error symbol.
1577 By contrast, using only error symbols without condition names would
1578 seriously decrease the power of @code{condition-case}. Condition names
1579 make it possible to categorize errors at various levels of generality
1580 when you write an error handler. Using error symbols alone would
1581 eliminate all but the narrowest level of classification.
1583 @xref{Standard Errors}, for a list of the main error symbols
1584 and their conditions.
1587 @subsection Cleaning Up from Nonlocal Exits
1588 @cindex nonlocal exits, cleaning up
1590 The @code{unwind-protect} construct is essential whenever you
1591 temporarily put a data structure in an inconsistent state; it permits
1592 you to make the data consistent again in the event of an error or
1593 throw. (Another more specific cleanup construct that is used only for
1594 changes in buffer contents is the atomic change group; @ref{Atomic
1597 @defspec unwind-protect body-form cleanup-forms@dots{}
1598 @cindex cleanup forms
1599 @cindex protected forms
1600 @cindex error cleanup
1602 @code{unwind-protect} executes @var{body-form} with a guarantee that
1603 the @var{cleanup-forms} will be evaluated if control leaves
1604 @var{body-form}, no matter how that happens. @var{body-form} may
1605 complete normally, or execute a @code{throw} out of the
1606 @code{unwind-protect}, or cause an error; in all cases, the
1607 @var{cleanup-forms} will be evaluated.
1609 If @var{body-form} finishes normally, @code{unwind-protect} returns the
1610 value of @var{body-form}, after it evaluates the @var{cleanup-forms}.
1611 If @var{body-form} does not finish, @code{unwind-protect} does not
1612 return any value in the normal sense.
1614 Only @var{body-form} is protected by the @code{unwind-protect}. If any
1615 of the @var{cleanup-forms} themselves exits nonlocally (via a
1616 @code{throw} or an error), @code{unwind-protect} is @emph{not}
1617 guaranteed to evaluate the rest of them. If the failure of one of the
1618 @var{cleanup-forms} has the potential to cause trouble, then protect
1619 it with another @code{unwind-protect} around that form.
1621 The number of currently active @code{unwind-protect} forms counts,
1622 together with the number of local variable bindings, against the limit
1623 @code{max-specpdl-size} (@pxref{Definition of max-specpdl-size,, Local
1627 For example, here we make an invisible buffer for temporary use, and
1628 make sure to kill it before finishing:
1632 (let ((buffer (get-buffer-create " *temp*")))
1633 (with-current-buffer buffer
1636 (kill-buffer buffer))))
1641 You might think that we could just as well write @code{(kill-buffer
1642 (current-buffer))} and dispense with the variable @code{buffer}.
1643 However, the way shown above is safer, if @var{body-form} happens to
1644 get an error after switching to a different buffer! (Alternatively,
1645 you could write a @code{save-current-buffer} around @var{body-form},
1646 to ensure that the temporary buffer becomes current again in time to
1649 Emacs includes a standard macro called @code{with-temp-buffer} which
1650 expands into more or less the code shown above (@pxref{Definition of
1651 with-temp-buffer,, Current Buffer}). Several of the macros defined in
1652 this manual use @code{unwind-protect} in this way.
1655 Here is an actual example derived from an FTP package. It creates a
1656 process (@pxref{Processes}) to try to establish a connection to a remote
1657 machine. As the function @code{ftp-login} is highly susceptible to
1658 numerous problems that the writer of the function cannot anticipate, it
1659 is protected with a form that guarantees deletion of the process in the
1660 event of failure. Otherwise, Emacs might fill up with useless
1668 (setq process (ftp-setup-buffer host file))
1669 (if (setq win (ftp-login process host user password))
1670 (message "Logged in")
1671 (error "Ftp login failed")))
1672 (or win (and process (delete-process process)))))
1676 This example has a small bug: if the user types @kbd{C-g} to
1677 quit, and the quit happens immediately after the function
1678 @code{ftp-setup-buffer} returns but before the variable @code{process} is
1679 set, the process will not be killed. There is no easy way to fix this bug,
1680 but at least it is very unlikely.