Add seq-set-equal-p to test for set equality
[emacs.git] / doc / lispref / control.texi
blob401a999cf23c5f221f1babf8cc1f37f9164de34c
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-2017 Free Software
4 @c Foundation, Inc.
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.
17 @cindex textual order
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
28 than sequential.
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}).
37 @menu
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.
44 @end menu
46 @node Sequencing
47 @section Sequencing
48 @cindex sequencing
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:
59 @example
60 @group
61 (progn @var{a} @var{b} @var{c} @dots{})
62 @end group
63 @end example
65 @noindent
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.
87 @example
88 @group
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"
96 @end group
97 @end example
98 @end defspec
100   Two other constructs likewise evaluate a series of forms but return
101 different values:
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}.
107 @example
108 @group
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"
116 @end group
117 @end example
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:
122 @example
123 (prog1 (car x) (setq x (cdr x)))
124 @end example
125 @end defspec
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
130 @var{form2}.
132 @example
133 @group
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"
141 @end group
142 @end example
143 @end defspec
145 @node Conditionals
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:
169 @example
170 @group
171 (if nil
172     (print 'true)
173   'very-false)
174 @result{} very-false
175 @end group
176 @end example
177 @end defspec
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,
183 @example
184 (when @var{condition} @var{a} @var{b} @var{c})
185 @end example
187 @noindent
188 is entirely equivalent to
190 @example
191 (if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
192 @end example
193 @end defmac
195 @defmac unless condition forms@dots{}
196 This is a variant of @code{if} where there is no @var{then-form}:
198 @example
199 (unless @var{condition} @var{a} @var{b} @var{c})
200 @end example
202 @noindent
203 is entirely equivalent to
205 @example
206 (if @var{condition} nil
207    @var{a} @var{b} @var{c})
208 @end example
209 @end defmac
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:
217 @example
218 (@var{condition} @var{body-forms}@dots{})
219 @end example
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:
232 @example
233 (@var{condition})
234 @end example
236 @noindent
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,
245 respectively:
247 @example
248 @group
249 (cond ((numberp x) x)
250       ((stringp x) x)
251       ((bufferp x)
252        (setq temporary-hack x) ; @r{multiple body-forms}
253        (buffer-name x))        ; @r{in one clause}
254       ((symbolp x) (symbol-value x)))
255 @end group
256 @end example
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:
265 @example
266 @group
267 (setq a 5)
268 (cond ((eq a 'hack) 'foo)
269       (t "default"))
270 @result{} "default"
271 @end group
272 @end example
274 @noindent
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.
277 @end defspec
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.
281 For example:
283 @example
284 @group
285 (if @var{a} @var{b} @var{c})
286 @equiv{}
287 (cond (@var{a} @var{b}) (t @var{c}))
288 @end group
289 @end example
291 @menu
292 * Pattern matching case statement::
293 @end menu
295 @node Pattern matching case statement
296 @subsection Pattern matching case statement
297 @cindex pcase
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
325 describe them first.
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:
333 @table @code
335 @item '@var{val}
336 Matches if the value being matched is @code{equal} to @var{val}.
337 @item @var{atom}
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.
342 @item _
343 Matches any value.  This is known as @dfn{don't care} or @dfn{wildcard}.
344 @item @var{symbol}
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.
381 @end table
383 The function calls used in the @code{pred} and @code{app} UPatterns
384 can have one of the following forms:
386 @table @asis
387 @item function symbol, like @code{integerp}
388 In this case, the named function is applied to the value being
389 matched.
390 @item lambda-function @code{(lambda (@var{arg}) @var{body})}
391 In this case, the lambda-function is called with one argument, the
392 value being matched.
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.
397 @end table
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.
403 @example
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)))
410 @end example
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:
423 @table @code
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.
433 @item @var{atom}
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}.
439 @end table
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.
448 @end defmac
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}):
454 @example
455 (defun evaluate (exp env)
456   (pcase exp
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))))
461     ((pred numberp)     exp)
462     ((pred symbolp)     (cdr (assq exp env)))
463     (_                  (error "Unknown expression %S" exp))))
464 @end example
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
478 evaluation results:
480 @example
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
485 @end example
487 Additional UPatterns can be defined using the @code{pcase-defmacro}
488 macro.
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}.
496 @end defmac
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.
507 @defun not condition
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.
512 @end defun
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
517 order written.
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.
535 @example
536 @group
537 (and (print 1) (print 2) nil (print 3))
538      @print{} 1
539      @print{} 2
540 @result{} nil
541 @end group
542 @end example
544 Here is a more realistic example of using @code{and}:
546 @example
547 @group
548 (if (and (consp foo) (eq (car foo) 'x))
549     (message "foo is a list starting with x"))
550 @end group
551 @end example
553 @noindent
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:
560 @example
561 @group
562 (and @var{arg1} @var{arg2} @var{arg3})
563 @equiv{}
564 (if @var{arg1} (if @var{arg2} @var{arg3}))
565 @equiv{}
566 (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
567 @end group
568 @end example
569 @end defspec
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
585 did not?)
587 For example, this expression tests whether @code{x} is either
588 @code{nil} or the integer zero:
590 @example
591 (or (eq x nil) (eq x 0))
592 @end example
594 Like the @code{and} construct, @code{or} can be written in terms of
595 @code{cond}.  For example:
597 @example
598 @group
599 (or @var{arg1} @var{arg2} @var{arg3})
600 @equiv{}
601 (cond (@var{arg1})
602       (@var{arg2})
603       (@var{arg3}))
604 @end group
605 @end example
607 You could almost write @code{or} in terms of @code{if}, but not quite:
609 @example
610 @group
611 (if @var{arg1} @var{arg1}
612   (if @var{arg2} @var{arg2}
613     @var{arg3}))
614 @end group
615 @end example
617 @noindent
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.
621 @end defspec
623 @node Iteration
624 @section Iteration
625 @cindex iteration
626 @cindex recursion
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}.
646 @example
647 @group
648 (setq num 0)
649      @result{} 0
650 @end group
651 @group
652 (while (< num 4)
653   (princ (format "Iteration %d." num))
654   (setq num (1+ num)))
655      @print{} Iteration 0.
656      @print{} Iteration 1.
657      @print{} Iteration 2.
658      @print{} Iteration 3.
659      @result{} nil
660 @end group
661 @end example
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
666 shown here:
668 @example
669 @group
670 (while (progn
671          (forward-line 1)
672          (not (looking-at "^$"))))
673 @end group
674 @end example
676 @noindent
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).
680 @end defspec
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:
692 @example
693 (defun reverse (list)
694   (let (value)
695     (dolist (elt list value)
696       (setq value (cons elt value)))))
697 @end example
698 @end defmac
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:
707 @example
708 (dotimes (i 100)
709   (insert "I will not obey absurd orders\n"))
710 @end example
711 @end defmac
713 @node Generators
714 @section Generators
715 @cindex generators
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.
735 @end defmac
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}.
740 @end defmac
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}.
747 @end defmac
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}.
754 @end defmac
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.
782 @end defun
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}.
791 @end defun
793 Some convenience functions are provided to make working with
794 iterators easier:
796 @defmac iter-do (var iterator) body @dots{}
797 Run @var{body} with @var{var} bound to each value that
798 @var{iterator} produces.
799 @end defmac
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.
807 @example
808 (require 'generator)
809 (iter-defun my-iter (x)
810   (iter-yield (1+ (iter-yield (1+ x))))
811    ;; Return normally
812   -1)
814 (let* ((iter (my-iter 5))
815        (iter2 (my-iter 0)))
816   ;; Prints 6
817   (print (iter-next iter))
818   ;; Prints 9
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
824   (condition-case x
825       (iter-next iter)
826     (iter-end-of-sequence
827       ;; Prints -1, which my-iter returned normally
828       (print (cdr x)))))
829 @end example
831 @node Nonlocal Exits
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
839 exited.
841 @menu
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.
846 @end menu
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:
858 @example
859 @group
860 (defun foo-outer ()
861   (catch 'foo
862     (foo-inner)))
864 (defun foo-inner ()
865   @dots{}
866   (if x
867       (throw 'foo t))
868   @dots{})
869 @end group
870 @end example
872 @noindent
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
906 @quotation
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}.
912 @end quotation
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
924 the @code{catch}.
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}.
930 @end defspec
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
940 @code{catch}.
942 @kindex no-catch
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})}.
945 @end defun
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}
953 varying from 0 to 9:
955 @example
956 @group
957 (defun search-foo ()
958   (catch 'loop
959     (let ((i 0))
960       (while (< i 10)
961         (let ((j 0))
962           (while (< j 10)
963             (if (foo i j)
964                 (throw 'loop (list i j)))
965             (setq j (1+ j))))
966         (setq i (1+ i))))))
967 @end group
968 @end example
970 @noindent
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,
978 @code{hack}:
980 @example
981 @group
982 (defun catch2 (tag)
983   (catch tag
984     (throw 'hack 'yes)))
985 @result{} catch2
986 @end group
988 @group
989 (catch 'hack
990   (print (catch2 'hack))
991   'no)
992 @print{} yes
993 @result{} no
994 @end group
995 @end example
997 @noindent
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}:
1006 @example
1007 @group
1008 (catch 'hack
1009   (print (catch2 'quux))
1010   'no)
1011 @result{} yes
1012 @end group
1013 @end example
1015 @noindent
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.
1022 @node Errors
1023 @subsection Errors
1024 @cindex errors
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}.
1048 @menu
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.
1053 @end menu
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
1063 error.
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.
1073 @xref{Quitting}.
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}:
1088 @example
1089 @group
1090 (error "That is an error -- try something else")
1091      @error{} That is an error -- try something else
1092 @end group
1094 @group
1095 (error "Invalid name `%s'" "A%%B")
1096      @error{} Invalid name â€˜A%%B’
1097 @end group
1098 @end example
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 The @code{text-quoting-style} variable controls what quotes are
1105 generated; @xref{Keys in Documentation}.  A call using a format like
1106 @t{"Missing `%s'"} with grave accents and apostrophes typically
1107 generates a message like @t{"Missing â€˜foo’"} with matching curved
1108 quotes.  In contrast, a call using a format like @t{"Missing '%s'"}
1109 with only apostrophes typically generates a message like @t{"Missing
1110 ’foo’"} with only closing curved quotes, an unusual style in English.
1112 @strong{Warning:} If you want to use your own string as an error message
1113 verbatim, don't just write @code{(error @var{string})}.  If @var{string}
1114 @var{string} contains @samp{%}, @samp{`}, or @samp{'} it may be
1115 reformatted, with undesirable results.  Instead, use @code{(error "%s"
1116 @var{string})}.
1117 @end defun
1119 @defun signal error-symbol data
1120 @anchor{Definition of signal}
1121 This function signals an error named by @var{error-symbol}.  The
1122 argument @var{data} is a list of additional Lisp objects relevant to
1123 the circumstances of the error.
1125 The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
1126 defined with @code{define-error}.  This is how Emacs Lisp classifies different
1127 sorts of errors.  @xref{Error Symbols}, for a description of error symbols,
1128 error conditions and condition names.
1130 If the error is not handled, the two arguments are used in printing
1131 the error message.  Normally, this error message is provided by the
1132 @code{error-message} property of @var{error-symbol}.  If @var{data} is
1133 non-@code{nil}, this is followed by a colon and a comma separated list
1134 of the unevaluated elements of @var{data}.  For @code{error}, the
1135 error message is the @sc{car} of @var{data} (that must be a string).
1136 Subcategories of @code{file-error} are handled specially.
1138 The number and significance of the objects in @var{data} depends on
1139 @var{error-symbol}.  For example, with a @code{wrong-type-argument} error,
1140 there should be two objects in the list: a predicate that describes the type
1141 that was expected, and the object that failed to fit that type.
1143 Both @var{error-symbol} and @var{data} are available to any error
1144 handlers that handle the error: @code{condition-case} binds a local
1145 variable to a list of the form @code{(@var{error-symbol} .@:
1146 @var{data})} (@pxref{Handling Errors}).
1148 The function @code{signal} never returns.
1149 @c (though in older Emacs versions it sometimes could).
1151 @example
1152 @group
1153 (signal 'wrong-number-of-arguments '(x y))
1154      @error{} Wrong number of arguments: x, y
1155 @end group
1157 @group
1158 (signal 'no-such-error '("My unknown error condition"))
1159      @error{} peculiar error: "My unknown error condition"
1160 @end group
1161 @end example
1162 @end defun
1164 @cindex user errors, signaling
1165 @defun user-error format-string &rest args
1166 This function behaves exactly like @code{error}, except that it uses
1167 the error symbol @code{user-error} rather than @code{error}.  As the
1168 name suggests, this is intended to report errors on the part of the
1169 user, rather than errors in the code itself.  For example,
1170 if you try to use the command @code{Info-history-back} (@kbd{l}) to
1171 move back beyond the start of your Info browsing history, Emacs
1172 signals a @code{user-error}.  Such errors do not cause entry to the
1173 debugger, even when @code{debug-on-error} is non-@code{nil}.
1174 @xref{Error Debugging}.
1175 @end defun
1177 @cindex CL note---no continuable errors
1178 @quotation
1179 @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
1180 concept of continuable errors.
1181 @end quotation
1183 @node Processing of Errors
1184 @subsubsection How Emacs Processes Errors
1185 @cindex processing of errors
1187 When an error is signaled, @code{signal} searches for an active
1188 @dfn{handler} for the error.  A handler is a sequence of Lisp
1189 expressions designated to be executed if an error happens in part of the
1190 Lisp program.  If the error has an applicable handler, the handler is
1191 executed, and control resumes following the handler.  The handler
1192 executes in the environment of the @code{condition-case} that
1193 established it; all functions called within that @code{condition-case}
1194 have already been exited, and the handler cannot return to them.
1196 If there is no applicable handler for the error, it terminates the
1197 current command and returns control to the editor command loop.  (The
1198 command loop has an implicit handler for all kinds of errors.)  The
1199 command loop's handler uses the error symbol and associated data to
1200 print an error message.  You can use the variable
1201 @code{command-error-function} to control how this is done:
1203 @defvar command-error-function
1204 This variable, if non-@code{nil}, specifies a function to use to
1205 handle errors that return control to the Emacs command loop.  The
1206 function should take three arguments: @var{data}, a list of the same
1207 form that @code{condition-case} would bind to its variable;
1208 @var{context}, a string describing the situation in which the error
1209 occurred, or (more often) @code{nil}; and @var{caller}, the Lisp
1210 function which called the primitive that signaled the error.
1211 @end defvar
1213 @cindex @code{debug-on-error} use
1214 An error that has no explicit handler may call the Lisp debugger.  The
1215 debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
1216 Debugging}) is non-@code{nil}.  Unlike error handlers, the debugger runs
1217 in the environment of the error, so that you can examine values of
1218 variables precisely as they were at the time of the error.
1220 @node Handling Errors
1221 @subsubsection Writing Code to Handle Errors
1222 @cindex error handler
1223 @cindex handling errors
1225   The usual effect of signaling an error is to terminate the command
1226 that is running and return immediately to the Emacs editor command loop.
1227 You can arrange to trap errors occurring in a part of your program by
1228 establishing an error handler, with the special form
1229 @code{condition-case}.  A simple example looks like this:
1231 @example
1232 @group
1233 (condition-case nil
1234     (delete-file filename)
1235   (error nil))
1236 @end group
1237 @end example
1239 @noindent
1240 This deletes the file named @var{filename}, catching any error and
1241 returning @code{nil} if an error occurs.  (You can use the macro
1242 @code{ignore-errors} for a simple case like this; see below.)
1244   The @code{condition-case} construct is often used to trap errors that
1245 are predictable, such as failure to open a file in a call to
1246 @code{insert-file-contents}.  It is also used to trap errors that are
1247 totally unpredictable, such as when the program evaluates an expression
1248 read from the user.
1250   The second argument of @code{condition-case} is called the
1251 @dfn{protected form}.  (In the example above, the protected form is a
1252 call to @code{delete-file}.)  The error handlers go into effect when
1253 this form begins execution and are deactivated when this form returns.
1254 They remain in effect for all the intervening time.  In particular, they
1255 are in effect during the execution of functions called by this form, in
1256 their subroutines, and so on.  This is a good thing, since, strictly
1257 speaking, errors can be signaled only by Lisp primitives (including
1258 @code{signal} and @code{error}) called by the protected form, not by the
1259 protected form itself.
1261   The arguments after the protected form are handlers.  Each handler
1262 lists one or more @dfn{condition names} (which are symbols) to specify
1263 which errors it will handle.  The error symbol specified when an error
1264 is signaled also defines a list of condition names.  A handler applies
1265 to an error if they have any condition names in common.  In the example
1266 above, there is one handler, and it specifies one condition name,
1267 @code{error}, which covers all errors.
1269   The search for an applicable handler checks all the established handlers
1270 starting with the most recently established one.  Thus, if two nested
1271 @code{condition-case} forms offer to handle the same error, the inner of
1272 the two gets to handle it.
1274   If an error is handled by some @code{condition-case} form, this
1275 ordinarily prevents the debugger from being run, even if
1276 @code{debug-on-error} says this error should invoke the debugger.
1278   If you want to be able to debug errors that are caught by a
1279 @code{condition-case}, set the variable @code{debug-on-signal} to a
1280 non-@code{nil} value.  You can also specify that a particular handler
1281 should let the debugger run first, by writing @code{debug} among the
1282 conditions, like this:
1284 @example
1285 @group
1286 (condition-case nil
1287     (delete-file filename)
1288   ((debug error) nil))
1289 @end group
1290 @end example
1292 @noindent
1293 The effect of @code{debug} here is only to prevent
1294 @code{condition-case} from suppressing the call to the debugger.  Any
1295 given error will invoke the debugger only if @code{debug-on-error} and
1296 the other usual filtering mechanisms say it should.  @xref{Error Debugging}.
1298 @defmac condition-case-unless-debug var protected-form handlers@dots{}
1299 The macro @code{condition-case-unless-debug} provides another way to
1300 handle debugging of such forms.  It behaves exactly like
1301 @code{condition-case}, unless the variable @code{debug-on-error} is
1302 non-@code{nil}, in which case it does not handle any errors at all.
1303 @end defmac
1305   Once Emacs decides that a certain handler handles the error, it
1306 returns control to that handler.  To do so, Emacs unbinds all variable
1307 bindings made by binding constructs that are being exited, and
1308 executes the cleanups of all @code{unwind-protect} forms that are
1309 being exited.  Once control arrives at the handler, the body of the
1310 handler executes normally.
1312   After execution of the handler body, execution returns from the
1313 @code{condition-case} form.  Because the protected form is exited
1314 completely before execution of the handler, the handler cannot resume
1315 execution at the point of the error, nor can it examine variable
1316 bindings that were made within the protected form.  All it can do is
1317 clean up and proceed.
1319   Error signaling and handling have some resemblance to @code{throw} and
1320 @code{catch} (@pxref{Catch and Throw}), but they are entirely separate
1321 facilities.  An error cannot be caught by a @code{catch}, and a
1322 @code{throw} cannot be handled by an error handler (though using
1323 @code{throw} when there is no suitable @code{catch} signals an error
1324 that can be handled).
1326 @defspec condition-case var protected-form handlers@dots{}
1327 This special form establishes the error handlers @var{handlers} around
1328 the execution of @var{protected-form}.  If @var{protected-form} executes
1329 without error, the value it returns becomes the value of the
1330 @code{condition-case} form; in this case, the @code{condition-case} has
1331 no effect.  The @code{condition-case} form makes a difference when an
1332 error occurs during @var{protected-form}.
1334 Each of the @var{handlers} is a list of the form @code{(@var{conditions}
1335 @var{body}@dots{})}.  Here @var{conditions} is an error condition name
1336 to be handled, or a list of condition names (which can include @code{debug}
1337 to allow the debugger to run before the handler); @var{body} is one or more
1338 Lisp expressions to be executed when this handler handles an error.
1339 Here are examples of handlers:
1341 @example
1342 @group
1343 (error nil)
1345 (arith-error (message "Division by zero"))
1347 ((arith-error file-error)
1348  (message
1349   "Either division by zero or failure to open a file"))
1350 @end group
1351 @end example
1353 Each error that occurs has an @dfn{error symbol} that describes what
1354 kind of error it is, and which describes also a list of condition names
1355 (@pxref{Error Symbols}).  Emacs
1356 searches all the active @code{condition-case} forms for a handler that
1357 specifies one or more of these condition names; the innermost matching
1358 @code{condition-case} handles the error.  Within this
1359 @code{condition-case}, the first applicable handler handles the error.
1361 After executing the body of the handler, the @code{condition-case}
1362 returns normally, using the value of the last form in the handler body
1363 as the overall value.
1365 @cindex error description
1366 The argument @var{var} is a variable.  @code{condition-case} does not
1367 bind this variable when executing the @var{protected-form}, only when it
1368 handles an error.  At that time, it binds @var{var} locally to an
1369 @dfn{error description}, which is a list giving the particulars of the
1370 error.  The error description has the form @code{(@var{error-symbol}
1371 . @var{data})}.  The handler can refer to this list to decide what to
1372 do.  For example, if the error is for failure opening a file, the file
1373 name is the second element of @var{data}---the third element of the
1374 error description.
1376 If @var{var} is @code{nil}, that means no variable is bound.  Then the
1377 error symbol and associated data are not available to the handler.
1379 @cindex rethrow a signal
1380 Sometimes it is necessary to re-throw a signal caught by
1381 @code{condition-case}, for some outer-level handler to catch.  Here's
1382 how to do that:
1384 @example
1385   (signal (car err) (cdr err))
1386 @end example
1388 @noindent
1389 where @code{err} is the error description variable, the first argument
1390 to @code{condition-case} whose error condition you want to re-throw.
1391 @xref{Definition of signal}.
1392 @end defspec
1394 @defun error-message-string error-descriptor
1395 This function returns the error message string for a given error
1396 descriptor.  It is useful if you want to handle an error by printing the
1397 usual error message for that error.  @xref{Definition of signal}.
1398 @end defun
1400 @cindex @code{arith-error} example
1401 Here is an example of using @code{condition-case} to handle the error
1402 that results from dividing by zero.  The handler displays the error
1403 message (but without a beep), then returns a very large number.
1405 @example
1406 @group
1407 (defun safe-divide (dividend divisor)
1408   (condition-case err
1409       ;; @r{Protected form.}
1410       (/ dividend divisor)
1411 @end group
1412 @group
1413     ;; @r{The handler.}
1414     (arith-error                        ; @r{Condition.}
1415      ;; @r{Display the usual message for this error.}
1416      (message "%s" (error-message-string err))
1417      1000000)))
1418 @result{} safe-divide
1419 @end group
1421 @group
1422 (safe-divide 5 0)
1423      @print{} Arithmetic error: (arith-error)
1424 @result{} 1000000
1425 @end group
1426 @end example
1428 @noindent
1429 The handler specifies condition name @code{arith-error} so that it
1430 will handle only division-by-zero errors.  Other kinds of errors will
1431 not be handled (by this @code{condition-case}).  Thus:
1433 @example
1434 @group
1435 (safe-divide nil 3)
1436      @error{} Wrong type argument: number-or-marker-p, nil
1437 @end group
1438 @end example
1440   Here is a @code{condition-case} that catches all kinds of errors,
1441 including those from @code{error}:
1443 @example
1444 @group
1445 (setq baz 34)
1446      @result{} 34
1447 @end group
1449 @group
1450 (condition-case err
1451     (if (eq baz 35)
1452         t
1453       ;; @r{This is a call to the function @code{error}.}
1454       (error "Rats!  The variable %s was %s, not 35" 'baz baz))
1455   ;; @r{This is the handler; it is not a form.}
1456   (error (princ (format "The error was: %s" err))
1457          2))
1458 @print{} The error was: (error "Rats!  The variable baz was 34, not 35")
1459 @result{} 2
1460 @end group
1461 @end example
1463 @defmac ignore-errors body@dots{}
1464 This construct executes @var{body}, ignoring any errors that occur
1465 during its execution.  If the execution is without error,
1466 @code{ignore-errors} returns the value of the last form in @var{body};
1467 otherwise, it returns @code{nil}.
1469 Here's the example at the beginning of this subsection rewritten using
1470 @code{ignore-errors}:
1472 @example
1473 @group
1474   (ignore-errors
1475    (delete-file filename))
1476 @end group
1477 @end example
1478 @end defmac
1480 @defmac with-demoted-errors format body@dots{}
1481 This macro is like a milder version of @code{ignore-errors}.  Rather
1482 than suppressing errors altogether, it converts them into messages.
1483 It uses the string @var{format} to format the message.
1484 @var{format} should contain a single @samp{%}-sequence; e.g.,
1485 @code{"Error: %S"}.  Use @code{with-demoted-errors} around code
1486 that is not expected to signal errors, but
1487 should be robust if one does occur.  Note that this macro uses
1488 @code{condition-case-unless-debug} rather than @code{condition-case}.
1489 @end defmac
1491 @node Error Symbols
1492 @subsubsection Error Symbols and Condition Names
1493 @cindex error symbol
1494 @cindex error name
1495 @cindex condition name
1496 @cindex user-defined error
1497 @kindex error-conditions
1498 @kindex define-error
1500   When you signal an error, you specify an @dfn{error symbol} to specify
1501 the kind of error you have in mind.  Each error has one and only one
1502 error symbol to categorize it.  This is the finest classification of
1503 errors defined by the Emacs Lisp language.
1505   These narrow classifications are grouped into a hierarchy of wider
1506 classes called @dfn{error conditions}, identified by @dfn{condition
1507 names}.  The narrowest such classes belong to the error symbols
1508 themselves: each error symbol is also a condition name.  There are also
1509 condition names for more extensive classes, up to the condition name
1510 @code{error} which takes in all kinds of errors (but not @code{quit}).
1511 Thus, each error has one or more condition names: @code{error}, the
1512 error symbol if that is distinct from @code{error}, and perhaps some
1513 intermediate classifications.
1515 @defun define-error name message &optional parent
1516   In order for a symbol to be an error symbol, it must be defined with
1517 @code{define-error} which takes a parent condition (defaults to @code{error}).
1518 This parent defines the conditions that this kind of error belongs to.
1519 The transitive set of parents always includes the error symbol itself, and the
1520 symbol @code{error}.  Because quitting is not considered an error, the set of
1521 parents of @code{quit} is just @code{(quit)}.
1522 @end defun
1524 @cindex peculiar error
1525   In addition to its parents, the error symbol has a @var{message} which
1526 is a string to be printed when that error is signaled but not handled.  If that
1527 message is not valid, the error message @samp{peculiar error} is used.
1528 @xref{Definition of signal}.
1530 Internally, the set of parents is stored in the @code{error-conditions}
1531 property of the error symbol and the message is stored in the
1532 @code{error-message} property of the error symbol.
1534   Here is how we define a new error symbol, @code{new-error}:
1536 @example
1537 @group
1538 (define-error 'new-error "A new error" 'my-own-errors)
1539 @end group
1540 @end example
1542 @noindent
1543 This error has several condition names: @code{new-error}, the narrowest
1544 classification; @code{my-own-errors}, which we imagine is a wider
1545 classification; and all the conditions of @code{my-own-errors} which should
1546 include @code{error}, which is the widest of all.
1548   The error string should start with a capital letter but it should
1549 not end with a period.  This is for consistency with the rest of Emacs.
1551   Naturally, Emacs will never signal @code{new-error} on its own; only
1552 an explicit call to @code{signal} (@pxref{Definition of signal}) in
1553 your code can do this:
1555 @example
1556 @group
1557 (signal 'new-error '(x y))
1558      @error{} A new error: x, y
1559 @end group
1560 @end example
1562   This error can be handled through any of its condition names.
1563 This example handles @code{new-error} and any other errors in the class
1564 @code{my-own-errors}:
1566 @example
1567 @group
1568 (condition-case foo
1569     (bar nil t)
1570   (my-own-errors nil))
1571 @end group
1572 @end example
1574   The significant way that errors are classified is by their condition
1575 names---the names used to match errors with handlers.  An error symbol
1576 serves only as a convenient way to specify the intended error message
1577 and list of condition names.  It would be cumbersome to give
1578 @code{signal} a list of condition names rather than one error symbol.
1580   By contrast, using only error symbols without condition names would
1581 seriously decrease the power of @code{condition-case}.  Condition names
1582 make it possible to categorize errors at various levels of generality
1583 when you write an error handler.  Using error symbols alone would
1584 eliminate all but the narrowest level of classification.
1586   @xref{Standard Errors}, for a list of the main error symbols
1587 and their conditions.
1589 @node Cleanups
1590 @subsection Cleaning Up from Nonlocal Exits
1591 @cindex nonlocal exits, cleaning up
1593   The @code{unwind-protect} construct is essential whenever you
1594 temporarily put a data structure in an inconsistent state; it permits
1595 you to make the data consistent again in the event of an error or
1596 throw.  (Another more specific cleanup construct that is used only for
1597 changes in buffer contents is the atomic change group; @ref{Atomic
1598 Changes}.)
1600 @defspec unwind-protect body-form cleanup-forms@dots{}
1601 @cindex cleanup forms
1602 @cindex protected forms
1603 @cindex error cleanup
1604 @cindex unwinding
1605 @code{unwind-protect} executes @var{body-form} with a guarantee that
1606 the @var{cleanup-forms} will be evaluated if control leaves
1607 @var{body-form}, no matter how that happens.  @var{body-form} may
1608 complete normally, or execute a @code{throw} out of the
1609 @code{unwind-protect}, or cause an error; in all cases, the
1610 @var{cleanup-forms} will be evaluated.
1612 If @var{body-form} finishes normally, @code{unwind-protect} returns the
1613 value of @var{body-form}, after it evaluates the @var{cleanup-forms}.
1614 If @var{body-form} does not finish, @code{unwind-protect} does not
1615 return any value in the normal sense.
1617 Only @var{body-form} is protected by the @code{unwind-protect}.  If any
1618 of the @var{cleanup-forms} themselves exits nonlocally (via a
1619 @code{throw} or an error), @code{unwind-protect} is @emph{not}
1620 guaranteed to evaluate the rest of them.  If the failure of one of the
1621 @var{cleanup-forms} has the potential to cause trouble, then protect
1622 it with another @code{unwind-protect} around that form.
1624 The number of currently active @code{unwind-protect} forms counts,
1625 together with the number of local variable bindings, against the limit
1626 @code{max-specpdl-size} (@pxref{Definition of max-specpdl-size,, Local
1627 Variables}).
1628 @end defspec
1630   For example, here we make an invisible buffer for temporary use, and
1631 make sure to kill it before finishing:
1633 @example
1634 @group
1635 (let ((buffer (get-buffer-create " *temp*")))
1636   (with-current-buffer buffer
1637     (unwind-protect
1638         @var{body-form}
1639       (kill-buffer buffer))))
1640 @end group
1641 @end example
1643 @noindent
1644 You might think that we could just as well write @code{(kill-buffer
1645 (current-buffer))} and dispense with the variable @code{buffer}.
1646 However, the way shown above is safer, if @var{body-form} happens to
1647 get an error after switching to a different buffer!  (Alternatively,
1648 you could write a @code{save-current-buffer} around @var{body-form},
1649 to ensure that the temporary buffer becomes current again in time to
1650 kill it.)
1652   Emacs includes a standard macro called @code{with-temp-buffer} which
1653 expands into more or less the code shown above (@pxref{Definition of
1654 with-temp-buffer,, Current Buffer}).  Several of the macros defined in
1655 this manual use @code{unwind-protect} in this way.
1657 @findex ftp-login
1658   Here is an actual example derived from an FTP package.  It creates a
1659 process (@pxref{Processes}) to try to establish a connection to a remote
1660 machine.  As the function @code{ftp-login} is highly susceptible to
1661 numerous problems that the writer of the function cannot anticipate, it
1662 is protected with a form that guarantees deletion of the process in the
1663 event of failure.  Otherwise, Emacs might fill up with useless
1664 subprocesses.
1666 @example
1667 @group
1668 (let ((win nil))
1669   (unwind-protect
1670       (progn
1671         (setq process (ftp-setup-buffer host file))
1672         (if (setq win (ftp-login process host user password))
1673             (message "Logged in")
1674           (error "Ftp login failed")))
1675     (or win (and process (delete-process process)))))
1676 @end group
1677 @end example
1679   This example has a small bug: if the user types @kbd{C-g} to
1680 quit, and the quit happens immediately after the function
1681 @code{ftp-setup-buffer} returns but before the variable @code{process} is
1682 set, the process will not be killed.  There is no easy way to fix this bug,
1683 but at least it is very unlikely.