]> code.delx.au - gnu-emacs/blob - doc/lispref/control.texi
Update copyright year to 2016
[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 To compare a particular value against various possible cases, the macro
301 @code{pcase} can come handy. It takes the following form:
302
303 @example
304 (pcase @var{exp} @var{branch}1 @var{branch}2 @var{branch}3 @dots{})
305 @end example
306
307 where each @var{branch} takes the form @code{(@var{upattern}
308 @var{body-forms}@dots{})}.
309
310 It will first evaluate @var{exp} and then compare the value against each
311 @var{upattern} to see which @var{branch} to use, after which it will run the
312 corresponding @var{body-forms}. A common use case is to distinguish
313 between a few different constant values:
314
315 @example
316 (pcase (get-return-code x)
317 (`success (message "Done!"))
318 (`would-block (message "Sorry, can't do it now"))
319 (`read-only (message "The shmliblick is read-only"))
320 (`access-denied (message "You do not have the needed rights"))
321 (code (message "Unknown return code %S" code)))
322 @end example
323
324 In the last clause, @code{code} is a variable that gets bound to the value that
325 was returned by @code{(get-return-code x)}.
326
327 To give a more complex example, a simple interpreter for a little
328 expression language could look like (note that this example requires
329 lexical binding):
330
331 @example
332 (defun evaluate (exp env)
333 (pcase exp
334 (`(add ,x ,y) (+ (evaluate x env) (evaluate y env)))
335 (`(call ,fun ,arg) (funcall (evaluate fun env) (evaluate arg env)))
336 (`(fn ,arg ,body) (lambda (val)
337 (evaluate body (cons (cons arg val) env))))
338 ((pred numberp) exp)
339 ((pred symbolp) (cdr (assq exp env)))
340 (_ (error "Unknown expression %S" exp))))
341 @end example
342
343 Where @code{`(add ,x ,y)} is a pattern that checks that @code{exp} is a three
344 element list starting with the symbol @code{add}, then extracts the second and
345 third elements and binds them to the variables @code{x} and @code{y}.
346 @code{(pred numberp)} is a pattern that simply checks that @code{exp}
347 is a number, and @code{_} is the catch-all pattern that matches anything.
348
349 Here are some sample programs including their evaluation results:
350
351 @example
352 (evaluate '(add 1 2) nil) ;=> 3
353 (evaluate '(add x y) '((x . 1) (y . 2))) ;=> 3
354 (evaluate '(call (fn x (add 1 x)) 2) nil) ;=> 3
355 (evaluate '(sub 1 2) nil) ;=> error
356 @end example
357
358 There are two kinds of patterns involved in @code{pcase}, called
359 @emph{U-patterns} and @emph{Q-patterns}. The @var{upattern} mentioned above
360 are U-patterns and can take the following forms:
361
362 @table @code
363 @item `@var{qpattern}
364 This is one of the most common form of patterns. The intention is to mimic the
365 backquote macro: this pattern matches those values that could have been built
366 by such a backquote expression. Since we're pattern matching rather than
367 building a value, the unquote does not indicate where to plug an expression,
368 but instead it lets one specify a U-pattern that should match the value at
369 that location.
370
371 More specifically, a Q-pattern can take the following forms:
372 @table @code
373 @item (@var{qpattern1} . @var{qpattern2})
374 This pattern matches any cons cell whose @code{car} matches @var{qpattern1} and
375 whose @code{cdr} matches @var{qpattern2}.
376 @item [@var{qpattern1} @var{qpattern2} @dots{} @var{qpatternm}]
377 This pattern matches a vector of length @var{M} whose 0..(@var{M}-1)th
378 elements match @var{qpattern1}, @var{qpattern2} @dots{} @var{qpatternm},
379 respectively.
380 @item @var{atom}
381 This pattern matches any atom @code{equal} to @var{atom}.
382 @item ,@var{upattern}
383 This pattern matches any object that matches the @var{upattern}.
384 @end table
385
386 @item @var{symbol}
387 A mere symbol in a U-pattern matches anything, and additionally let-binds this
388 symbol to the value that it matched, so that you can later refer to it, either
389 in the @var{body-forms} or also later in the pattern.
390 @item _
391 This so-called @emph{don't care} pattern matches anything, like the previous
392 one, but unlike symbol patterns it does not bind any variable.
393 @item (pred @var{pred})
394 This pattern matches if the function @var{pred} returns non-@code{nil} when
395 called with the object being matched.
396 @item (or @var{upattern1} @var{upattern2}@dots{})
397 This pattern matches as soon as one of the argument patterns succeeds.
398 All argument patterns should let-bind the same variables.
399 @item (and @var{upattern1} @var{upattern2}@dots{})
400 This pattern matches only if all the argument patterns succeed.
401 @item (guard @var{exp})
402 This pattern ignores the object being examined and simply succeeds if @var{exp}
403 evaluates to non-@code{nil} and fails otherwise. It is typically used inside
404 an @code{and} pattern. For example, @code{(and x (guard (< x 10)))}
405 is a pattern which matches any number smaller than 10 and let-binds it to
406 the variable @code{x}.
407 @end table
408
409 @node Combining Conditions
410 @section Constructs for Combining Conditions
411 @cindex combining conditions
412
413 This section describes three constructs that are often used together
414 with @code{if} and @code{cond} to express complicated conditions. The
415 constructs @code{and} and @code{or} can also be used individually as
416 kinds of multiple conditional constructs.
417
418 @defun not condition
419 This function tests for the falsehood of @var{condition}. It returns
420 @code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
421 The function @code{not} is identical to @code{null}, and we recommend
422 using the name @code{null} if you are testing for an empty list.
423 @end defun
424
425 @defspec and conditions@dots{}
426 The @code{and} special form tests whether all the @var{conditions} are
427 true. It works by evaluating the @var{conditions} one by one in the
428 order written.
429
430 If any of the @var{conditions} evaluates to @code{nil}, then the result
431 of the @code{and} must be @code{nil} regardless of the remaining
432 @var{conditions}; so @code{and} returns @code{nil} right away, ignoring
433 the remaining @var{conditions}.
434
435 If all the @var{conditions} turn out non-@code{nil}, then the value of
436 the last of them becomes the value of the @code{and} form. Just
437 @code{(and)}, with no @var{conditions}, returns @code{t}, appropriate
438 because all the @var{conditions} turned out non-@code{nil}. (Think
439 about it; which one did not?)
440
441 Here is an example. The first condition returns the integer 1, which is
442 not @code{nil}. Similarly, the second condition returns the integer 2,
443 which is not @code{nil}. The third condition is @code{nil}, so the
444 remaining condition is never evaluated.
445
446 @example
447 @group
448 (and (print 1) (print 2) nil (print 3))
449 @print{} 1
450 @print{} 2
451 @result{} nil
452 @end group
453 @end example
454
455 Here is a more realistic example of using @code{and}:
456
457 @example
458 @group
459 (if (and (consp foo) (eq (car foo) 'x))
460 (message "foo is a list starting with x"))
461 @end group
462 @end example
463
464 @noindent
465 Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
466 @code{nil}, thus avoiding an error.
467
468 @code{and} expressions can also be written using either @code{if} or
469 @code{cond}. Here's how:
470
471 @example
472 @group
473 (and @var{arg1} @var{arg2} @var{arg3})
474 @equiv{}
475 (if @var{arg1} (if @var{arg2} @var{arg3}))
476 @equiv{}
477 (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
478 @end group
479 @end example
480 @end defspec
481
482 @defspec or conditions@dots{}
483 The @code{or} special form tests whether at least one of the
484 @var{conditions} is true. It works by evaluating all the
485 @var{conditions} one by one in the order written.
486
487 If any of the @var{conditions} evaluates to a non-@code{nil} value, then
488 the result of the @code{or} must be non-@code{nil}; so @code{or} returns
489 right away, ignoring the remaining @var{conditions}. The value it
490 returns is the non-@code{nil} value of the condition just evaluated.
491
492 If all the @var{conditions} turn out @code{nil}, then the @code{or}
493 expression returns @code{nil}. Just @code{(or)}, with no
494 @var{conditions}, returns @code{nil}, appropriate because all the
495 @var{conditions} turned out @code{nil}. (Think about it; which one
496 did not?)
497
498 For example, this expression tests whether @code{x} is either
499 @code{nil} or the integer zero:
500
501 @example
502 (or (eq x nil) (eq x 0))
503 @end example
504
505 Like the @code{and} construct, @code{or} can be written in terms of
506 @code{cond}. For example:
507
508 @example
509 @group
510 (or @var{arg1} @var{arg2} @var{arg3})
511 @equiv{}
512 (cond (@var{arg1})
513 (@var{arg2})
514 (@var{arg3}))
515 @end group
516 @end example
517
518 You could almost write @code{or} in terms of @code{if}, but not quite:
519
520 @example
521 @group
522 (if @var{arg1} @var{arg1}
523 (if @var{arg2} @var{arg2}
524 @var{arg3}))
525 @end group
526 @end example
527
528 @noindent
529 This is not completely equivalent because it can evaluate @var{arg1} or
530 @var{arg2} twice. By contrast, @code{(or @var{arg1} @var{arg2}
531 @var{arg3})} never evaluates any argument more than once.
532 @end defspec
533
534 @node Iteration
535 @section Iteration
536 @cindex iteration
537 @cindex recursion
538
539 Iteration means executing part of a program repetitively. For
540 example, you might want to repeat some computation once for each element
541 of a list, or once for each integer from 0 to @var{n}. You can do this
542 in Emacs Lisp with the special form @code{while}:
543
544 @defspec while condition forms@dots{}
545 @code{while} first evaluates @var{condition}. If the result is
546 non-@code{nil}, it evaluates @var{forms} in textual order. Then it
547 reevaluates @var{condition}, and if the result is non-@code{nil}, it
548 evaluates @var{forms} again. This process repeats until @var{condition}
549 evaluates to @code{nil}.
550
551 There is no limit on the number of iterations that may occur. The loop
552 will continue until either @var{condition} evaluates to @code{nil} or
553 until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
554
555 The value of a @code{while} form is always @code{nil}.
556
557 @example
558 @group
559 (setq num 0)
560 @result{} 0
561 @end group
562 @group
563 (while (< num 4)
564 (princ (format "Iteration %d." num))
565 (setq num (1+ num)))
566 @print{} Iteration 0.
567 @print{} Iteration 1.
568 @print{} Iteration 2.
569 @print{} Iteration 3.
570 @result{} nil
571 @end group
572 @end example
573
574 To write a repeat-until loop, which will execute something on each
575 iteration and then do the end-test, put the body followed by the
576 end-test in a @code{progn} as the first argument of @code{while}, as
577 shown here:
578
579 @example
580 @group
581 (while (progn
582 (forward-line 1)
583 (not (looking-at "^$"))))
584 @end group
585 @end example
586
587 @noindent
588 This moves forward one line and continues moving by lines until it
589 reaches an empty line. It is peculiar in that the @code{while} has no
590 body, just the end test (which also does the real work of moving point).
591 @end defspec
592
593 The @code{dolist} and @code{dotimes} macros provide convenient ways to
594 write two common kinds of loops.
595
596 @defmac dolist (var list [result]) body@dots{}
597 This construct executes @var{body} once for each element of
598 @var{list}, binding the variable @var{var} locally to hold the current
599 element. Then it returns the value of evaluating @var{result}, or
600 @code{nil} if @var{result} is omitted. For example, here is how you
601 could use @code{dolist} to define the @code{reverse} function:
602
603 @example
604 (defun reverse (list)
605 (let (value)
606 (dolist (elt list value)
607 (setq value (cons elt value)))))
608 @end example
609 @end defmac
610
611 @defmac dotimes (var count [result]) body@dots{}
612 This construct executes @var{body} once for each integer from 0
613 (inclusive) to @var{count} (exclusive), binding the variable @var{var}
614 to the integer for the current iteration. Then it returns the value
615 of evaluating @var{result}, or @code{nil} if @var{result} is omitted.
616 Here is an example of using @code{dotimes} to do something 100 times:
617
618 @example
619 (dotimes (i 100)
620 (insert "I will not obey absurd orders\n"))
621 @end example
622 @end defmac
623
624 @node Generators
625 @section Generators
626 @cindex generators
627
628 A @dfn{generator} is a function that produces a potentially-infinite
629 stream of values. Each time the function produces a value, it
630 suspends itself and waits for a caller to request the next value.
631
632 @defmac iter-defun name args [doc] [declare] [interactive] body@dots{}
633 @code{iter-defun} defines a generator function. A generator function
634 has the same signature as a normal function, but works differently.
635 Instead of executing @var{body} when called, a generator function
636 returns an iterator object. That iterator runs @var{body} to generate
637 values, emitting a value and pausing where @code{iter-yield} or
638 @code{iter-yield-from} appears. When @var{body} returns normally,
639 @code{iter-next} signals @code{iter-end-of-sequence} with @var{body}'s
640 result as its condition data.
641
642 Any kind of Lisp code is valid inside @var{body}, but
643 @code{iter-yield} and @code{iter-yield-from} cannot appear inside
644 @code{unwind-protect} forms.
645
646 @end defmac
647
648 @defmac iter-lambda args [doc] [interactive] body@dots{}
649 @code{iter-lambda} produces an unnamed generator function that works
650 just like a generator function produced with @code{iter-defun}.
651 @end defmac
652
653 @defmac iter-yield value
654 When it appears inside a generator function, @code{iter-yield}
655 indicates that the current iterator should pause and return
656 @var{value} from @code{iter-next}. @code{iter-yield} evaluates to the
657 @code{value} parameter of next call to @code{iter-next}.
658 @end defmac
659
660 @defmac iter-yield-from iterator
661 @code{iter-yield-from} yields all the values that @var{iterator}
662 produces and evaluates to the value that @var{iterator}'s generator
663 function returns normally. While it has control, @var{iterator}
664 receives values sent to the iterator using @code{iter-next}.
665 @end defmac
666
667 To use a generator function, first call it normally, producing a
668 @dfn{iterator} object. An iterator is a specific instance of a
669 generator. Then use @code{iter-next} to retrieve values from this
670 iterator. When there are no more values to pull from an iterator,
671 @code{iter-next} raises an @code{iter-end-of-sequence} condition with
672 the iterator's final value.
673
674 It's important to note that generator function bodies only execute
675 inside calls to @code{iter-next}. A call to a function defined with
676 @code{iter-defun} produces an iterator; you must drive this
677 iterator with @code{iter-next} for anything interesting to happen.
678 Each call to a generator function produces a @emph{different}
679 iterator, each with its own state.
680
681 @defun iter-next iterator value
682 Retrieve the next value from @var{iterator}. If there are no more
683 values to be generated (because @var{iterator}'s generator function
684 returned), @code{iter-next} signals the @code{iter-end-of-sequence}
685 condition; the data value associated with this condition is the value
686 with which @var{iterator}'s generator function returned.
687
688 @var{value} is sent into the iterator and becomes the value to which
689 @code{iter-yield} evaluates. @var{value} is ignored for the first
690 @code{iter-next} call to a given iterator, since at the start of
691 @var{iterator}'s generator function, the generator function is not
692 evaluating any @code{iter-yield} form.
693 @end defun
694
695 @defun iter-close iterator
696 If @var{iterator} is suspended inside an @code{unwind-protect}'s
697 @code{bodyform} and becomes unreachable, Emacs will eventually run
698 unwind handlers after a garbage collection pass. (Note that
699 @code{iter-yield} is illegal inside an @code{unwind-protect}'s
700 @code{unwindforms}.) To ensure that these handlers are run before
701 then, use @code{iter-close}.
702 @end defun
703
704 Some convenience functions are provided to make working with
705 iterators easier:
706
707 @defmac iter-do (var iterator) body @dots{}
708 Run @var{body} with @var{var} bound to each value that
709 @var{iterator} produces.
710 @end defmac
711
712 The Common Lisp loop facility also contains features for working with
713 iterators. See @xref{Loop Facility,,,cl,Common Lisp Extensions}.
714
715 The following piece of code demonstrates some important principles of
716 working with iterators.
717
718 @example
719 (iter-defun my-iter (x)
720 (iter-yield (1+ (iter-yield (1+ x))))
721 ;; Return normally
722 -1)
723
724 (let* ((iter (my-iter 5))
725 (iter2 (my-iter 0)))
726 ;; Prints 6
727 (print (iter-next iter))
728 ;; Prints 9
729 (print (iter-next iter 8))
730 ;; Prints 1; iter and iter2 have distinct states
731 (print (iter-next iter2 nil))
732
733 ;; We expect the iter sequence to end now
734 (condition-case x
735 (iter-next iter)
736 (iter-end-of-sequence
737 ;; Prints -1, which my-iter returned normally
738 (print (cdr x)))))
739 @end example
740
741 @node Nonlocal Exits
742 @section Nonlocal Exits
743 @cindex nonlocal exits
744
745 A @dfn{nonlocal exit} is a transfer of control from one point in a
746 program to another remote point. Nonlocal exits can occur in Emacs Lisp
747 as a result of errors; you can also use them under explicit control.
748 Nonlocal exits unbind all variable bindings made by the constructs being
749 exited.
750
751 @menu
752 * Catch and Throw:: Nonlocal exits for the program's own purposes.
753 * Examples of Catch:: Showing how such nonlocal exits can be written.
754 * Errors:: How errors are signaled and handled.
755 * Cleanups:: Arranging to run a cleanup form if an error happens.
756 @end menu
757
758 @node Catch and Throw
759 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
760
761 Most control constructs affect only the flow of control within the
762 construct itself. The function @code{throw} is the exception to this
763 rule of normal program execution: it performs a nonlocal exit on
764 request. (There are other exceptions, but they are for error handling
765 only.) @code{throw} is used inside a @code{catch}, and jumps back to
766 that @code{catch}. For example:
767
768 @example
769 @group
770 (defun foo-outer ()
771 (catch 'foo
772 (foo-inner)))
773
774 (defun foo-inner ()
775 @dots{}
776 (if x
777 (throw 'foo t))
778 @dots{})
779 @end group
780 @end example
781
782 @noindent
783 The @code{throw} form, if executed, transfers control straight back to
784 the corresponding @code{catch}, which returns immediately. The code
785 following the @code{throw} is not executed. The second argument of
786 @code{throw} is used as the return value of the @code{catch}.
787
788 The function @code{throw} finds the matching @code{catch} based on the
789 first argument: it searches for a @code{catch} whose first argument is
790 @code{eq} to the one specified in the @code{throw}. If there is more
791 than one applicable @code{catch}, the innermost one takes precedence.
792 Thus, in the above example, the @code{throw} specifies @code{foo}, and
793 the @code{catch} in @code{foo-outer} specifies the same symbol, so that
794 @code{catch} is the applicable one (assuming there is no other matching
795 @code{catch} in between).
796
797 Executing @code{throw} exits all Lisp constructs up to the matching
798 @code{catch}, including function calls. When binding constructs such
799 as @code{let} or function calls are exited in this way, the bindings
800 are unbound, just as they are when these constructs exit normally
801 (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
802 and position saved by @code{save-excursion} (@pxref{Excursions}), and
803 the narrowing status saved by @code{save-restriction}. It also runs
804 any cleanups established with the @code{unwind-protect} special form
805 when it exits that form (@pxref{Cleanups}).
806
807 The @code{throw} need not appear lexically within the @code{catch}
808 that it jumps to. It can equally well be called from another function
809 called within the @code{catch}. As long as the @code{throw} takes place
810 chronologically after entry to the @code{catch}, and chronologically
811 before exit from it, it has access to that @code{catch}. This is why
812 @code{throw} can be used in commands such as @code{exit-recursive-edit}
813 that throw back to the editor command loop (@pxref{Recursive Editing}).
814
815 @cindex CL note---only @code{throw} in Emacs
816 @quotation
817 @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
818 have several ways of transferring control nonsequentially: @code{return},
819 @code{return-from}, and @code{go}, for example. Emacs Lisp has only
820 @code{throw}. The @file{cl-lib} library provides versions of some of
821 these. @xref{Blocks and Exits,,,cl,Common Lisp Extensions}.
822 @end quotation
823
824 @defspec catch tag body@dots{}
825 @cindex tag on run time stack
826 @code{catch} establishes a return point for the @code{throw} function.
827 The return point is distinguished from other such return points by
828 @var{tag}, which may be any Lisp object except @code{nil}. The argument
829 @var{tag} is evaluated normally before the return point is established.
830
831 With the return point in effect, @code{catch} evaluates the forms of the
832 @var{body} in textual order. If the forms execute normally (without
833 error or nonlocal exit) the value of the last body form is returned from
834 the @code{catch}.
835
836 If a @code{throw} is executed during the execution of @var{body},
837 specifying the same value @var{tag}, the @code{catch} form exits
838 immediately; the value it returns is whatever was specified as the
839 second argument of @code{throw}.
840 @end defspec
841
842 @defun throw tag value
843 The purpose of @code{throw} is to return from a return point previously
844 established with @code{catch}. The argument @var{tag} is used to choose
845 among the various existing return points; it must be @code{eq} to the value
846 specified in the @code{catch}. If multiple return points match @var{tag},
847 the innermost one is used.
848
849 The argument @var{value} is used as the value to return from that
850 @code{catch}.
851
852 @kindex no-catch
853 If no return point is in effect with tag @var{tag}, then a @code{no-catch}
854 error is signaled with data @code{(@var{tag} @var{value})}.
855 @end defun
856
857 @node Examples of Catch
858 @subsection Examples of @code{catch} and @code{throw}
859
860 One way to use @code{catch} and @code{throw} is to exit from a doubly
861 nested loop. (In most languages, this would be done with a @code{goto}.)
862 Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
863 varying from 0 to 9:
864
865 @example
866 @group
867 (defun search-foo ()
868 (catch 'loop
869 (let ((i 0))
870 (while (< i 10)
871 (let ((j 0))
872 (while (< j 10)
873 (if (foo i j)
874 (throw 'loop (list i j)))
875 (setq j (1+ j))))
876 (setq i (1+ i))))))
877 @end group
878 @end example
879
880 @noindent
881 If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
882 list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
883 @code{catch} returns normally, and the value is @code{nil}, since that
884 is the result of the @code{while}.
885
886 Here are two tricky examples, slightly different, showing two
887 return points at once. First, two return points with the same tag,
888 @code{hack}:
889
890 @example
891 @group
892 (defun catch2 (tag)
893 (catch tag
894 (throw 'hack 'yes)))
895 @result{} catch2
896 @end group
897
898 @group
899 (catch 'hack
900 (print (catch2 'hack))
901 'no)
902 @print{} yes
903 @result{} no
904 @end group
905 @end example
906
907 @noindent
908 Since both return points have tags that match the @code{throw}, it goes to
909 the inner one, the one established in @code{catch2}. Therefore,
910 @code{catch2} returns normally with value @code{yes}, and this value is
911 printed. Finally the second body form in the outer @code{catch}, which is
912 @code{'no}, is evaluated and returned from the outer @code{catch}.
913
914 Now let's change the argument given to @code{catch2}:
915
916 @example
917 @group
918 (catch 'hack
919 (print (catch2 'quux))
920 'no)
921 @result{} yes
922 @end group
923 @end example
924
925 @noindent
926 We still have two return points, but this time only the outer one has
927 the tag @code{hack}; the inner one has the tag @code{quux} instead.
928 Therefore, @code{throw} makes the outer @code{catch} return the value
929 @code{yes}. The function @code{print} is never called, and the
930 body-form @code{'no} is never evaluated.
931
932 @node Errors
933 @subsection Errors
934 @cindex errors
935
936 When Emacs Lisp attempts to evaluate a form that, for some reason,
937 cannot be evaluated, it @dfn{signals} an @dfn{error}.
938
939 When an error is signaled, Emacs's default reaction is to print an
940 error message and terminate execution of the current command. This is
941 the right thing to do in most cases, such as if you type @kbd{C-f} at
942 the end of the buffer.
943
944 In complicated programs, simple termination may not be what you want.
945 For example, the program may have made temporary changes in data
946 structures, or created temporary buffers that should be deleted before
947 the program is finished. In such cases, you would use
948 @code{unwind-protect} to establish @dfn{cleanup expressions} to be
949 evaluated in case of error. (@xref{Cleanups}.) Occasionally, you may
950 wish the program to continue execution despite an error in a subroutine.
951 In these cases, you would use @code{condition-case} to establish
952 @dfn{error handlers} to recover control in case of error.
953
954 Resist the temptation to use error handling to transfer control from
955 one part of the program to another; use @code{catch} and @code{throw}
956 instead. @xref{Catch and Throw}.
957
958 @menu
959 * Signaling Errors:: How to report an error.
960 * Processing of Errors:: What Emacs does when you report an error.
961 * Handling Errors:: How you can trap errors and continue execution.
962 * Error Symbols:: How errors are classified for trapping them.
963 @end menu
964
965 @node Signaling Errors
966 @subsubsection How to Signal an Error
967 @cindex signaling errors
968
969 @dfn{Signaling} an error means beginning error processing. Error
970 processing normally aborts all or part of the running program and
971 returns to a point that is set up to handle the error
972 (@pxref{Processing of Errors}). Here we describe how to signal an
973 error.
974
975 Most errors are signaled automatically within Lisp primitives
976 which you call for other purposes, such as if you try to take the
977 @sc{car} of an integer or move forward a character at the end of the
978 buffer. You can also signal errors explicitly with the functions
979 @code{error} and @code{signal}.
980
981 Quitting, which happens when the user types @kbd{C-g}, is not
982 considered an error, but it is handled almost like an error.
983 @xref{Quitting}.
984
985 Every error specifies an error message, one way or another. The
986 message should state what is wrong (``File does not exist''), not how
987 things ought to be (``File must exist''). The convention in Emacs
988 Lisp is that error messages should start with a capital letter, but
989 should not end with any sort of punctuation.
990
991 @defun error format-string &rest args
992 This function signals an error with an error message constructed by
993 applying @code{format-message} (@pxref{Formatting Strings}) to
994 @var{format-string} and @var{args}.
995
996 These examples show typical uses of @code{error}:
997
998 @example
999 @group
1000 (error "That is an error -- try something else")
1001 @error{} That is an error -- try something else
1002 @end group
1003
1004 @group
1005 (error "Invalid name `%s'" "A%%B")
1006 @error{} Invalid name ‘A%%B’
1007 @end group
1008 @end example
1009
1010 @code{error} works by calling @code{signal} with two arguments: the
1011 error symbol @code{error}, and a list containing the string returned by
1012 @code{format-message}.
1013
1014 In a format string containing single quotes, curved quotes @t{‘like
1015 this’} and grave quotes @t{`like this'} work better than straight
1016 quotes @t{'like this'}, as @code{error} typically formats every
1017 straight quote as a curved closing quote.
1018
1019 @strong{Warning:} If you want to use your own string as an error message
1020 verbatim, don't just write @code{(error @var{string})}. If @var{string}
1021 @var{string} contains @samp{%}, @samp{`}, or @samp{'} it may be
1022 reformatted, with undesirable results. Instead, use @code{(error "%s"
1023 @var{string})}.
1024 @end defun
1025
1026 @defun signal error-symbol data
1027 @anchor{Definition of signal}
1028 This function signals an error named by @var{error-symbol}. The
1029 argument @var{data} is a list of additional Lisp objects relevant to
1030 the circumstances of the error.
1031
1032 The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
1033 defined with @code{define-error}. This is how Emacs Lisp classifies different
1034 sorts of errors. @xref{Error Symbols}, for a description of error symbols,
1035 error conditions and condition names.
1036
1037 If the error is not handled, the two arguments are used in printing
1038 the error message. Normally, this error message is provided by the
1039 @code{error-message} property of @var{error-symbol}. If @var{data} is
1040 non-@code{nil}, this is followed by a colon and a comma separated list
1041 of the unevaluated elements of @var{data}. For @code{error}, the
1042 error message is the @sc{car} of @var{data} (that must be a string).
1043 Subcategories of @code{file-error} are handled specially.
1044
1045 The number and significance of the objects in @var{data} depends on
1046 @var{error-symbol}. For example, with a @code{wrong-type-argument} error,
1047 there should be two objects in the list: a predicate that describes the type
1048 that was expected, and the object that failed to fit that type.
1049
1050 Both @var{error-symbol} and @var{data} are available to any error
1051 handlers that handle the error: @code{condition-case} binds a local
1052 variable to a list of the form @code{(@var{error-symbol} .@:
1053 @var{data})} (@pxref{Handling Errors}).
1054
1055 The function @code{signal} never returns.
1056 @c (though in older Emacs versions it sometimes could).
1057
1058 @example
1059 @group
1060 (signal 'wrong-number-of-arguments '(x y))
1061 @error{} Wrong number of arguments: x, y
1062 @end group
1063
1064 @group
1065 (signal 'no-such-error '("My unknown error condition"))
1066 @error{} peculiar error: "My unknown error condition"
1067 @end group
1068 @end example
1069 @end defun
1070
1071 @cindex user errors, signaling
1072 @defun user-error format-string &rest args
1073 This function behaves exactly like @code{error}, except that it uses
1074 the error symbol @code{user-error} rather than @code{error}. As the
1075 name suggests, this is intended to report errors on the part of the
1076 user, rather than errors in the code itself. For example,
1077 if you try to use the command @code{Info-history-back} (@kbd{l}) to
1078 move back beyond the start of your Info browsing history, Emacs
1079 signals a @code{user-error}. Such errors do not cause entry to the
1080 debugger, even when @code{debug-on-error} is non-@code{nil}.
1081 @xref{Error Debugging}.
1082 @end defun
1083
1084 @cindex CL note---no continuable errors
1085 @quotation
1086 @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
1087 concept of continuable errors.
1088 @end quotation
1089
1090 @node Processing of Errors
1091 @subsubsection How Emacs Processes Errors
1092 @cindex processing of errors
1093
1094 When an error is signaled, @code{signal} searches for an active
1095 @dfn{handler} for the error. A handler is a sequence of Lisp
1096 expressions designated to be executed if an error happens in part of the
1097 Lisp program. If the error has an applicable handler, the handler is
1098 executed, and control resumes following the handler. The handler
1099 executes in the environment of the @code{condition-case} that
1100 established it; all functions called within that @code{condition-case}
1101 have already been exited, and the handler cannot return to them.
1102
1103 If there is no applicable handler for the error, it terminates the
1104 current command and returns control to the editor command loop. (The
1105 command loop has an implicit handler for all kinds of errors.) The
1106 command loop's handler uses the error symbol and associated data to
1107 print an error message. You can use the variable
1108 @code{command-error-function} to control how this is done:
1109
1110 @defvar command-error-function
1111 This variable, if non-@code{nil}, specifies a function to use to
1112 handle errors that return control to the Emacs command loop. The
1113 function should take three arguments: @var{data}, a list of the same
1114 form that @code{condition-case} would bind to its variable;
1115 @var{context}, a string describing the situation in which the error
1116 occurred, or (more often) @code{nil}; and @var{caller}, the Lisp
1117 function which called the primitive that signaled the error.
1118 @end defvar
1119
1120 @cindex @code{debug-on-error} use
1121 An error that has no explicit handler may call the Lisp debugger. The
1122 debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
1123 Debugging}) is non-@code{nil}. Unlike error handlers, the debugger runs
1124 in the environment of the error, so that you can examine values of
1125 variables precisely as they were at the time of the error.
1126
1127 @node Handling Errors
1128 @subsubsection Writing Code to Handle Errors
1129 @cindex error handler
1130 @cindex handling errors
1131
1132 The usual effect of signaling an error is to terminate the command
1133 that is running and return immediately to the Emacs editor command loop.
1134 You can arrange to trap errors occurring in a part of your program by
1135 establishing an error handler, with the special form
1136 @code{condition-case}. A simple example looks like this:
1137
1138 @example
1139 @group
1140 (condition-case nil
1141 (delete-file filename)
1142 (error nil))
1143 @end group
1144 @end example
1145
1146 @noindent
1147 This deletes the file named @var{filename}, catching any error and
1148 returning @code{nil} if an error occurs. (You can use the macro
1149 @code{ignore-errors} for a simple case like this; see below.)
1150
1151 The @code{condition-case} construct is often used to trap errors that
1152 are predictable, such as failure to open a file in a call to
1153 @code{insert-file-contents}. It is also used to trap errors that are
1154 totally unpredictable, such as when the program evaluates an expression
1155 read from the user.
1156
1157 The second argument of @code{condition-case} is called the
1158 @dfn{protected form}. (In the example above, the protected form is a
1159 call to @code{delete-file}.) The error handlers go into effect when
1160 this form begins execution and are deactivated when this form returns.
1161 They remain in effect for all the intervening time. In particular, they
1162 are in effect during the execution of functions called by this form, in
1163 their subroutines, and so on. This is a good thing, since, strictly
1164 speaking, errors can be signaled only by Lisp primitives (including
1165 @code{signal} and @code{error}) called by the protected form, not by the
1166 protected form itself.
1167
1168 The arguments after the protected form are handlers. Each handler
1169 lists one or more @dfn{condition names} (which are symbols) to specify
1170 which errors it will handle. The error symbol specified when an error
1171 is signaled also defines a list of condition names. A handler applies
1172 to an error if they have any condition names in common. In the example
1173 above, there is one handler, and it specifies one condition name,
1174 @code{error}, which covers all errors.
1175
1176 The search for an applicable handler checks all the established handlers
1177 starting with the most recently established one. Thus, if two nested
1178 @code{condition-case} forms offer to handle the same error, the inner of
1179 the two gets to handle it.
1180
1181 If an error is handled by some @code{condition-case} form, this
1182 ordinarily prevents the debugger from being run, even if
1183 @code{debug-on-error} says this error should invoke the debugger.
1184
1185 If you want to be able to debug errors that are caught by a
1186 @code{condition-case}, set the variable @code{debug-on-signal} to a
1187 non-@code{nil} value. You can also specify that a particular handler
1188 should let the debugger run first, by writing @code{debug} among the
1189 conditions, like this:
1190
1191 @example
1192 @group
1193 (condition-case nil
1194 (delete-file filename)
1195 ((debug error) nil))
1196 @end group
1197 @end example
1198
1199 @noindent
1200 The effect of @code{debug} here is only to prevent
1201 @code{condition-case} from suppressing the call to the debugger. Any
1202 given error will invoke the debugger only if @code{debug-on-error} and
1203 the other usual filtering mechanisms say it should. @xref{Error Debugging}.
1204
1205 @defmac condition-case-unless-debug var protected-form handlers@dots{}
1206 The macro @code{condition-case-unless-debug} provides another way to
1207 handle debugging of such forms. It behaves exactly like
1208 @code{condition-case}, unless the variable @code{debug-on-error} is
1209 non-@code{nil}, in which case it does not handle any errors at all.
1210 @end defmac
1211
1212 Once Emacs decides that a certain handler handles the error, it
1213 returns control to that handler. To do so, Emacs unbinds all variable
1214 bindings made by binding constructs that are being exited, and
1215 executes the cleanups of all @code{unwind-protect} forms that are
1216 being exited. Once control arrives at the handler, the body of the
1217 handler executes normally.
1218
1219 After execution of the handler body, execution returns from the
1220 @code{condition-case} form. Because the protected form is exited
1221 completely before execution of the handler, the handler cannot resume
1222 execution at the point of the error, nor can it examine variable
1223 bindings that were made within the protected form. All it can do is
1224 clean up and proceed.
1225
1226 Error signaling and handling have some resemblance to @code{throw} and
1227 @code{catch} (@pxref{Catch and Throw}), but they are entirely separate
1228 facilities. An error cannot be caught by a @code{catch}, and a
1229 @code{throw} cannot be handled by an error handler (though using
1230 @code{throw} when there is no suitable @code{catch} signals an error
1231 that can be handled).
1232
1233 @defspec condition-case var protected-form handlers@dots{}
1234 This special form establishes the error handlers @var{handlers} around
1235 the execution of @var{protected-form}. If @var{protected-form} executes
1236 without error, the value it returns becomes the value of the
1237 @code{condition-case} form; in this case, the @code{condition-case} has
1238 no effect. The @code{condition-case} form makes a difference when an
1239 error occurs during @var{protected-form}.
1240
1241 Each of the @var{handlers} is a list of the form @code{(@var{conditions}
1242 @var{body}@dots{})}. Here @var{conditions} is an error condition name
1243 to be handled, or a list of condition names (which can include @code{debug}
1244 to allow the debugger to run before the handler); @var{body} is one or more
1245 Lisp expressions to be executed when this handler handles an error.
1246 Here are examples of handlers:
1247
1248 @example
1249 @group
1250 (error nil)
1251
1252 (arith-error (message "Division by zero"))
1253
1254 ((arith-error file-error)
1255 (message
1256 "Either division by zero or failure to open a file"))
1257 @end group
1258 @end example
1259
1260 Each error that occurs has an @dfn{error symbol} that describes what
1261 kind of error it is, and which describes also a list of condition names
1262 (@pxref{Error Symbols}). Emacs
1263 searches all the active @code{condition-case} forms for a handler that
1264 specifies one or more of these condition names; the innermost matching
1265 @code{condition-case} handles the error. Within this
1266 @code{condition-case}, the first applicable handler handles the error.
1267
1268 After executing the body of the handler, the @code{condition-case}
1269 returns normally, using the value of the last form in the handler body
1270 as the overall value.
1271
1272 @cindex error description
1273 The argument @var{var} is a variable. @code{condition-case} does not
1274 bind this variable when executing the @var{protected-form}, only when it
1275 handles an error. At that time, it binds @var{var} locally to an
1276 @dfn{error description}, which is a list giving the particulars of the
1277 error. The error description has the form @code{(@var{error-symbol}
1278 . @var{data})}. The handler can refer to this list to decide what to
1279 do. For example, if the error is for failure opening a file, the file
1280 name is the second element of @var{data}---the third element of the
1281 error description.
1282
1283 If @var{var} is @code{nil}, that means no variable is bound. Then the
1284 error symbol and associated data are not available to the handler.
1285
1286 @cindex rethrow a signal
1287 Sometimes it is necessary to re-throw a signal caught by
1288 @code{condition-case}, for some outer-level handler to catch. Here's
1289 how to do that:
1290
1291 @example
1292 (signal (car err) (cdr err))
1293 @end example
1294
1295 @noindent
1296 where @code{err} is the error description variable, the first argument
1297 to @code{condition-case} whose error condition you want to re-throw.
1298 @xref{Definition of signal}.
1299 @end defspec
1300
1301 @defun error-message-string error-descriptor
1302 This function returns the error message string for a given error
1303 descriptor. It is useful if you want to handle an error by printing the
1304 usual error message for that error. @xref{Definition of signal}.
1305 @end defun
1306
1307 @cindex @code{arith-error} example
1308 Here is an example of using @code{condition-case} to handle the error
1309 that results from dividing by zero. The handler displays the error
1310 message (but without a beep), then returns a very large number.
1311
1312 @example
1313 @group
1314 (defun safe-divide (dividend divisor)
1315 (condition-case err
1316 ;; @r{Protected form.}
1317 (/ dividend divisor)
1318 @end group
1319 @group
1320 ;; @r{The handler.}
1321 (arith-error ; @r{Condition.}
1322 ;; @r{Display the usual message for this error.}
1323 (message "%s" (error-message-string err))
1324 1000000)))
1325 @result{} safe-divide
1326 @end group
1327
1328 @group
1329 (safe-divide 5 0)
1330 @print{} Arithmetic error: (arith-error)
1331 @result{} 1000000
1332 @end group
1333 @end example
1334
1335 @noindent
1336 The handler specifies condition name @code{arith-error} so that it
1337 will handle only division-by-zero errors. Other kinds of errors will
1338 not be handled (by this @code{condition-case}). Thus:
1339
1340 @example
1341 @group
1342 (safe-divide nil 3)
1343 @error{} Wrong type argument: number-or-marker-p, nil
1344 @end group
1345 @end example
1346
1347 Here is a @code{condition-case} that catches all kinds of errors,
1348 including those from @code{error}:
1349
1350 @example
1351 @group
1352 (setq baz 34)
1353 @result{} 34
1354 @end group
1355
1356 @group
1357 (condition-case err
1358 (if (eq baz 35)
1359 t
1360 ;; @r{This is a call to the function @code{error}.}
1361 (error "Rats! The variable %s was %s, not 35" 'baz baz))
1362 ;; @r{This is the handler; it is not a form.}
1363 (error (princ (format "The error was: %s" err))
1364 2))
1365 @print{} The error was: (error "Rats! The variable baz was 34, not 35")
1366 @result{} 2
1367 @end group
1368 @end example
1369
1370 @defmac ignore-errors body@dots{}
1371 This construct executes @var{body}, ignoring any errors that occur
1372 during its execution. If the execution is without error,
1373 @code{ignore-errors} returns the value of the last form in @var{body};
1374 otherwise, it returns @code{nil}.
1375
1376 Here's the example at the beginning of this subsection rewritten using
1377 @code{ignore-errors}:
1378
1379 @example
1380 @group
1381 (ignore-errors
1382 (delete-file filename))
1383 @end group
1384 @end example
1385 @end defmac
1386
1387 @defmac with-demoted-errors format body@dots{}
1388 This macro is like a milder version of @code{ignore-errors}. Rather
1389 than suppressing errors altogether, it converts them into messages.
1390 It uses the string @var{format} to format the message.
1391 @var{format} should contain a single @samp{%}-sequence; e.g.,
1392 @code{"Error: %S"}. Use @code{with-demoted-errors} around code
1393 that is not expected to signal errors, but
1394 should be robust if one does occur. Note that this macro uses
1395 @code{condition-case-unless-debug} rather than @code{condition-case}.
1396 @end defmac
1397
1398 @node Error Symbols
1399 @subsubsection Error Symbols and Condition Names
1400 @cindex error symbol
1401 @cindex error name
1402 @cindex condition name
1403 @cindex user-defined error
1404 @kindex error-conditions
1405 @kindex define-error
1406
1407 When you signal an error, you specify an @dfn{error symbol} to specify
1408 the kind of error you have in mind. Each error has one and only one
1409 error symbol to categorize it. This is the finest classification of
1410 errors defined by the Emacs Lisp language.
1411
1412 These narrow classifications are grouped into a hierarchy of wider
1413 classes called @dfn{error conditions}, identified by @dfn{condition
1414 names}. The narrowest such classes belong to the error symbols
1415 themselves: each error symbol is also a condition name. There are also
1416 condition names for more extensive classes, up to the condition name
1417 @code{error} which takes in all kinds of errors (but not @code{quit}).
1418 Thus, each error has one or more condition names: @code{error}, the
1419 error symbol if that is distinct from @code{error}, and perhaps some
1420 intermediate classifications.
1421
1422 @defun define-error name message &optional parent
1423 In order for a symbol to be an error symbol, it must be defined with
1424 @code{define-error} which takes a parent condition (defaults to @code{error}).
1425 This parent defines the conditions that this kind of error belongs to.
1426 The transitive set of parents always includes the error symbol itself, and the
1427 symbol @code{error}. Because quitting is not considered an error, the set of
1428 parents of @code{quit} is just @code{(quit)}.
1429 @end defun
1430
1431 @cindex peculiar error
1432 In addition to its parents, the error symbol has a @var{message} which
1433 is a string to be printed when that error is signaled but not handled. If that
1434 message is not valid, the error message @samp{peculiar error} is used.
1435 @xref{Definition of signal}.
1436
1437 Internally, the set of parents is stored in the @code{error-conditions}
1438 property of the error symbol and the message is stored in the
1439 @code{error-message} property of the error symbol.
1440
1441 Here is how we define a new error symbol, @code{new-error}:
1442
1443 @example
1444 @group
1445 (define-error 'new-error "A new error" 'my-own-errors)
1446 @end group
1447 @end example
1448
1449 @noindent
1450 This error has several condition names: @code{new-error}, the narrowest
1451 classification; @code{my-own-errors}, which we imagine is a wider
1452 classification; and all the conditions of @code{my-own-errors} which should
1453 include @code{error}, which is the widest of all.
1454
1455 The error string should start with a capital letter but it should
1456 not end with a period. This is for consistency with the rest of Emacs.
1457
1458 Naturally, Emacs will never signal @code{new-error} on its own; only
1459 an explicit call to @code{signal} (@pxref{Definition of signal}) in
1460 your code can do this:
1461
1462 @example
1463 @group
1464 (signal 'new-error '(x y))
1465 @error{} A new error: x, y
1466 @end group
1467 @end example
1468
1469 This error can be handled through any of its condition names.
1470 This example handles @code{new-error} and any other errors in the class
1471 @code{my-own-errors}:
1472
1473 @example
1474 @group
1475 (condition-case foo
1476 (bar nil t)
1477 (my-own-errors nil))
1478 @end group
1479 @end example
1480
1481 The significant way that errors are classified is by their condition
1482 names---the names used to match errors with handlers. An error symbol
1483 serves only as a convenient way to specify the intended error message
1484 and list of condition names. It would be cumbersome to give
1485 @code{signal} a list of condition names rather than one error symbol.
1486
1487 By contrast, using only error symbols without condition names would
1488 seriously decrease the power of @code{condition-case}. Condition names
1489 make it possible to categorize errors at various levels of generality
1490 when you write an error handler. Using error symbols alone would
1491 eliminate all but the narrowest level of classification.
1492
1493 @xref{Standard Errors}, for a list of the main error symbols
1494 and their conditions.
1495
1496 @node Cleanups
1497 @subsection Cleaning Up from Nonlocal Exits
1498 @cindex nonlocal exits, cleaning up
1499
1500 The @code{unwind-protect} construct is essential whenever you
1501 temporarily put a data structure in an inconsistent state; it permits
1502 you to make the data consistent again in the event of an error or
1503 throw. (Another more specific cleanup construct that is used only for
1504 changes in buffer contents is the atomic change group; @ref{Atomic
1505 Changes}.)
1506
1507 @defspec unwind-protect body-form cleanup-forms@dots{}
1508 @cindex cleanup forms
1509 @cindex protected forms
1510 @cindex error cleanup
1511 @cindex unwinding
1512 @code{unwind-protect} executes @var{body-form} with a guarantee that
1513 the @var{cleanup-forms} will be evaluated if control leaves
1514 @var{body-form}, no matter how that happens. @var{body-form} may
1515 complete normally, or execute a @code{throw} out of the
1516 @code{unwind-protect}, or cause an error; in all cases, the
1517 @var{cleanup-forms} will be evaluated.
1518
1519 If @var{body-form} finishes normally, @code{unwind-protect} returns the
1520 value of @var{body-form}, after it evaluates the @var{cleanup-forms}.
1521 If @var{body-form} does not finish, @code{unwind-protect} does not
1522 return any value in the normal sense.
1523
1524 Only @var{body-form} is protected by the @code{unwind-protect}. If any
1525 of the @var{cleanup-forms} themselves exits nonlocally (via a
1526 @code{throw} or an error), @code{unwind-protect} is @emph{not}
1527 guaranteed to evaluate the rest of them. If the failure of one of the
1528 @var{cleanup-forms} has the potential to cause trouble, then protect
1529 it with another @code{unwind-protect} around that form.
1530
1531 The number of currently active @code{unwind-protect} forms counts,
1532 together with the number of local variable bindings, against the limit
1533 @code{max-specpdl-size} (@pxref{Definition of max-specpdl-size,, Local
1534 Variables}).
1535 @end defspec
1536
1537 For example, here we make an invisible buffer for temporary use, and
1538 make sure to kill it before finishing:
1539
1540 @example
1541 @group
1542 (let ((buffer (get-buffer-create " *temp*")))
1543 (with-current-buffer buffer
1544 (unwind-protect
1545 @var{body-form}
1546 (kill-buffer buffer))))
1547 @end group
1548 @end example
1549
1550 @noindent
1551 You might think that we could just as well write @code{(kill-buffer
1552 (current-buffer))} and dispense with the variable @code{buffer}.
1553 However, the way shown above is safer, if @var{body-form} happens to
1554 get an error after switching to a different buffer! (Alternatively,
1555 you could write a @code{save-current-buffer} around @var{body-form},
1556 to ensure that the temporary buffer becomes current again in time to
1557 kill it.)
1558
1559 Emacs includes a standard macro called @code{with-temp-buffer} which
1560 expands into more or less the code shown above (@pxref{Definition of
1561 with-temp-buffer,, Current Buffer}). Several of the macros defined in
1562 this manual use @code{unwind-protect} in this way.
1563
1564 @findex ftp-login
1565 Here is an actual example derived from an FTP package. It creates a
1566 process (@pxref{Processes}) to try to establish a connection to a remote
1567 machine. As the function @code{ftp-login} is highly susceptible to
1568 numerous problems that the writer of the function cannot anticipate, it
1569 is protected with a form that guarantees deletion of the process in the
1570 event of failure. Otherwise, Emacs might fill up with useless
1571 subprocesses.
1572
1573 @example
1574 @group
1575 (let ((win nil))
1576 (unwind-protect
1577 (progn
1578 (setq process (ftp-setup-buffer host file))
1579 (if (setq win (ftp-login process host user password))
1580 (message "Logged in")
1581 (error "Ftp login failed")))
1582 (or win (and process (delete-process process)))))
1583 @end group
1584 @end example
1585
1586 This example has a small bug: if the user types @kbd{C-g} to
1587 quit, and the quit happens immediately after the function
1588 @code{ftp-setup-buffer} returns but before the variable @code{process} is
1589 set, the process will not be killed. There is no easy way to fix this bug,
1590 but at least it is very unlikely.