]> code.delx.au - gnu-emacs/blob - doc/lispref/control.texi
Minor doc fixes for quoting
[gnu-emacs] / doc / lispref / control.texi
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
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
10
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.
16
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.
26
27 Explicit control structures make possible an order of execution other
28 than sequential.
29
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}).
36
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
45
46 @node Sequencing
47 @section Sequencing
48 @cindex sequencing
49 @cindex sequential execution
50
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.
56
57 A @code{progn} special form looks like this:
58
59 @example
60 @group
61 (progn @var{a} @var{b} @var{c} @dots{})
62 @end group
63 @end example
64
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}.
70
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}.
82
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.
86
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
99
100 Two other constructs likewise evaluate a series of forms but return
101 different values:
102
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}.
106
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
118
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:
121
122 @example
123 (prog1 (car x) (setq x (cdr x)))
124 @end example
125 @end defspec
126
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}.
131
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
144
145 @node Conditionals
146 @section Conditionals
147 @cindex conditional evaluation
148
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.
153
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}.)
161
162 If @var{condition} has the value @code{nil}, and no @var{else-forms} are
163 given, @code{if} returns @code{nil}.
164
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:
168
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
178
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,
182
183 @example
184 (when @var{condition} @var{a} @var{b} @var{c})
185 @end example
186
187 @noindent
188 is entirely equivalent to
189
190 @example
191 (if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
192 @end example
193 @end defmac
194
195 @defmac unless condition forms@dots{}
196 This is a variant of @code{if} where there is no @var{then-form}:
197
198 @example
199 (unless @var{condition} @var{a} @var{b} @var{c})
200 @end example
201
202 @noindent
203 is entirely equivalent to
204
205 @example
206 (if @var{condition} nil
207 @var{a} @var{b} @var{c})
208 @end example
209 @end defmac
210
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:
216
217 @example
218 (@var{condition} @var{body-forms}@dots{})
219 @end example
220
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.
226
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}.
229
230 A clause may also look like this:
231
232 @example
233 (@var{condition})
234 @end example
235
236 @noindent
237 Then, if @var{condition} is non-@code{nil} when tested, the @code{cond}
238 form returns the value of @var{condition}.
239
240 If every @var{condition} evaluates to @code{nil}, so that every clause
241 fails, @code{cond} returns @code{nil}.
242
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:
246
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
257
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:
264
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
273
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
278
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:
282
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
290
291 @menu
292 * Pattern matching case statement::
293 @end menu
294
295 @node Pattern matching case statement
296 @subsection Pattern matching case statement
297 @cindex pcase
298 @cindex pattern matching
299
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.
310
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.
321
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.
326
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}.
330
331 A UPattern can have the following forms:
332
333 @table @code
334
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
382
383 The function calls used in the @code{pred} and @code{app} UPatterns
384 can have one of the following forms:
385
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
398
399 Here's an illustrative example of using UPatterns:
400
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
411
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)}.
419
420 Backquoted patterns have the form @code{`@var{qpattern}} where
421 @var{qpattern} can have the following forms:
422
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
440
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.
447
448 @end defmac
449
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}):
453
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
465
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.
476
477 Here are some sample programs in this small language, including their
478 evaluation results:
479
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
486
487 Additional UPatterns can be defined using the @code{pcase-defmacro}
488 macro.
489
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
497
498 @node Combining Conditions
499 @section Constructs for Combining Conditions
500 @cindex combining conditions
501
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.
506
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
513
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.
518
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}.
523
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?)
529
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.
534
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
543
544 Here is a more realistic example of using @code{and}:
545
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
552
553 @noindent
554 Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
555 @code{nil}, thus avoiding an error.
556
557 @code{and} expressions can also be written using either @code{if} or
558 @code{cond}. Here's how:
559
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
570
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.
575
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.
580
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?)
586
587 For example, this expression tests whether @code{x} is either
588 @code{nil} or the integer zero:
589
590 @example
591 (or (eq x nil) (eq x 0))
592 @end example
593
594 Like the @code{and} construct, @code{or} can be written in terms of
595 @code{cond}. For example:
596
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
606
607 You could almost write @code{or} in terms of @code{if}, but not quite:
608
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
616
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
622
623 @node Iteration
624 @section Iteration
625 @cindex iteration
626 @cindex recursion
627
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}:
632
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}.
639
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}).
643
644 The value of a @code{while} form is always @code{nil}.
645
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
662
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:
667
668 @example
669 @group
670 (while (progn
671 (forward-line 1)
672 (not (looking-at "^$"))))
673 @end group
674 @end example
675
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
681
682 The @code{dolist} and @code{dotimes} macros provide convenient ways to
683 write two common kinds of loops.
684
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:
691
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
699
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:
706
707 @example
708 (dotimes (i 100)
709 (insert "I will not obey absurd orders\n"))
710 @end example
711 @end defmac
712
713 @node Generators
714 @section Generators
715 @cindex generators
716
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.
720
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.
730
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.
734
735 @end defmac
736
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
741
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
748
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
755
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.
762
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.
769
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.
776
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
783
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
792
793 Some convenience functions are provided to make working with
794 iterators easier:
795
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
800
801 The Common Lisp loop facility also contains features for working with
802 iterators. See @xref{Loop Facility,,,cl,Common Lisp Extensions}.
803
804 The following piece of code demonstrates some important principles of
805 working with iterators.
806
807 @example
808 (iter-defun my-iter (x)
809 (iter-yield (1+ (iter-yield (1+ x))))
810 ;; Return normally
811 -1)
812
813 (let* ((iter (my-iter 5))
814 (iter2 (my-iter 0)))
815 ;; Prints 6
816 (print (iter-next iter))
817 ;; Prints 9
818 (print (iter-next iter 8))
819 ;; Prints 1; iter and iter2 have distinct states
820 (print (iter-next iter2 nil))
821
822 ;; We expect the iter sequence to end now
823 (condition-case x
824 (iter-next iter)
825 (iter-end-of-sequence
826 ;; Prints -1, which my-iter returned normally
827 (print (cdr x)))))
828 @end example
829
830 @node Nonlocal Exits
831 @section Nonlocal Exits
832 @cindex nonlocal exits
833
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
838 exited.
839
840 @menu
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.
845 @end menu
846
847 @node Catch and Throw
848 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
849
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:
856
857 @example
858 @group
859 (defun foo-outer ()
860 (catch 'foo
861 (foo-inner)))
862
863 (defun foo-inner ()
864 @dots{}
865 (if x
866 (throw 'foo t))
867 @dots{})
868 @end group
869 @end example
870
871 @noindent
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}.
876
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).
885
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}).
895
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}).
903
904 @cindex CL note---only @code{throw} in Emacs
905 @quotation
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}.
911 @end quotation
912
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.
919
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
923 the @code{catch}.
924
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}.
929 @end defspec
930
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.
937
938 The argument @var{value} is used as the value to return from that
939 @code{catch}.
940
941 @kindex no-catch
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})}.
944 @end defun
945
946 @node Examples of Catch
947 @subsection Examples of @code{catch} and @code{throw}
948
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}
952 varying from 0 to 9:
953
954 @example
955 @group
956 (defun search-foo ()
957 (catch 'loop
958 (let ((i 0))
959 (while (< i 10)
960 (let ((j 0))
961 (while (< j 10)
962 (if (foo i j)
963 (throw 'loop (list i j)))
964 (setq j (1+ j))))
965 (setq i (1+ i))))))
966 @end group
967 @end example
968
969 @noindent
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}.
974
975 Here are two tricky examples, slightly different, showing two
976 return points at once. First, two return points with the same tag,
977 @code{hack}:
978
979 @example
980 @group
981 (defun catch2 (tag)
982 (catch tag
983 (throw 'hack 'yes)))
984 @result{} catch2
985 @end group
986
987 @group
988 (catch 'hack
989 (print (catch2 'hack))
990 'no)
991 @print{} yes
992 @result{} no
993 @end group
994 @end example
995
996 @noindent
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}.
1002
1003 Now let's change the argument given to @code{catch2}:
1004
1005 @example
1006 @group
1007 (catch 'hack
1008 (print (catch2 'quux))
1009 'no)
1010 @result{} yes
1011 @end group
1012 @end example
1013
1014 @noindent
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.
1020
1021 @node Errors
1022 @subsection Errors
1023 @cindex errors
1024
1025 When Emacs Lisp attempts to evaluate a form that, for some reason,
1026 cannot be evaluated, it @dfn{signals} an @dfn{error}.
1027
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.
1032
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.
1042
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}.
1046
1047 @menu
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.
1052 @end menu
1053
1054 @node Signaling Errors
1055 @subsubsection How to Signal an Error
1056 @cindex signaling errors
1057
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
1062 error.
1063
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}.
1069
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.
1072 @xref{Quitting}.
1073
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.
1079
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}.
1084
1085 These examples show typical uses of @code{error}:
1086
1087 @example
1088 @group
1089 (error "That is an error -- try something else")
1090 @error{} That is an error -- try something else
1091 @end group
1092
1093 @group
1094 (error "Invalid name `%s'" "A%%B")
1095 @error{} Invalid name ‘A%%B’
1096 @end group
1097 @end example
1098
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}.
1102
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.
1110
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"
1115 @var{string})}.
1116 @end defun
1117
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.
1123
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.
1128
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.
1136
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.
1141
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}).
1146
1147 The function @code{signal} never returns.
1148 @c (though in older Emacs versions it sometimes could).
1149
1150 @example
1151 @group
1152 (signal 'wrong-number-of-arguments '(x y))
1153 @error{} Wrong number of arguments: x, y
1154 @end group
1155
1156 @group
1157 (signal 'no-such-error '("My unknown error condition"))
1158 @error{} peculiar error: "My unknown error condition"
1159 @end group
1160 @end example
1161 @end defun
1162
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}.
1174 @end defun
1175
1176 @cindex CL note---no continuable errors
1177 @quotation
1178 @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
1179 concept of continuable errors.
1180 @end quotation
1181
1182 @node Processing of Errors
1183 @subsubsection How Emacs Processes Errors
1184 @cindex processing of errors
1185
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.
1194
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:
1201
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.
1210 @end defvar
1211
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.
1218
1219 @node Handling Errors
1220 @subsubsection Writing Code to Handle Errors
1221 @cindex error handler
1222 @cindex handling errors
1223
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:
1229
1230 @example
1231 @group
1232 (condition-case nil
1233 (delete-file filename)
1234 (error nil))
1235 @end group
1236 @end example
1237
1238 @noindent
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.)
1242
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
1247 read from the user.
1248
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.
1259
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.
1267
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.
1272
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.
1276
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:
1282
1283 @example
1284 @group
1285 (condition-case nil
1286 (delete-file filename)
1287 ((debug error) nil))
1288 @end group
1289 @end example
1290
1291 @noindent
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}.
1296
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.
1302 @end defmac
1303
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.
1310
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.
1317
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).
1324
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}.
1332
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:
1339
1340 @example
1341 @group
1342 (error nil)
1343
1344 (arith-error (message "Division by zero"))
1345
1346 ((arith-error file-error)
1347 (message
1348 "Either division by zero or failure to open a file"))
1349 @end group
1350 @end example
1351
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.
1359
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.
1363
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
1373 error description.
1374
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.
1377
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
1381 how to do that:
1382
1383 @example
1384 (signal (car err) (cdr err))
1385 @end example
1386
1387 @noindent
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}.
1391 @end defspec
1392
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}.
1397 @end defun
1398
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.
1403
1404 @example
1405 @group
1406 (defun safe-divide (dividend divisor)
1407 (condition-case err
1408 ;; @r{Protected form.}
1409 (/ dividend divisor)
1410 @end group
1411 @group
1412 ;; @r{The handler.}
1413 (arith-error ; @r{Condition.}
1414 ;; @r{Display the usual message for this error.}
1415 (message "%s" (error-message-string err))
1416 1000000)))
1417 @result{} safe-divide
1418 @end group
1419
1420 @group
1421 (safe-divide 5 0)
1422 @print{} Arithmetic error: (arith-error)
1423 @result{} 1000000
1424 @end group
1425 @end example
1426
1427 @noindent
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:
1431
1432 @example
1433 @group
1434 (safe-divide nil 3)
1435 @error{} Wrong type argument: number-or-marker-p, nil
1436 @end group
1437 @end example
1438
1439 Here is a @code{condition-case} that catches all kinds of errors,
1440 including those from @code{error}:
1441
1442 @example
1443 @group
1444 (setq baz 34)
1445 @result{} 34
1446 @end group
1447
1448 @group
1449 (condition-case err
1450 (if (eq baz 35)
1451 t
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))
1456 2))
1457 @print{} The error was: (error "Rats! The variable baz was 34, not 35")
1458 @result{} 2
1459 @end group
1460 @end example
1461
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}.
1467
1468 Here's the example at the beginning of this subsection rewritten using
1469 @code{ignore-errors}:
1470
1471 @example
1472 @group
1473 (ignore-errors
1474 (delete-file filename))
1475 @end group
1476 @end example
1477 @end defmac
1478
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}.
1488 @end defmac
1489
1490 @node Error Symbols
1491 @subsubsection Error Symbols and Condition Names
1492 @cindex error symbol
1493 @cindex error name
1494 @cindex condition name
1495 @cindex user-defined error
1496 @kindex error-conditions
1497 @kindex define-error
1498
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.
1503
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.
1513
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)}.
1521 @end defun
1522
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}.
1528
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.
1532
1533 Here is how we define a new error symbol, @code{new-error}:
1534
1535 @example
1536 @group
1537 (define-error 'new-error "A new error" 'my-own-errors)
1538 @end group
1539 @end example
1540
1541 @noindent
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.
1546
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.
1549
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:
1553
1554 @example
1555 @group
1556 (signal 'new-error '(x y))
1557 @error{} A new error: x, y
1558 @end group
1559 @end example
1560
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}:
1564
1565 @example
1566 @group
1567 (condition-case foo
1568 (bar nil t)
1569 (my-own-errors nil))
1570 @end group
1571 @end example
1572
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.
1578
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.
1584
1585 @xref{Standard Errors}, for a list of the main error symbols
1586 and their conditions.
1587
1588 @node Cleanups
1589 @subsection Cleaning Up from Nonlocal Exits
1590 @cindex nonlocal exits, cleaning up
1591
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
1597 Changes}.)
1598
1599 @defspec unwind-protect body-form cleanup-forms@dots{}
1600 @cindex cleanup forms
1601 @cindex protected forms
1602 @cindex error cleanup
1603 @cindex unwinding
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.
1610
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.
1615
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.
1622
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
1626 Variables}).
1627 @end defspec
1628
1629 For example, here we make an invisible buffer for temporary use, and
1630 make sure to kill it before finishing:
1631
1632 @example
1633 @group
1634 (let ((buffer (get-buffer-create " *temp*")))
1635 (with-current-buffer buffer
1636 (unwind-protect
1637 @var{body-form}
1638 (kill-buffer buffer))))
1639 @end group
1640 @end example
1641
1642 @noindent
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
1649 kill it.)
1650
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.
1655
1656 @findex ftp-login
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
1663 subprocesses.
1664
1665 @example
1666 @group
1667 (let ((win nil))
1668 (unwind-protect
1669 (progn
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)))))
1675 @end group
1676 @end example
1677
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.