]> code.delx.au - gnu-emacs/blob - doc/lispref/control.texi
Merge from emacs-24; up to 2012-05-08T14:11:47Z!monnier@iro.umontreal.ca
[gnu-emacs] / doc / lispref / control.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998-1999, 2001-2012 Free Software Foundation, Inc.
4 @c See the file elisp.texi for copying conditions.
5 @node Control Structures
6 @chapter Control Structures
7 @cindex special forms for control structures
8 @cindex control structures
9
10 A Lisp program consists of a set of @dfn{expressions}, or
11 @dfn{forms} (@pxref{Forms}). We control the order of execution of
12 these forms by enclosing them in @dfn{control structures}. Control
13 structures are special forms which control when, whether, or how many
14 times to execute the forms they contain.
15
16 @cindex textual order
17 The simplest order of execution is sequential execution: first form
18 @var{a}, then form @var{b}, and so on. This is what happens when you
19 write several forms in succession in the body of a function, or at top
20 level in a file of Lisp code---the forms are executed in the order
21 written. We call this @dfn{textual order}. For example, if a function
22 body consists of two forms @var{a} and @var{b}, evaluation of the
23 function evaluates first @var{a} and then @var{b}. The result of
24 evaluating @var{b} becomes the value of the function.
25
26 Explicit control structures make possible an order of execution other
27 than sequential.
28
29 Emacs Lisp provides several kinds of control structure, including
30 other varieties of sequencing, conditionals, iteration, and (controlled)
31 jumps---all discussed below. The built-in control structures are
32 special forms since their subforms are not necessarily evaluated or not
33 evaluated sequentially. You can use macros to define your own control
34 structure constructs (@pxref{Macros}).
35
36 @menu
37 * Sequencing:: Evaluation in textual order.
38 * Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}.
39 * Combining Conditions:: @code{and}, @code{or}, @code{not}.
40 * Iteration:: @code{while} loops.
41 * Nonlocal Exits:: Jumping out of a sequence.
42 @end menu
43
44 @node Sequencing
45 @section Sequencing
46
47 Evaluating forms in the order they appear is the most common way
48 control passes from one form to another. In some contexts, such as in a
49 function body, this happens automatically. Elsewhere you must use a
50 control structure construct to do this: @code{progn}, the simplest
51 control construct of Lisp.
52
53 A @code{progn} special form looks like this:
54
55 @example
56 @group
57 (progn @var{a} @var{b} @var{c} @dots{})
58 @end group
59 @end example
60
61 @noindent
62 and it says to execute the forms @var{a}, @var{b}, @var{c}, and so on, in
63 that order. These forms are called the @dfn{body} of the @code{progn} form.
64 The value of the last form in the body becomes the value of the entire
65 @code{progn}. @code{(progn)} returns @code{nil}.
66
67 @cindex implicit @code{progn}
68 In the early days of Lisp, @code{progn} was the only way to execute
69 two or more forms in succession and use the value of the last of them.
70 But programmers found they often needed to use a @code{progn} in the
71 body of a function, where (at that time) only one form was allowed. So
72 the body of a function was made into an ``implicit @code{progn}'':
73 several forms are allowed just as in the body of an actual @code{progn}.
74 Many other control structures likewise contain an implicit @code{progn}.
75 As a result, @code{progn} is not used as much as it was many years ago.
76 It is needed now most often inside an @code{unwind-protect}, @code{and},
77 @code{or}, or in the @var{then}-part of an @code{if}.
78
79 @defspec progn forms@dots{}
80 This special form evaluates all of the @var{forms}, in textual
81 order, returning the result of the final form.
82
83 @example
84 @group
85 (progn (print "The first form")
86 (print "The second form")
87 (print "The third form"))
88 @print{} "The first form"
89 @print{} "The second form"
90 @print{} "The third form"
91 @result{} "The third form"
92 @end group
93 @end example
94 @end defspec
95
96 Two other constructs likewise evaluate a series of forms but return
97 different values:
98
99 @defspec prog1 form1 forms@dots{}
100 This special form evaluates @var{form1} and all of the @var{forms}, in
101 textual order, returning the result of @var{form1}.
102
103 @example
104 @group
105 (prog1 (print "The first form")
106 (print "The second form")
107 (print "The third form"))
108 @print{} "The first form"
109 @print{} "The second form"
110 @print{} "The third form"
111 @result{} "The first form"
112 @end group
113 @end example
114
115 Here is a way to remove the first element from a list in the variable
116 @code{x}, then return the value of that former element:
117
118 @example
119 (prog1 (car x) (setq x (cdr x)))
120 @end example
121 @end defspec
122
123 @defspec prog2 form1 form2 forms@dots{}
124 This special form evaluates @var{form1}, @var{form2}, and all of the
125 following @var{forms}, in textual order, returning the result of
126 @var{form2}.
127
128 @example
129 @group
130 (prog2 (print "The first form")
131 (print "The second form")
132 (print "The third form"))
133 @print{} "The first form"
134 @print{} "The second form"
135 @print{} "The third form"
136 @result{} "The second form"
137 @end group
138 @end example
139 @end defspec
140
141 @node Conditionals
142 @section Conditionals
143 @cindex conditional evaluation
144
145 Conditional control structures choose among alternatives. Emacs Lisp
146 has four conditional forms: @code{if}, which is much the same as in
147 other languages; @code{when} and @code{unless}, which are variants of
148 @code{if}; and @code{cond}, which is a generalized case statement.
149
150 @defspec if condition then-form else-forms@dots{}
151 @code{if} chooses between the @var{then-form} and the @var{else-forms}
152 based on the value of @var{condition}. If the evaluated @var{condition} is
153 non-@code{nil}, @var{then-form} is evaluated and the result returned.
154 Otherwise, the @var{else-forms} are evaluated in textual order, and the
155 value of the last one is returned. (The @var{else} part of @code{if} is
156 an example of an implicit @code{progn}. @xref{Sequencing}.)
157
158 If @var{condition} has the value @code{nil}, and no @var{else-forms} are
159 given, @code{if} returns @code{nil}.
160
161 @code{if} is a special form because the branch that is not selected is
162 never evaluated---it is ignored. Thus, in this example,
163 @code{true} is not printed because @code{print} is never called:
164
165 @example
166 @group
167 (if nil
168 (print 'true)
169 'very-false)
170 @result{} very-false
171 @end group
172 @end example
173 @end defspec
174
175 @defmac when condition then-forms@dots{}
176 This is a variant of @code{if} where there are no @var{else-forms},
177 and possibly several @var{then-forms}. In particular,
178
179 @example
180 (when @var{condition} @var{a} @var{b} @var{c})
181 @end example
182
183 @noindent
184 is entirely equivalent to
185
186 @example
187 (if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
188 @end example
189 @end defmac
190
191 @defmac unless condition forms@dots{}
192 This is a variant of @code{if} where there is no @var{then-form}:
193
194 @example
195 (unless @var{condition} @var{a} @var{b} @var{c})
196 @end example
197
198 @noindent
199 is entirely equivalent to
200
201 @example
202 (if @var{condition} nil
203 @var{a} @var{b} @var{c})
204 @end example
205 @end defmac
206
207 @defspec cond clause@dots{}
208 @code{cond} chooses among an arbitrary number of alternatives. Each
209 @var{clause} in the @code{cond} must be a list. The @sc{car} of this
210 list is the @var{condition}; the remaining elements, if any, the
211 @var{body-forms}. Thus, a clause looks like this:
212
213 @example
214 (@var{condition} @var{body-forms}@dots{})
215 @end example
216
217 @code{cond} tries the clauses in textual order, by evaluating the
218 @var{condition} of each clause. If the value of @var{condition} is
219 non-@code{nil}, the clause ``succeeds''; then @code{cond} evaluates its
220 @var{body-forms}, and the value of the last of @var{body-forms} becomes
221 the value of the @code{cond}. The remaining clauses are ignored.
222
223 If the value of @var{condition} is @code{nil}, the clause ``fails'', so
224 the @code{cond} moves on to the following clause, trying its
225 @var{condition}.
226
227 If every @var{condition} evaluates to @code{nil}, so that every clause
228 fails, @code{cond} returns @code{nil}.
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 value of
238 @var{condition} becomes the value of the @code{cond} form.
239
240 The following example has four clauses, which test for the cases where
241 the value of @code{x} is a number, string, buffer and symbol,
242 respectively:
243
244 @example
245 @group
246 (cond ((numberp x) x)
247 ((stringp x) x)
248 ((bufferp x)
249 (setq temporary-hack x) ; @r{multiple body-forms}
250 (buffer-name x)) ; @r{in one clause}
251 ((symbolp x) (symbol-value x)))
252 @end group
253 @end example
254
255 Often we want to execute the last clause whenever none of the previous
256 clauses was successful. To do this, we use @code{t} as the
257 @var{condition} of the last clause, like this: @code{(t
258 @var{body-forms})}. The form @code{t} evaluates to @code{t}, which is
259 never @code{nil}, so this clause never fails, provided the @code{cond}
260 gets to it at all. For example:
261
262 @example
263 @group
264 (setq a 5)
265 (cond ((eq a 'hack) 'foo)
266 (t "default"))
267 @result{} "default"
268 @end group
269 @end example
270
271 @noindent
272 This @code{cond} expression returns @code{foo} if the value of @code{a}
273 is @code{hack}, and returns the string @code{"default"} otherwise.
274 @end defspec
275
276 Any conditional construct can be expressed with @code{cond} or with
277 @code{if}. Therefore, the choice between them is a matter of style.
278 For example:
279
280 @example
281 @group
282 (if @var{a} @var{b} @var{c})
283 @equiv{}
284 (cond (@var{a} @var{b}) (t @var{c}))
285 @end group
286 @end example
287
288 @node Combining Conditions
289 @section Constructs for Combining Conditions
290
291 This section describes three constructs that are often used together
292 with @code{if} and @code{cond} to express complicated conditions. The
293 constructs @code{and} and @code{or} can also be used individually as
294 kinds of multiple conditional constructs.
295
296 @defun not condition
297 This function tests for the falsehood of @var{condition}. It returns
298 @code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
299 The function @code{not} is identical to @code{null}, and we recommend
300 using the name @code{null} if you are testing for an empty list.
301 @end defun
302
303 @defspec and conditions@dots{}
304 The @code{and} special form tests whether all the @var{conditions} are
305 true. It works by evaluating the @var{conditions} one by one in the
306 order written.
307
308 If any of the @var{conditions} evaluates to @code{nil}, then the result
309 of the @code{and} must be @code{nil} regardless of the remaining
310 @var{conditions}; so @code{and} returns @code{nil} right away, ignoring
311 the remaining @var{conditions}.
312
313 If all the @var{conditions} turn out non-@code{nil}, then the value of
314 the last of them becomes the value of the @code{and} form. Just
315 @code{(and)}, with no @var{conditions}, returns @code{t}, appropriate
316 because all the @var{conditions} turned out non-@code{nil}. (Think
317 about it; which one did not?)
318
319 Here is an example. The first condition returns the integer 1, which is
320 not @code{nil}. Similarly, the second condition returns the integer 2,
321 which is not @code{nil}. The third condition is @code{nil}, so the
322 remaining condition is never evaluated.
323
324 @example
325 @group
326 (and (print 1) (print 2) nil (print 3))
327 @print{} 1
328 @print{} 2
329 @result{} nil
330 @end group
331 @end example
332
333 Here is a more realistic example of using @code{and}:
334
335 @example
336 @group
337 (if (and (consp foo) (eq (car foo) 'x))
338 (message "foo is a list starting with x"))
339 @end group
340 @end example
341
342 @noindent
343 Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
344 @code{nil}, thus avoiding an error.
345
346 @code{and} expressions can also be written using either @code{if} or
347 @code{cond}. Here's how:
348
349 @example
350 @group
351 (and @var{arg1} @var{arg2} @var{arg3})
352 @equiv{}
353 (if @var{arg1} (if @var{arg2} @var{arg3}))
354 @equiv{}
355 (cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
356 @end group
357 @end example
358 @end defspec
359
360 @defspec or conditions@dots{}
361 The @code{or} special form tests whether at least one of the
362 @var{conditions} is true. It works by evaluating all the
363 @var{conditions} one by one in the order written.
364
365 If any of the @var{conditions} evaluates to a non-@code{nil} value, then
366 the result of the @code{or} must be non-@code{nil}; so @code{or} returns
367 right away, ignoring the remaining @var{conditions}. The value it
368 returns is the non-@code{nil} value of the condition just evaluated.
369
370 If all the @var{conditions} turn out @code{nil}, then the @code{or}
371 expression returns @code{nil}. Just @code{(or)}, with no
372 @var{conditions}, returns @code{nil}, appropriate because all the
373 @var{conditions} turned out @code{nil}. (Think about it; which one
374 did not?)
375
376 For example, this expression tests whether @code{x} is either
377 @code{nil} or the integer zero:
378
379 @example
380 (or (eq x nil) (eq x 0))
381 @end example
382
383 Like the @code{and} construct, @code{or} can be written in terms of
384 @code{cond}. For example:
385
386 @example
387 @group
388 (or @var{arg1} @var{arg2} @var{arg3})
389 @equiv{}
390 (cond (@var{arg1})
391 (@var{arg2})
392 (@var{arg3}))
393 @end group
394 @end example
395
396 You could almost write @code{or} in terms of @code{if}, but not quite:
397
398 @example
399 @group
400 (if @var{arg1} @var{arg1}
401 (if @var{arg2} @var{arg2}
402 @var{arg3}))
403 @end group
404 @end example
405
406 @noindent
407 This is not completely equivalent because it can evaluate @var{arg1} or
408 @var{arg2} twice. By contrast, @code{(or @var{arg1} @var{arg2}
409 @var{arg3})} never evaluates any argument more than once.
410 @end defspec
411
412 @node Iteration
413 @section Iteration
414 @cindex iteration
415 @cindex recursion
416
417 Iteration means executing part of a program repetitively. For
418 example, you might want to repeat some computation once for each element
419 of a list, or once for each integer from 0 to @var{n}. You can do this
420 in Emacs Lisp with the special form @code{while}:
421
422 @defspec while condition forms@dots{}
423 @code{while} first evaluates @var{condition}. If the result is
424 non-@code{nil}, it evaluates @var{forms} in textual order. Then it
425 reevaluates @var{condition}, and if the result is non-@code{nil}, it
426 evaluates @var{forms} again. This process repeats until @var{condition}
427 evaluates to @code{nil}.
428
429 There is no limit on the number of iterations that may occur. The loop
430 will continue until either @var{condition} evaluates to @code{nil} or
431 until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
432
433 The value of a @code{while} form is always @code{nil}.
434
435 @example
436 @group
437 (setq num 0)
438 @result{} 0
439 @end group
440 @group
441 (while (< num 4)
442 (princ (format "Iteration %d." num))
443 (setq num (1+ num)))
444 @print{} Iteration 0.
445 @print{} Iteration 1.
446 @print{} Iteration 2.
447 @print{} Iteration 3.
448 @result{} nil
449 @end group
450 @end example
451
452 To write a ``repeat...until'' loop, which will execute something on each
453 iteration and then do the end-test, put the body followed by the
454 end-test in a @code{progn} as the first argument of @code{while}, as
455 shown here:
456
457 @example
458 @group
459 (while (progn
460 (forward-line 1)
461 (not (looking-at "^$"))))
462 @end group
463 @end example
464
465 @noindent
466 This moves forward one line and continues moving by lines until it
467 reaches an empty line. It is peculiar in that the @code{while} has no
468 body, just the end test (which also does the real work of moving point).
469 @end defspec
470
471 The @code{dolist} and @code{dotimes} macros provide convenient ways to
472 write two common kinds of loops.
473
474 @defmac dolist (var list [result]) body@dots{}
475 This construct executes @var{body} once for each element of
476 @var{list}, binding the variable @var{var} locally to hold the current
477 element. Then it returns the value of evaluating @var{result}, or
478 @code{nil} if @var{result} is omitted. For example, here is how you
479 could use @code{dolist} to define the @code{reverse} function:
480
481 @example
482 (defun reverse (list)
483 (let (value)
484 (dolist (elt list value)
485 (setq value (cons elt value)))))
486 @end example
487 @end defmac
488
489 @defmac dotimes (var count [result]) body@dots{}
490 This construct executes @var{body} once for each integer from 0
491 (inclusive) to @var{count} (exclusive), binding the variable @var{var}
492 to the integer for the current iteration. Then it returns the value
493 of evaluating @var{result}, or @code{nil} if @var{result} is omitted.
494 Here is an example of using @code{dotimes} to do something 100 times:
495
496 @example
497 (dotimes (i 100)
498 (insert "I will not obey absurd orders\n"))
499 @end example
500 @end defmac
501
502 @node Nonlocal Exits
503 @section Nonlocal Exits
504 @cindex nonlocal exits
505
506 A @dfn{nonlocal exit} is a transfer of control from one point in a
507 program to another remote point. Nonlocal exits can occur in Emacs Lisp
508 as a result of errors; you can also use them under explicit control.
509 Nonlocal exits unbind all variable bindings made by the constructs being
510 exited.
511
512 @menu
513 * Catch and Throw:: Nonlocal exits for the program's own purposes.
514 * Examples of Catch:: Showing how such nonlocal exits can be written.
515 * Errors:: How errors are signaled and handled.
516 * Cleanups:: Arranging to run a cleanup form if an error happens.
517 @end menu
518
519 @node Catch and Throw
520 @subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
521
522 Most control constructs affect only the flow of control within the
523 construct itself. The function @code{throw} is the exception to this
524 rule of normal program execution: it performs a nonlocal exit on
525 request. (There are other exceptions, but they are for error handling
526 only.) @code{throw} is used inside a @code{catch}, and jumps back to
527 that @code{catch}. For example:
528
529 @example
530 @group
531 (defun foo-outer ()
532 (catch 'foo
533 (foo-inner)))
534
535 (defun foo-inner ()
536 @dots{}
537 (if x
538 (throw 'foo t))
539 @dots{})
540 @end group
541 @end example
542
543 @noindent
544 The @code{throw} form, if executed, transfers control straight back to
545 the corresponding @code{catch}, which returns immediately. The code
546 following the @code{throw} is not executed. The second argument of
547 @code{throw} is used as the return value of the @code{catch}.
548
549 The function @code{throw} finds the matching @code{catch} based on the
550 first argument: it searches for a @code{catch} whose first argument is
551 @code{eq} to the one specified in the @code{throw}. If there is more
552 than one applicable @code{catch}, the innermost one takes precedence.
553 Thus, in the above example, the @code{throw} specifies @code{foo}, and
554 the @code{catch} in @code{foo-outer} specifies the same symbol, so that
555 @code{catch} is the applicable one (assuming there is no other matching
556 @code{catch} in between).
557
558 Executing @code{throw} exits all Lisp constructs up to the matching
559 @code{catch}, including function calls. When binding constructs such
560 as @code{let} or function calls are exited in this way, the bindings
561 are unbound, just as they are when these constructs exit normally
562 (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
563 and position saved by @code{save-excursion} (@pxref{Excursions}), and
564 the narrowing status saved by @code{save-restriction}. It also runs
565 any cleanups established with the @code{unwind-protect} special form
566 when it exits that form (@pxref{Cleanups}).
567
568 The @code{throw} need not appear lexically within the @code{catch}
569 that it jumps to. It can equally well be called from another function
570 called within the @code{catch}. As long as the @code{throw} takes place
571 chronologically after entry to the @code{catch}, and chronologically
572 before exit from it, it has access to that @code{catch}. This is why
573 @code{throw} can be used in commands such as @code{exit-recursive-edit}
574 that throw back to the editor command loop (@pxref{Recursive Editing}).
575
576 @cindex CL note---only @code{throw} in Emacs
577 @quotation
578 @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
579 have several ways of transferring control nonsequentially: @code{return},
580 @code{return-from}, and @code{go}, for example. Emacs Lisp has only
581 @code{throw}.
582 @end quotation
583
584 @defspec catch tag body@dots{}
585 @cindex tag on run time stack
586 @code{catch} establishes a return point for the @code{throw} function.
587 The return point is distinguished from other such return points by
588 @var{tag}, which may be any Lisp object except @code{nil}. The argument
589 @var{tag} is evaluated normally before the return point is established.
590
591 With the return point in effect, @code{catch} evaluates the forms of the
592 @var{body} in textual order. If the forms execute normally (without
593 error or nonlocal exit) the value of the last body form is returned from
594 the @code{catch}.
595
596 If a @code{throw} is executed during the execution of @var{body},
597 specifying the same value @var{tag}, the @code{catch} form exits
598 immediately; the value it returns is whatever was specified as the
599 second argument of @code{throw}.
600 @end defspec
601
602 @defun throw tag value
603 The purpose of @code{throw} is to return from a return point previously
604 established with @code{catch}. The argument @var{tag} is used to choose
605 among the various existing return points; it must be @code{eq} to the value
606 specified in the @code{catch}. If multiple return points match @var{tag},
607 the innermost one is used.
608
609 The argument @var{value} is used as the value to return from that
610 @code{catch}.
611
612 @kindex no-catch
613 If no return point is in effect with tag @var{tag}, then a @code{no-catch}
614 error is signaled with data @code{(@var{tag} @var{value})}.
615 @end defun
616
617 @node Examples of Catch
618 @subsection Examples of @code{catch} and @code{throw}
619
620 One way to use @code{catch} and @code{throw} is to exit from a doubly
621 nested loop. (In most languages, this would be done with a ``goto''.)
622 Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
623 varying from 0 to 9:
624
625 @example
626 @group
627 (defun search-foo ()
628 (catch 'loop
629 (let ((i 0))
630 (while (< i 10)
631 (let ((j 0))
632 (while (< j 10)
633 (if (foo i j)
634 (throw 'loop (list i j)))
635 (setq j (1+ j))))
636 (setq i (1+ i))))))
637 @end group
638 @end example
639
640 @noindent
641 If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
642 list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
643 @code{catch} returns normally, and the value is @code{nil}, since that
644 is the result of the @code{while}.
645
646 Here are two tricky examples, slightly different, showing two
647 return points at once. First, two return points with the same tag,
648 @code{hack}:
649
650 @example
651 @group
652 (defun catch2 (tag)
653 (catch tag
654 (throw 'hack 'yes)))
655 @result{} catch2
656 @end group
657
658 @group
659 (catch 'hack
660 (print (catch2 'hack))
661 'no)
662 @print{} yes
663 @result{} no
664 @end group
665 @end example
666
667 @noindent
668 Since both return points have tags that match the @code{throw}, it goes to
669 the inner one, the one established in @code{catch2}. Therefore,
670 @code{catch2} returns normally with value @code{yes}, and this value is
671 printed. Finally the second body form in the outer @code{catch}, which is
672 @code{'no}, is evaluated and returned from the outer @code{catch}.
673
674 Now let's change the argument given to @code{catch2}:
675
676 @example
677 @group
678 (catch 'hack
679 (print (catch2 'quux))
680 'no)
681 @result{} yes
682 @end group
683 @end example
684
685 @noindent
686 We still have two return points, but this time only the outer one has
687 the tag @code{hack}; the inner one has the tag @code{quux} instead.
688 Therefore, @code{throw} makes the outer @code{catch} return the value
689 @code{yes}. The function @code{print} is never called, and the
690 body-form @code{'no} is never evaluated.
691
692 @node Errors
693 @subsection Errors
694 @cindex errors
695
696 When Emacs Lisp attempts to evaluate a form that, for some reason,
697 cannot be evaluated, it @dfn{signals} an @dfn{error}.
698
699 When an error is signaled, Emacs's default reaction is to print an
700 error message and terminate execution of the current command. This is
701 the right thing to do in most cases, such as if you type @kbd{C-f} at
702 the end of the buffer.
703
704 In complicated programs, simple termination may not be what you want.
705 For example, the program may have made temporary changes in data
706 structures, or created temporary buffers that should be deleted before
707 the program is finished. In such cases, you would use
708 @code{unwind-protect} to establish @dfn{cleanup expressions} to be
709 evaluated in case of error. (@xref{Cleanups}.) Occasionally, you may
710 wish the program to continue execution despite an error in a subroutine.
711 In these cases, you would use @code{condition-case} to establish
712 @dfn{error handlers} to recover control in case of error.
713
714 Resist the temptation to use error handling to transfer control from
715 one part of the program to another; use @code{catch} and @code{throw}
716 instead. @xref{Catch and Throw}.
717
718 @menu
719 * Signaling Errors:: How to report an error.
720 * Processing of Errors:: What Emacs does when you report an error.
721 * Handling Errors:: How you can trap errors and continue execution.
722 * Error Symbols:: How errors are classified for trapping them.
723 @end menu
724
725 @node Signaling Errors
726 @subsubsection How to Signal an Error
727 @cindex signaling errors
728
729 @dfn{Signaling} an error means beginning error processing. Error
730 processing normally aborts all or part of the running program and
731 returns to a point that is set up to handle the error
732 (@pxref{Processing of Errors}). Here we describe how to signal an
733 error.
734
735 Most errors are signaled ``automatically'' within Lisp primitives
736 which you call for other purposes, such as if you try to take the
737 @sc{car} of an integer or move forward a character at the end of the
738 buffer. You can also signal errors explicitly with the functions
739 @code{error} and @code{signal}.
740
741 Quitting, which happens when the user types @kbd{C-g}, is not
742 considered an error, but it is handled almost like an error.
743 @xref{Quitting}.
744
745 Every error specifies an error message, one way or another. The
746 message should state what is wrong (``File does not exist''), not how
747 things ought to be (``File must exist''). The convention in Emacs
748 Lisp is that error messages should start with a capital letter, but
749 should not end with any sort of punctuation.
750
751 @defun error format-string &rest args
752 This function signals an error with an error message constructed by
753 applying @code{format} (@pxref{Formatting Strings}) to
754 @var{format-string} and @var{args}.
755
756 These examples show typical uses of @code{error}:
757
758 @example
759 @group
760 (error "That is an error -- try something else")
761 @error{} That is an error -- try something else
762 @end group
763
764 @group
765 (error "You have committed %d errors" 10)
766 @error{} You have committed 10 errors
767 @end group
768 @end example
769
770 @code{error} works by calling @code{signal} with two arguments: the
771 error symbol @code{error}, and a list containing the string returned by
772 @code{format}.
773
774 @strong{Warning:} If you want to use your own string as an error message
775 verbatim, don't just write @code{(error @var{string})}. If @var{string}
776 contains @samp{%}, it will be interpreted as a format specifier, with
777 undesirable results. Instead, use @code{(error "%s" @var{string})}.
778 @end defun
779
780 @defun signal error-symbol data
781 @anchor{Definition of signal}
782 This function signals an error named by @var{error-symbol}. The
783 argument @var{data} is a list of additional Lisp objects relevant to
784 the circumstances of the error.
785
786 The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
787 bearing a property @code{error-conditions} whose value is a list of
788 condition names. This is how Emacs Lisp classifies different sorts of
789 errors. @xref{Error Symbols}, for a description of error symbols,
790 error conditions and condition names.
791
792 If the error is not handled, the two arguments are used in printing
793 the error message. Normally, this error message is provided by the
794 @code{error-message} property of @var{error-symbol}. If @var{data} is
795 non-@code{nil}, this is followed by a colon and a comma separated list
796 of the unevaluated elements of @var{data}. For @code{error}, the
797 error message is the @sc{car} of @var{data} (that must be a string).
798 Subcategories of @code{file-error} are handled specially.
799
800 The number and significance of the objects in @var{data} depends on
801 @var{error-symbol}. For example, with a @code{wrong-type-argument} error,
802 there should be two objects in the list: a predicate that describes the type
803 that was expected, and the object that failed to fit that type.
804
805 Both @var{error-symbol} and @var{data} are available to any error
806 handlers that handle the error: @code{condition-case} binds a local
807 variable to a list of the form @code{(@var{error-symbol} .@:
808 @var{data})} (@pxref{Handling Errors}).
809
810 The function @code{signal} never returns.
811 @c (though in older Emacs versions it sometimes could).
812
813 @example
814 @group
815 (signal 'wrong-number-of-arguments '(x y))
816 @error{} Wrong number of arguments: x, y
817 @end group
818
819 @group
820 (signal 'no-such-error '("My unknown error condition"))
821 @error{} peculiar error: "My unknown error condition"
822 @end group
823 @end example
824 @end defun
825
826 @cindex CL note---no continuable errors
827 @quotation
828 @b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
829 concept of continuable errors.
830 @end quotation
831
832 @node Processing of Errors
833 @subsubsection How Emacs Processes Errors
834
835 When an error is signaled, @code{signal} searches for an active
836 @dfn{handler} for the error. A handler is a sequence of Lisp
837 expressions designated to be executed if an error happens in part of the
838 Lisp program. If the error has an applicable handler, the handler is
839 executed, and control resumes following the handler. The handler
840 executes in the environment of the @code{condition-case} that
841 established it; all functions called within that @code{condition-case}
842 have already been exited, and the handler cannot return to them.
843
844 If there is no applicable handler for the error, it terminates the
845 current command and returns control to the editor command loop. (The
846 command loop has an implicit handler for all kinds of errors.) The
847 command loop's handler uses the error symbol and associated data to
848 print an error message. You can use the variable
849 @code{command-error-function} to control how this is done:
850
851 @defvar command-error-function
852 This variable, if non-@code{nil}, specifies a function to use to
853 handle errors that return control to the Emacs command loop. The
854 function should take three arguments: @var{data}, a list of the same
855 form that @code{condition-case} would bind to its variable;
856 @var{context}, a string describing the situation in which the error
857 occurred, or (more often) @code{nil}; and @var{caller}, the Lisp
858 function which called the primitive that signaled the error.
859 @end defvar
860
861 @cindex @code{debug-on-error} use
862 An error that has no explicit handler may call the Lisp debugger. The
863 debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
864 Debugging}) is non-@code{nil}. Unlike error handlers, the debugger runs
865 in the environment of the error, so that you can examine values of
866 variables precisely as they were at the time of the error.
867
868 @node Handling Errors
869 @subsubsection Writing Code to Handle Errors
870 @cindex error handler
871 @cindex handling errors
872
873 The usual effect of signaling an error is to terminate the command
874 that is running and return immediately to the Emacs editor command loop.
875 You can arrange to trap errors occurring in a part of your program by
876 establishing an error handler, with the special form
877 @code{condition-case}. A simple example looks like this:
878
879 @example
880 @group
881 (condition-case nil
882 (delete-file filename)
883 (error nil))
884 @end group
885 @end example
886
887 @noindent
888 This deletes the file named @var{filename}, catching any error and
889 returning @code{nil} if an error occurs. (You can use the macro
890 @code{ignore-errors} for a simple case like this; see below.)
891
892 The @code{condition-case} construct is often used to trap errors that
893 are predictable, such as failure to open a file in a call to
894 @code{insert-file-contents}. It is also used to trap errors that are
895 totally unpredictable, such as when the program evaluates an expression
896 read from the user.
897
898 The second argument of @code{condition-case} is called the
899 @dfn{protected form}. (In the example above, the protected form is a
900 call to @code{delete-file}.) The error handlers go into effect when
901 this form begins execution and are deactivated when this form returns.
902 They remain in effect for all the intervening time. In particular, they
903 are in effect during the execution of functions called by this form, in
904 their subroutines, and so on. This is a good thing, since, strictly
905 speaking, errors can be signaled only by Lisp primitives (including
906 @code{signal} and @code{error}) called by the protected form, not by the
907 protected form itself.
908
909 The arguments after the protected form are handlers. Each handler
910 lists one or more @dfn{condition names} (which are symbols) to specify
911 which errors it will handle. The error symbol specified when an error
912 is signaled also defines a list of condition names. A handler applies
913 to an error if they have any condition names in common. In the example
914 above, there is one handler, and it specifies one condition name,
915 @code{error}, which covers all errors.
916
917 The search for an applicable handler checks all the established handlers
918 starting with the most recently established one. Thus, if two nested
919 @code{condition-case} forms offer to handle the same error, the inner of
920 the two gets to handle it.
921
922 If an error is handled by some @code{condition-case} form, this
923 ordinarily prevents the debugger from being run, even if
924 @code{debug-on-error} says this error should invoke the debugger.
925
926 If you want to be able to debug errors that are caught by a
927 @code{condition-case}, set the variable @code{debug-on-signal} to a
928 non-@code{nil} value. You can also specify that a particular handler
929 should let the debugger run first, by writing @code{debug} among the
930 conditions, like this:
931
932 @example
933 @group
934 (condition-case nil
935 (delete-file filename)
936 ((debug error) nil))
937 @end group
938 @end example
939
940 @noindent
941 The effect of @code{debug} here is only to prevent
942 @code{condition-case} from suppressing the call to the debugger. Any
943 given error will invoke the debugger only if @code{debug-on-error} and
944 the other usual filtering mechanisms say it should. @xref{Error Debugging}.
945
946 @defmac condition-case-unless-debug var protected-form handlers@dots{}
947 The macro @code{condition-case-unless-debug} provides another way to
948 handle debugging of such forms. It behaves exactly like
949 @code{condition-case}, unless the variable @code{debug-on-error} is
950 non-@code{nil}, in which case it does not handle any errors at all.
951 @end defmac
952
953 Once Emacs decides that a certain handler handles the error, it
954 returns control to that handler. To do so, Emacs unbinds all variable
955 bindings made by binding constructs that are being exited, and
956 executes the cleanups of all @code{unwind-protect} forms that are
957 being exited. Once control arrives at the handler, the body of the
958 handler executes normally.
959
960 After execution of the handler body, execution returns from the
961 @code{condition-case} form. Because the protected form is exited
962 completely before execution of the handler, the handler cannot resume
963 execution at the point of the error, nor can it examine variable
964 bindings that were made within the protected form. All it can do is
965 clean up and proceed.
966
967 Error signaling and handling have some resemblance to @code{throw} and
968 @code{catch} (@pxref{Catch and Throw}), but they are entirely separate
969 facilities. An error cannot be caught by a @code{catch}, and a
970 @code{throw} cannot be handled by an error handler (though using
971 @code{throw} when there is no suitable @code{catch} signals an error
972 that can be handled).
973
974 @defspec condition-case var protected-form handlers@dots{}
975 This special form establishes the error handlers @var{handlers} around
976 the execution of @var{protected-form}. If @var{protected-form} executes
977 without error, the value it returns becomes the value of the
978 @code{condition-case} form; in this case, the @code{condition-case} has
979 no effect. The @code{condition-case} form makes a difference when an
980 error occurs during @var{protected-form}.
981
982 Each of the @var{handlers} is a list of the form @code{(@var{conditions}
983 @var{body}@dots{})}. Here @var{conditions} is an error condition name
984 to be handled, or a list of condition names (which can include @code{debug}
985 to allow the debugger to run before the handler); @var{body} is one or more
986 Lisp expressions to be executed when this handler handles an error.
987 Here are examples of handlers:
988
989 @example
990 @group
991 (error nil)
992
993 (arith-error (message "Division by zero"))
994
995 ((arith-error file-error)
996 (message
997 "Either division by zero or failure to open a file"))
998 @end group
999 @end example
1000
1001 Each error that occurs has an @dfn{error symbol} that describes what
1002 kind of error it is. The @code{error-conditions} property of this
1003 symbol is a list of condition names (@pxref{Error Symbols}). Emacs
1004 searches all the active @code{condition-case} forms for a handler that
1005 specifies one or more of these condition names; the innermost matching
1006 @code{condition-case} handles the error. Within this
1007 @code{condition-case}, the first applicable handler handles the error.
1008
1009 After executing the body of the handler, the @code{condition-case}
1010 returns normally, using the value of the last form in the handler body
1011 as the overall value.
1012
1013 @cindex error description
1014 The argument @var{var} is a variable. @code{condition-case} does not
1015 bind this variable when executing the @var{protected-form}, only when it
1016 handles an error. At that time, it binds @var{var} locally to an
1017 @dfn{error description}, which is a list giving the particulars of the
1018 error. The error description has the form @code{(@var{error-symbol}
1019 . @var{data})}. The handler can refer to this list to decide what to
1020 do. For example, if the error is for failure opening a file, the file
1021 name is the second element of @var{data}---the third element of the
1022 error description.
1023
1024 If @var{var} is @code{nil}, that means no variable is bound. Then the
1025 error symbol and associated data are not available to the handler.
1026
1027 @cindex rethrow a signal
1028 Sometimes it is necessary to re-throw a signal caught by
1029 @code{condition-case}, for some outer-level handler to catch. Here's
1030 how to do that:
1031
1032 @example
1033 (signal (car err) (cdr err))
1034 @end example
1035
1036 @noindent
1037 where @code{err} is the error description variable, the first argument
1038 to @code{condition-case} whose error condition you want to re-throw.
1039 @xref{Definition of signal}.
1040 @end defspec
1041
1042 @defun error-message-string error-descriptor
1043 This function returns the error message string for a given error
1044 descriptor. It is useful if you want to handle an error by printing the
1045 usual error message for that error. @xref{Definition of signal}.
1046 @end defun
1047
1048 @cindex @code{arith-error} example
1049 Here is an example of using @code{condition-case} to handle the error
1050 that results from dividing by zero. The handler displays the error
1051 message (but without a beep), then returns a very large number.
1052
1053 @example
1054 @group
1055 (defun safe-divide (dividend divisor)
1056 (condition-case err
1057 ;; @r{Protected form.}
1058 (/ dividend divisor)
1059 @end group
1060 @group
1061 ;; @r{The handler.}
1062 (arith-error ; @r{Condition.}
1063 ;; @r{Display the usual message for this error.}
1064 (message "%s" (error-message-string err))
1065 1000000)))
1066 @result{} safe-divide
1067 @end group
1068
1069 @group
1070 (safe-divide 5 0)
1071 @print{} Arithmetic error: (arith-error)
1072 @result{} 1000000
1073 @end group
1074 @end example
1075
1076 @noindent
1077 The handler specifies condition name @code{arith-error} so that it
1078 will handle only division-by-zero errors. Other kinds of errors will
1079 not be handled (by this @code{condition-case}). Thus:
1080
1081 @example
1082 @group
1083 (safe-divide nil 3)
1084 @error{} Wrong type argument: number-or-marker-p, nil
1085 @end group
1086 @end example
1087
1088 Here is a @code{condition-case} that catches all kinds of errors,
1089 including those from @code{error}:
1090
1091 @example
1092 @group
1093 (setq baz 34)
1094 @result{} 34
1095 @end group
1096
1097 @group
1098 (condition-case err
1099 (if (eq baz 35)
1100 t
1101 ;; @r{This is a call to the function @code{error}.}
1102 (error "Rats! The variable %s was %s, not 35" 'baz baz))
1103 ;; @r{This is the handler; it is not a form.}
1104 (error (princ (format "The error was: %s" err))
1105 2))
1106 @print{} The error was: (error "Rats! The variable baz was 34, not 35")
1107 @result{} 2
1108 @end group
1109 @end example
1110
1111 @defmac ignore-errors body@dots{}
1112 This construct executes @var{body}, ignoring any errors that occur
1113 during its execution. If the execution is without error,
1114 @code{ignore-errors} returns the value of the last form in @var{body};
1115 otherwise, it returns @code{nil}.
1116
1117 Here's the example at the beginning of this subsection rewritten using
1118 @code{ignore-errors}:
1119
1120 @example
1121 @group
1122 (ignore-errors
1123 (delete-file filename))
1124 @end group
1125 @end example
1126 @end defmac
1127
1128 @defmac with-demoted-errors body@dots{}
1129 This macro is like a milder version of @code{ignore-errors}. Rather
1130 than suppressing errors altogether, it converts them into messages.
1131 Use this form around code that is not expected to signal errors, but
1132 should be robust if one does occur. Note that this macro uses
1133 @code{condition-case-unless-debug} rather than @code{condition-case}.
1134 @end defmac
1135
1136 @node Error Symbols
1137 @subsubsection Error Symbols and Condition Names
1138 @cindex error symbol
1139 @cindex error name
1140 @cindex condition name
1141 @cindex user-defined error
1142 @kindex error-conditions
1143
1144 When you signal an error, you specify an @dfn{error symbol} to specify
1145 the kind of error you have in mind. Each error has one and only one
1146 error symbol to categorize it. This is the finest classification of
1147 errors defined by the Emacs Lisp language.
1148
1149 These narrow classifications are grouped into a hierarchy of wider
1150 classes called @dfn{error conditions}, identified by @dfn{condition
1151 names}. The narrowest such classes belong to the error symbols
1152 themselves: each error symbol is also a condition name. There are also
1153 condition names for more extensive classes, up to the condition name
1154 @code{error} which takes in all kinds of errors (but not @code{quit}).
1155 Thus, each error has one or more condition names: @code{error}, the
1156 error symbol if that is distinct from @code{error}, and perhaps some
1157 intermediate classifications.
1158
1159 In order for a symbol to be an error symbol, it must have an
1160 @code{error-conditions} property which gives a list of condition names.
1161 This list defines the conditions that this kind of error belongs to.
1162 (The error symbol itself, and the symbol @code{error}, should always be
1163 members of this list.) Thus, the hierarchy of condition names is
1164 defined by the @code{error-conditions} properties of the error symbols.
1165 Because quitting is not considered an error, the value of the
1166 @code{error-conditions} property of @code{quit} is just @code{(quit)}.
1167
1168 @cindex peculiar error
1169 In addition to the @code{error-conditions} list, the error symbol
1170 should have an @code{error-message} property whose value is a string to
1171 be printed when that error is signaled but not handled. If the
1172 error symbol has no @code{error-message} property or if the
1173 @code{error-message} property exists, but is not a string, the error
1174 message @samp{peculiar error} is used. @xref{Definition of signal}.
1175
1176 Here is how we define a new error symbol, @code{new-error}:
1177
1178 @example
1179 @group
1180 (put 'new-error
1181 'error-conditions
1182 '(error my-own-errors new-error))
1183 @result{} (error my-own-errors new-error)
1184 @end group
1185 @group
1186 (put 'new-error 'error-message "A new error")
1187 @result{} "A new error"
1188 @end group
1189 @end example
1190
1191 @noindent
1192 This error has three condition names: @code{new-error}, the narrowest
1193 classification; @code{my-own-errors}, which we imagine is a wider
1194 classification; and @code{error}, which is the widest of all.
1195
1196 The error string should start with a capital letter but it should
1197 not end with a period. This is for consistency with the rest of Emacs.
1198
1199 Naturally, Emacs will never signal @code{new-error} on its own; only
1200 an explicit call to @code{signal} (@pxref{Definition of signal}) in
1201 your code can do this:
1202
1203 @example
1204 @group
1205 (signal 'new-error '(x y))
1206 @error{} A new error: x, y
1207 @end group
1208 @end example
1209
1210 This error can be handled through any of the three condition names.
1211 This example handles @code{new-error} and any other errors in the class
1212 @code{my-own-errors}:
1213
1214 @example
1215 @group
1216 (condition-case foo
1217 (bar nil t)
1218 (my-own-errors nil))
1219 @end group
1220 @end example
1221
1222 The significant way that errors are classified is by their condition
1223 names---the names used to match errors with handlers. An error symbol
1224 serves only as a convenient way to specify the intended error message
1225 and list of condition names. It would be cumbersome to give
1226 @code{signal} a list of condition names rather than one error symbol.
1227
1228 By contrast, using only error symbols without condition names would
1229 seriously decrease the power of @code{condition-case}. Condition names
1230 make it possible to categorize errors at various levels of generality
1231 when you write an error handler. Using error symbols alone would
1232 eliminate all but the narrowest level of classification.
1233
1234 @xref{Standard Errors}, for a list of the main error symbols
1235 and their conditions.
1236
1237 @node Cleanups
1238 @subsection Cleaning Up from Nonlocal Exits
1239
1240 The @code{unwind-protect} construct is essential whenever you
1241 temporarily put a data structure in an inconsistent state; it permits
1242 you to make the data consistent again in the event of an error or
1243 throw. (Another more specific cleanup construct that is used only for
1244 changes in buffer contents is the atomic change group; @ref{Atomic
1245 Changes}.)
1246
1247 @defspec unwind-protect body-form cleanup-forms@dots{}
1248 @cindex cleanup forms
1249 @cindex protected forms
1250 @cindex error cleanup
1251 @cindex unwinding
1252 @code{unwind-protect} executes @var{body-form} with a guarantee that
1253 the @var{cleanup-forms} will be evaluated if control leaves
1254 @var{body-form}, no matter how that happens. @var{body-form} may
1255 complete normally, or execute a @code{throw} out of the
1256 @code{unwind-protect}, or cause an error; in all cases, the
1257 @var{cleanup-forms} will be evaluated.
1258
1259 If @var{body-form} finishes normally, @code{unwind-protect} returns the
1260 value of @var{body-form}, after it evaluates the @var{cleanup-forms}.
1261 If @var{body-form} does not finish, @code{unwind-protect} does not
1262 return any value in the normal sense.
1263
1264 Only @var{body-form} is protected by the @code{unwind-protect}. If any
1265 of the @var{cleanup-forms} themselves exits nonlocally (via a
1266 @code{throw} or an error), @code{unwind-protect} is @emph{not}
1267 guaranteed to evaluate the rest of them. If the failure of one of the
1268 @var{cleanup-forms} has the potential to cause trouble, then protect
1269 it with another @code{unwind-protect} around that form.
1270
1271 The number of currently active @code{unwind-protect} forms counts,
1272 together with the number of local variable bindings, against the limit
1273 @code{max-specpdl-size} (@pxref{Definition of max-specpdl-size,, Local
1274 Variables}).
1275 @end defspec
1276
1277 For example, here we make an invisible buffer for temporary use, and
1278 make sure to kill it before finishing:
1279
1280 @example
1281 @group
1282 (let ((buffer (get-buffer-create " *temp*")))
1283 (with-current-buffer buffer
1284 (unwind-protect
1285 @var{body-form}
1286 (kill-buffer buffer))))
1287 @end group
1288 @end example
1289
1290 @noindent
1291 You might think that we could just as well write @code{(kill-buffer
1292 (current-buffer))} and dispense with the variable @code{buffer}.
1293 However, the way shown above is safer, if @var{body-form} happens to
1294 get an error after switching to a different buffer! (Alternatively,
1295 you could write a @code{save-current-buffer} around @var{body-form},
1296 to ensure that the temporary buffer becomes current again in time to
1297 kill it.)
1298
1299 Emacs includes a standard macro called @code{with-temp-buffer} which
1300 expands into more or less the code shown above (@pxref{Definition of
1301 with-temp-buffer,, Current Buffer}). Several of the macros defined in
1302 this manual use @code{unwind-protect} in this way.
1303
1304 @findex ftp-login
1305 Here is an actual example derived from an FTP package. It creates a
1306 process (@pxref{Processes}) to try to establish a connection to a remote
1307 machine. As the function @code{ftp-login} is highly susceptible to
1308 numerous problems that the writer of the function cannot anticipate, it
1309 is protected with a form that guarantees deletion of the process in the
1310 event of failure. Otherwise, Emacs might fill up with useless
1311 subprocesses.
1312
1313 @example
1314 @group
1315 (let ((win nil))
1316 (unwind-protect
1317 (progn
1318 (setq process (ftp-setup-buffer host file))
1319 (if (setq win (ftp-login process host user password))
1320 (message "Logged in")
1321 (error "Ftp login failed")))
1322 (or win (and process (delete-process process)))))
1323 @end group
1324 @end example
1325
1326 This example has a small bug: if the user types @kbd{C-g} to
1327 quit, and the quit happens immediately after the function
1328 @code{ftp-setup-buffer} returns but before the variable @code{process} is
1329 set, the process will not be killed. There is no easy way to fix this bug,
1330 but at least it is very unlikely.