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-2016 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.
808 (iter-defun my-iter (x)
809 (iter-yield (1+ (iter-yield (1+ x))))
813 (let* ((iter (my-iter 5))
816 (print (iter-next iter))
818 (print (iter-next iter 8))
819 ;; Prints 1; iter and iter2 have distinct states
820 (print (iter-next iter2 nil))
822 ;; We expect the iter sequence to end now
825 (iter-end-of-sequence
826 ;; Prints -1, which my-iter returned normally
831 @section Nonlocal Exits
832 @cindex nonlocal exits
834 A @dfn{nonlocal exit} is a transfer of control from one point in a
835 program to another remote point. Nonlocal exits can occur in Emacs Lisp
836 as a result of errors; you can also use them under explicit control.
837 Nonlocal exits unbind all variable bindings made by the constructs being
841 * Catch and Throw:: Nonlocal exits for the program's own purposes.
842 * Examples of Catch:: Showing how such nonlocal exits can be written.
843 * Errors:: How errors are signaled and handled.
844 * Cleanups:: Arranging to run a cleanup form if an error happens.
847 @node Catch and Throw
848 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
850 Most control constructs affect only the flow of control within the
851 construct itself. The function @code{throw} is the exception to this
852 rule of normal program execution: it performs a nonlocal exit on
853 request. (There are other exceptions, but they are for error handling
854 only.) @code{throw} is used inside a @code{catch}, and jumps back to
855 that @code{catch}. For example:
872 The @code{throw} form, if executed, transfers control straight back to
873 the corresponding @code{catch}, which returns immediately. The code
874 following the @code{throw} is not executed. The second argument of
875 @code{throw} is used as the return value of the @code{catch}.
877 The function @code{throw} finds the matching @code{catch} based on the
878 first argument: it searches for a @code{catch} whose first argument is
879 @code{eq} to the one specified in the @code{throw}. If there is more
880 than one applicable @code{catch}, the innermost one takes precedence.
881 Thus, in the above example, the @code{throw} specifies @code{foo}, and
882 the @code{catch} in @code{foo-outer} specifies the same symbol, so that
883 @code{catch} is the applicable one (assuming there is no other matching
884 @code{catch} in between).
886 Executing @code{throw} exits all Lisp constructs up to the matching
887 @code{catch}, including function calls. When binding constructs such
888 as @code{let} or function calls are exited in this way, the bindings
889 are unbound, just as they are when these constructs exit normally
890 (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
891 and position saved by @code{save-excursion} (@pxref{Excursions}), and
892 the narrowing status saved by @code{save-restriction}. It also runs
893 any cleanups established with the @code{unwind-protect} special form
894 when it exits that form (@pxref{Cleanups}).
896 The @code{throw} need not appear lexically within the @code{catch}
897 that it jumps to. It can equally well be called from another function
898 called within the @code{catch}. As long as the @code{throw} takes place
899 chronologically after entry to the @code{catch}, and chronologically
900 before exit from it, it has access to that @code{catch}. This is why
901 @code{throw} can be used in commands such as @code{exit-recursive-edit}
902 that throw back to the editor command loop (@pxref{Recursive Editing}).
904 @cindex CL note---only @code{throw} in Emacs
906 @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
907 have several ways of transferring control nonsequentially: @code{return},
908 @code{return-from}, and @code{go}, for example. Emacs Lisp has only
909 @code{throw}. The @file{cl-lib} library provides versions of some of
910 these. @xref{Blocks and Exits,,,cl,Common Lisp Extensions}.
913 @defspec catch tag body@dots{}
914 @cindex tag on run time stack
915 @code{catch} establishes a return point for the @code{throw} function.
916 The return point is distinguished from other such return points by
917 @var{tag}, which may be any Lisp object except @code{nil}. The argument
918 @var{tag} is evaluated normally before the return point is established.
920 With the return point in effect, @code{catch} evaluates the forms of the
921 @var{body} in textual order. If the forms execute normally (without
922 error or nonlocal exit) the value of the last body form is returned from
925 If a @code{throw} is executed during the execution of @var{body},
926 specifying the same value @var{tag}, the @code{catch} form exits
927 immediately; the value it returns is whatever was specified as the
928 second argument of @code{throw}.
931 @defun throw tag value
932 The purpose of @code{throw} is to return from a return point previously
933 established with @code{catch}. The argument @var{tag} is used to choose
934 among the various existing return points; it must be @code{eq} to the value
935 specified in the @code{catch}. If multiple return points match @var{tag},
936 the innermost one is used.
938 The argument @var{value} is used as the value to return from that
942 If no return point is in effect with tag @var{tag}, then a @code{no-catch}
943 error is signaled with data @code{(@var{tag} @var{value})}.
946 @node Examples of Catch
947 @subsection Examples of @code{catch} and @code{throw}
949 One way to use @code{catch} and @code{throw} is to exit from a doubly
950 nested loop. (In most languages, this would be done with a @code{goto}.)
951 Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
963 (throw 'loop (list i j)))
970 If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
971 list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
972 @code{catch} returns normally, and the value is @code{nil}, since that
973 is the result of the @code{while}.
975 Here are two tricky examples, slightly different, showing two
976 return points at once. First, two return points with the same tag,
989 (print (catch2 'hack))
997 Since both return points have tags that match the @code{throw}, it goes to
998 the inner one, the one established in @code{catch2}. Therefore,
999 @code{catch2} returns normally with value @code{yes}, and this value is
1000 printed. Finally the second body form in the outer @code{catch}, which is
1001 @code{'no}, is evaluated and returned from the outer @code{catch}.
1003 Now let's change the argument given to @code{catch2}:
1008 (print (catch2 'quux))
1015 We still have two return points, but this time only the outer one has
1016 the tag @code{hack}; the inner one has the tag @code{quux} instead.
1017 Therefore, @code{throw} makes the outer @code{catch} return the value
1018 @code{yes}. The function @code{print} is never called, and the
1019 body-form @code{'no} is never evaluated.
1025 When Emacs Lisp attempts to evaluate a form that, for some reason,
1026 cannot be evaluated, it @dfn{signals} an @dfn{error}.
1028 When an error is signaled, Emacs's default reaction is to print an
1029 error message and terminate execution of the current command. This is
1030 the right thing to do in most cases, such as if you type @kbd{C-f} at
1031 the end of the buffer.
1033 In complicated programs, simple termination may not be what you want.
1034 For example, the program may have made temporary changes in data
1035 structures, or created temporary buffers that should be deleted before
1036 the program is finished. In such cases, you would use
1037 @code{unwind-protect} to establish @dfn{cleanup expressions} to be
1038 evaluated in case of error. (@xref{Cleanups}.) Occasionally, you may
1039 wish the program to continue execution despite an error in a subroutine.
1040 In these cases, you would use @code{condition-case} to establish
1041 @dfn{error handlers} to recover control in case of error.
1043 Resist the temptation to use error handling to transfer control from
1044 one part of the program to another; use @code{catch} and @code{throw}
1045 instead. @xref{Catch and Throw}.
1048 * Signaling Errors:: How to report an error.
1049 * Processing of Errors:: What Emacs does when you report an error.
1050 * Handling Errors:: How you can trap errors and continue execution.
1051 * Error Symbols:: How errors are classified for trapping them.
1054 @node Signaling Errors
1055 @subsubsection How to Signal an Error
1056 @cindex signaling errors
1058 @dfn{Signaling} an error means beginning error processing. Error
1059 processing normally aborts all or part of the running program and
1060 returns to a point that is set up to handle the error
1061 (@pxref{Processing of Errors}). Here we describe how to signal an
1064 Most errors are signaled automatically within Lisp primitives
1065 which you call for other purposes, such as if you try to take the
1066 @sc{car} of an integer or move forward a character at the end of the
1067 buffer. You can also signal errors explicitly with the functions
1068 @code{error} and @code{signal}.
1070 Quitting, which happens when the user types @kbd{C-g}, is not
1071 considered an error, but it is handled almost like an error.
1074 Every error specifies an error message, one way or another. The
1075 message should state what is wrong (``File does not exist''), not how
1076 things ought to be (``File must exist''). The convention in Emacs
1077 Lisp is that error messages should start with a capital letter, but
1078 should not end with any sort of punctuation.
1080 @defun error format-string &rest args
1081 This function signals an error with an error message constructed by
1082 applying @code{format-message} (@pxref{Formatting Strings}) to
1083 @var{format-string} and @var{args}.
1085 These examples show typical uses of @code{error}:
1089 (error "That is an error -- try something else")
1090 @error{} That is an error -- try something else
1094 (error "Invalid name `%s'" "A%%B")
1095 @error{} Invalid name ‘A%%B’
1099 @code{error} works by calling @code{signal} with two arguments: the
1100 error symbol @code{error}, and a list containing the string returned by
1101 @code{format-message}.
1103 The @code{text-quoting-style} variable controls what quotes are
1104 generated; @xref{Keys in Documentation}. A call using a format like
1105 @t{"Missing `%s'"} with grave accents and apostrophes typically
1106 generates a message like @t{"Missing ‘foo’"} with matching curved
1107 quotes. In contrast, a call using a format like @t{"Missing '%s'"}
1108 with only apostrophes typically generates a message like @t{"Missing
1109 ’foo’"} with only closing curved quotes, an unusual style in English.
1111 @strong{Warning:} If you want to use your own string as an error message
1112 verbatim, don't just write @code{(error @var{string})}. If @var{string}
1113 @var{string} contains @samp{%}, @samp{`}, or @samp{'} it may be
1114 reformatted, with undesirable results. Instead, use @code{(error "%s"
1118 @defun signal error-symbol data
1119 @anchor{Definition of signal}
1120 This function signals an error named by @var{error-symbol}. The
1121 argument @var{data} is a list of additional Lisp objects relevant to
1122 the circumstances of the error.
1124 The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
1125 defined with @code{define-error}. This is how Emacs Lisp classifies different
1126 sorts of errors. @xref{Error Symbols}, for a description of error symbols,
1127 error conditions and condition names.
1129 If the error is not handled, the two arguments are used in printing
1130 the error message. Normally, this error message is provided by the
1131 @code{error-message} property of @var{error-symbol}. If @var{data} is
1132 non-@code{nil}, this is followed by a colon and a comma separated list
1133 of the unevaluated elements of @var{data}. For @code{error}, the
1134 error message is the @sc{car} of @var{data} (that must be a string).
1135 Subcategories of @code{file-error} are handled specially.
1137 The number and significance of the objects in @var{data} depends on
1138 @var{error-symbol}. For example, with a @code{wrong-type-argument} error,
1139 there should be two objects in the list: a predicate that describes the type
1140 that was expected, and the object that failed to fit that type.
1142 Both @var{error-symbol} and @var{data} are available to any error
1143 handlers that handle the error: @code{condition-case} binds a local
1144 variable to a list of the form @code{(@var{error-symbol} .@:
1145 @var{data})} (@pxref{Handling Errors}).
1147 The function @code{signal} never returns.
1148 @c (though in older Emacs versions it sometimes could).
1152 (signal 'wrong-number-of-arguments '(x y))
1153 @error{} Wrong number of arguments: x, y
1157 (signal 'no-such-error '("My unknown error condition"))
1158 @error{} peculiar error: "My unknown error condition"
1163 @cindex user errors, signaling
1164 @defun user-error format-string &rest args
1165 This function behaves exactly like @code{error}, except that it uses
1166 the error symbol @code{user-error} rather than @code{error}. As the
1167 name suggests, this is intended to report errors on the part of the
1168 user, rather than errors in the code itself. For example,
1169 if you try to use the command @code{Info-history-back} (@kbd{l}) to
1170 move back beyond the start of your Info browsing history, Emacs
1171 signals a @code{user-error}. Such errors do not cause entry to the
1172 debugger, even when @code{debug-on-error} is non-@code{nil}.
1173 @xref{Error Debugging}.
1176 @cindex CL note---no continuable errors
1178 @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
1179 concept of continuable errors.
1182 @node Processing of Errors
1183 @subsubsection How Emacs Processes Errors
1184 @cindex processing of errors
1186 When an error is signaled, @code{signal} searches for an active
1187 @dfn{handler} for the error. A handler is a sequence of Lisp
1188 expressions designated to be executed if an error happens in part of the
1189 Lisp program. If the error has an applicable handler, the handler is
1190 executed, and control resumes following the handler. The handler
1191 executes in the environment of the @code{condition-case} that
1192 established it; all functions called within that @code{condition-case}
1193 have already been exited, and the handler cannot return to them.
1195 If there is no applicable handler for the error, it terminates the
1196 current command and returns control to the editor command loop. (The
1197 command loop has an implicit handler for all kinds of errors.) The
1198 command loop's handler uses the error symbol and associated data to
1199 print an error message. You can use the variable
1200 @code{command-error-function} to control how this is done:
1202 @defvar command-error-function
1203 This variable, if non-@code{nil}, specifies a function to use to
1204 handle errors that return control to the Emacs command loop. The
1205 function should take three arguments: @var{data}, a list of the same
1206 form that @code{condition-case} would bind to its variable;
1207 @var{context}, a string describing the situation in which the error
1208 occurred, or (more often) @code{nil}; and @var{caller}, the Lisp
1209 function which called the primitive that signaled the error.
1212 @cindex @code{debug-on-error} use
1213 An error that has no explicit handler may call the Lisp debugger. The
1214 debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
1215 Debugging}) is non-@code{nil}. Unlike error handlers, the debugger runs
1216 in the environment of the error, so that you can examine values of
1217 variables precisely as they were at the time of the error.
1219 @node Handling Errors
1220 @subsubsection Writing Code to Handle Errors
1221 @cindex error handler
1222 @cindex handling errors
1224 The usual effect of signaling an error is to terminate the command
1225 that is running and return immediately to the Emacs editor command loop.
1226 You can arrange to trap errors occurring in a part of your program by
1227 establishing an error handler, with the special form
1228 @code{condition-case}. A simple example looks like this:
1233 (delete-file filename)
1239 This deletes the file named @var{filename}, catching any error and
1240 returning @code{nil} if an error occurs. (You can use the macro
1241 @code{ignore-errors} for a simple case like this; see below.)
1243 The @code{condition-case} construct is often used to trap errors that
1244 are predictable, such as failure to open a file in a call to
1245 @code{insert-file-contents}. It is also used to trap errors that are
1246 totally unpredictable, such as when the program evaluates an expression
1249 The second argument of @code{condition-case} is called the
1250 @dfn{protected form}. (In the example above, the protected form is a
1251 call to @code{delete-file}.) The error handlers go into effect when
1252 this form begins execution and are deactivated when this form returns.
1253 They remain in effect for all the intervening time. In particular, they
1254 are in effect during the execution of functions called by this form, in
1255 their subroutines, and so on. This is a good thing, since, strictly
1256 speaking, errors can be signaled only by Lisp primitives (including
1257 @code{signal} and @code{error}) called by the protected form, not by the
1258 protected form itself.
1260 The arguments after the protected form are handlers. Each handler
1261 lists one or more @dfn{condition names} (which are symbols) to specify
1262 which errors it will handle. The error symbol specified when an error
1263 is signaled also defines a list of condition names. A handler applies
1264 to an error if they have any condition names in common. In the example
1265 above, there is one handler, and it specifies one condition name,
1266 @code{error}, which covers all errors.
1268 The search for an applicable handler checks all the established handlers
1269 starting with the most recently established one. Thus, if two nested
1270 @code{condition-case} forms offer to handle the same error, the inner of
1271 the two gets to handle it.
1273 If an error is handled by some @code{condition-case} form, this
1274 ordinarily prevents the debugger from being run, even if
1275 @code{debug-on-error} says this error should invoke the debugger.
1277 If you want to be able to debug errors that are caught by a
1278 @code{condition-case}, set the variable @code{debug-on-signal} to a
1279 non-@code{nil} value. You can also specify that a particular handler
1280 should let the debugger run first, by writing @code{debug} among the
1281 conditions, like this:
1286 (delete-file filename)
1287 ((debug error) nil))
1292 The effect of @code{debug} here is only to prevent
1293 @code{condition-case} from suppressing the call to the debugger. Any
1294 given error will invoke the debugger only if @code{debug-on-error} and
1295 the other usual filtering mechanisms say it should. @xref{Error Debugging}.
1297 @defmac condition-case-unless-debug var protected-form handlers@dots{}
1298 The macro @code{condition-case-unless-debug} provides another way to
1299 handle debugging of such forms. It behaves exactly like
1300 @code{condition-case}, unless the variable @code{debug-on-error} is
1301 non-@code{nil}, in which case it does not handle any errors at all.
1304 Once Emacs decides that a certain handler handles the error, it
1305 returns control to that handler. To do so, Emacs unbinds all variable
1306 bindings made by binding constructs that are being exited, and
1307 executes the cleanups of all @code{unwind-protect} forms that are
1308 being exited. Once control arrives at the handler, the body of the
1309 handler executes normally.
1311 After execution of the handler body, execution returns from the
1312 @code{condition-case} form. Because the protected form is exited
1313 completely before execution of the handler, the handler cannot resume
1314 execution at the point of the error, nor can it examine variable
1315 bindings that were made within the protected form. All it can do is
1316 clean up and proceed.
1318 Error signaling and handling have some resemblance to @code{throw} and
1319 @code{catch} (@pxref{Catch and Throw}), but they are entirely separate
1320 facilities. An error cannot be caught by a @code{catch}, and a
1321 @code{throw} cannot be handled by an error handler (though using
1322 @code{throw} when there is no suitable @code{catch} signals an error
1323 that can be handled).
1325 @defspec condition-case var protected-form handlers@dots{}
1326 This special form establishes the error handlers @var{handlers} around
1327 the execution of @var{protected-form}. If @var{protected-form} executes
1328 without error, the value it returns becomes the value of the
1329 @code{condition-case} form; in this case, the @code{condition-case} has
1330 no effect. The @code{condition-case} form makes a difference when an
1331 error occurs during @var{protected-form}.
1333 Each of the @var{handlers} is a list of the form @code{(@var{conditions}
1334 @var{body}@dots{})}. Here @var{conditions} is an error condition name
1335 to be handled, or a list of condition names (which can include @code{debug}
1336 to allow the debugger to run before the handler); @var{body} is one or more
1337 Lisp expressions to be executed when this handler handles an error.
1338 Here are examples of handlers:
1344 (arith-error (message "Division by zero"))
1346 ((arith-error file-error)
1348 "Either division by zero or failure to open a file"))
1352 Each error that occurs has an @dfn{error symbol} that describes what
1353 kind of error it is, and which describes also a list of condition names
1354 (@pxref{Error Symbols}). Emacs
1355 searches all the active @code{condition-case} forms for a handler that
1356 specifies one or more of these condition names; the innermost matching
1357 @code{condition-case} handles the error. Within this
1358 @code{condition-case}, the first applicable handler handles the error.
1360 After executing the body of the handler, the @code{condition-case}
1361 returns normally, using the value of the last form in the handler body
1362 as the overall value.
1364 @cindex error description
1365 The argument @var{var} is a variable. @code{condition-case} does not
1366 bind this variable when executing the @var{protected-form}, only when it
1367 handles an error. At that time, it binds @var{var} locally to an
1368 @dfn{error description}, which is a list giving the particulars of the
1369 error. The error description has the form @code{(@var{error-symbol}
1370 . @var{data})}. The handler can refer to this list to decide what to
1371 do. For example, if the error is for failure opening a file, the file
1372 name is the second element of @var{data}---the third element of the
1375 If @var{var} is @code{nil}, that means no variable is bound. Then the
1376 error symbol and associated data are not available to the handler.
1378 @cindex rethrow a signal
1379 Sometimes it is necessary to re-throw a signal caught by
1380 @code{condition-case}, for some outer-level handler to catch. Here's
1384 (signal (car err) (cdr err))
1388 where @code{err} is the error description variable, the first argument
1389 to @code{condition-case} whose error condition you want to re-throw.
1390 @xref{Definition of signal}.
1393 @defun error-message-string error-descriptor
1394 This function returns the error message string for a given error
1395 descriptor. It is useful if you want to handle an error by printing the
1396 usual error message for that error. @xref{Definition of signal}.
1399 @cindex @code{arith-error} example
1400 Here is an example of using @code{condition-case} to handle the error
1401 that results from dividing by zero. The handler displays the error
1402 message (but without a beep), then returns a very large number.
1406 (defun safe-divide (dividend divisor)
1408 ;; @r{Protected form.}
1409 (/ dividend divisor)
1413 (arith-error ; @r{Condition.}
1414 ;; @r{Display the usual message for this error.}
1415 (message "%s" (error-message-string err))
1417 @result{} safe-divide
1422 @print{} Arithmetic error: (arith-error)
1428 The handler specifies condition name @code{arith-error} so that it
1429 will handle only division-by-zero errors. Other kinds of errors will
1430 not be handled (by this @code{condition-case}). Thus:
1435 @error{} Wrong type argument: number-or-marker-p, nil
1439 Here is a @code{condition-case} that catches all kinds of errors,
1440 including those from @code{error}:
1452 ;; @r{This is a call to the function @code{error}.}
1453 (error "Rats! The variable %s was %s, not 35" 'baz baz))
1454 ;; @r{This is the handler; it is not a form.}
1455 (error (princ (format "The error was: %s" err))
1457 @print{} The error was: (error "Rats! The variable baz was 34, not 35")
1462 @defmac ignore-errors body@dots{}
1463 This construct executes @var{body}, ignoring any errors that occur
1464 during its execution. If the execution is without error,
1465 @code{ignore-errors} returns the value of the last form in @var{body};
1466 otherwise, it returns @code{nil}.
1468 Here's the example at the beginning of this subsection rewritten using
1469 @code{ignore-errors}:
1474 (delete-file filename))
1479 @defmac with-demoted-errors format body@dots{}
1480 This macro is like a milder version of @code{ignore-errors}. Rather
1481 than suppressing errors altogether, it converts them into messages.
1482 It uses the string @var{format} to format the message.
1483 @var{format} should contain a single @samp{%}-sequence; e.g.,
1484 @code{"Error: %S"}. Use @code{with-demoted-errors} around code
1485 that is not expected to signal errors, but
1486 should be robust if one does occur. Note that this macro uses
1487 @code{condition-case-unless-debug} rather than @code{condition-case}.
1491 @subsubsection Error Symbols and Condition Names
1492 @cindex error symbol
1494 @cindex condition name
1495 @cindex user-defined error
1496 @kindex error-conditions
1497 @kindex define-error
1499 When you signal an error, you specify an @dfn{error symbol} to specify
1500 the kind of error you have in mind. Each error has one and only one
1501 error symbol to categorize it. This is the finest classification of
1502 errors defined by the Emacs Lisp language.
1504 These narrow classifications are grouped into a hierarchy of wider
1505 classes called @dfn{error conditions}, identified by @dfn{condition
1506 names}. The narrowest such classes belong to the error symbols
1507 themselves: each error symbol is also a condition name. There are also
1508 condition names for more extensive classes, up to the condition name
1509 @code{error} which takes in all kinds of errors (but not @code{quit}).
1510 Thus, each error has one or more condition names: @code{error}, the
1511 error symbol if that is distinct from @code{error}, and perhaps some
1512 intermediate classifications.
1514 @defun define-error name message &optional parent
1515 In order for a symbol to be an error symbol, it must be defined with
1516 @code{define-error} which takes a parent condition (defaults to @code{error}).
1517 This parent defines the conditions that this kind of error belongs to.
1518 The transitive set of parents always includes the error symbol itself, and the
1519 symbol @code{error}. Because quitting is not considered an error, the set of
1520 parents of @code{quit} is just @code{(quit)}.
1523 @cindex peculiar error
1524 In addition to its parents, the error symbol has a @var{message} which
1525 is a string to be printed when that error is signaled but not handled. If that
1526 message is not valid, the error message @samp{peculiar error} is used.
1527 @xref{Definition of signal}.
1529 Internally, the set of parents is stored in the @code{error-conditions}
1530 property of the error symbol and the message is stored in the
1531 @code{error-message} property of the error symbol.
1533 Here is how we define a new error symbol, @code{new-error}:
1537 (define-error 'new-error "A new error" 'my-own-errors)
1542 This error has several condition names: @code{new-error}, the narrowest
1543 classification; @code{my-own-errors}, which we imagine is a wider
1544 classification; and all the conditions of @code{my-own-errors} which should
1545 include @code{error}, which is the widest of all.
1547 The error string should start with a capital letter but it should
1548 not end with a period. This is for consistency with the rest of Emacs.
1550 Naturally, Emacs will never signal @code{new-error} on its own; only
1551 an explicit call to @code{signal} (@pxref{Definition of signal}) in
1552 your code can do this:
1556 (signal 'new-error '(x y))
1557 @error{} A new error: x, y
1561 This error can be handled through any of its condition names.
1562 This example handles @code{new-error} and any other errors in the class
1563 @code{my-own-errors}:
1569 (my-own-errors nil))
1573 The significant way that errors are classified is by their condition
1574 names---the names used to match errors with handlers. An error symbol
1575 serves only as a convenient way to specify the intended error message
1576 and list of condition names. It would be cumbersome to give
1577 @code{signal} a list of condition names rather than one error symbol.
1579 By contrast, using only error symbols without condition names would
1580 seriously decrease the power of @code{condition-case}. Condition names
1581 make it possible to categorize errors at various levels of generality
1582 when you write an error handler. Using error symbols alone would
1583 eliminate all but the narrowest level of classification.
1585 @xref{Standard Errors}, for a list of the main error symbols
1586 and their conditions.
1589 @subsection Cleaning Up from Nonlocal Exits
1590 @cindex nonlocal exits, cleaning up
1592 The @code{unwind-protect} construct is essential whenever you
1593 temporarily put a data structure in an inconsistent state; it permits
1594 you to make the data consistent again in the event of an error or
1595 throw. (Another more specific cleanup construct that is used only for
1596 changes in buffer contents is the atomic change group; @ref{Atomic
1599 @defspec unwind-protect body-form cleanup-forms@dots{}
1600 @cindex cleanup forms
1601 @cindex protected forms
1602 @cindex error cleanup
1604 @code{unwind-protect} executes @var{body-form} with a guarantee that
1605 the @var{cleanup-forms} will be evaluated if control leaves
1606 @var{body-form}, no matter how that happens. @var{body-form} may
1607 complete normally, or execute a @code{throw} out of the
1608 @code{unwind-protect}, or cause an error; in all cases, the
1609 @var{cleanup-forms} will be evaluated.
1611 If @var{body-form} finishes normally, @code{unwind-protect} returns the
1612 value of @var{body-form}, after it evaluates the @var{cleanup-forms}.
1613 If @var{body-form} does not finish, @code{unwind-protect} does not
1614 return any value in the normal sense.
1616 Only @var{body-form} is protected by the @code{unwind-protect}. If any
1617 of the @var{cleanup-forms} themselves exits nonlocally (via a
1618 @code{throw} or an error), @code{unwind-protect} is @emph{not}
1619 guaranteed to evaluate the rest of them. If the failure of one of the
1620 @var{cleanup-forms} has the potential to cause trouble, then protect
1621 it with another @code{unwind-protect} around that form.
1623 The number of currently active @code{unwind-protect} forms counts,
1624 together with the number of local variable bindings, against the limit
1625 @code{max-specpdl-size} (@pxref{Definition of max-specpdl-size,, Local
1629 For example, here we make an invisible buffer for temporary use, and
1630 make sure to kill it before finishing:
1634 (let ((buffer (get-buffer-create " *temp*")))
1635 (with-current-buffer buffer
1638 (kill-buffer buffer))))
1643 You might think that we could just as well write @code{(kill-buffer
1644 (current-buffer))} and dispense with the variable @code{buffer}.
1645 However, the way shown above is safer, if @var{body-form} happens to
1646 get an error after switching to a different buffer! (Alternatively,
1647 you could write a @code{save-current-buffer} around @var{body-form},
1648 to ensure that the temporary buffer becomes current again in time to
1651 Emacs includes a standard macro called @code{with-temp-buffer} which
1652 expands into more or less the code shown above (@pxref{Definition of
1653 with-temp-buffer,, Current Buffer}). Several of the macros defined in
1654 this manual use @code{unwind-protect} in this way.
1657 Here is an actual example derived from an FTP package. It creates a
1658 process (@pxref{Processes}) to try to establish a connection to a remote
1659 machine. As the function @code{ftp-login} is highly susceptible to
1660 numerous problems that the writer of the function cannot anticipate, it
1661 is protected with a form that guarantees deletion of the process in the
1662 event of failure. Otherwise, Emacs might fill up with useless
1670 (setq process (ftp-setup-buffer host file))
1671 (if (setq win (ftp-login process host user password))
1672 (message "Logged in")
1673 (error "Ftp login failed")))
1674 (or win (and process (delete-process process)))))
1678 This example has a small bug: if the user types @kbd{C-g} to
1679 quit, and the quit happens immediately after the function
1680 @code{ftp-setup-buffer} returns but before the variable @code{process} is
1681 set, the process will not be killed. There is no easy way to fix this bug,
1682 but at least it is very unlikely.