Commit 83ac6b45 authored by Richard M. Stallman's avatar Richard M. Stallman
Browse files

Initial revision

parent a0acfc98
@c -*-texinfo-*-
@c This is part of the GNU Emacs Lisp Reference Manual.
@c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
@c See the file elisp.texi for copying conditions.
@setfilename ../info/control
@node Control Structures, Variables, Evaluation, Top
@chapter Control Structures
@cindex special forms for control structures
@cindex control structures
A Lisp program consists of expressions or @dfn{forms} (@pxref{Forms}).
We control the order of execution of the forms by enclosing them in
@dfn{control structures}. Control structures are special forms which
control when, whether, or how many times to execute the forms they contain.
The simplest control structure is sequential execution: first form
@var{a}, then form @var{b}, and so on. This is what happens when you
write several forms in succession in the body of a function, or at top
level in a file of Lisp code---the forms are executed in the order they
are written. We call this @dfn{textual order}. For example, if a
function body consists of two forms @var{a} and @var{b}, evaluation of
the function evaluates first @var{a} and then @var{b}, and the
function's value is the value of @var{b}.
Emacs Lisp provides several kinds of control structure, including
other varieties of sequencing, function calls, conditionals, iteration,
and (controlled) jumps. The built-in control structures are special
forms since their subforms are not necessarily evaluated. You can use
macros to define your own control structure constructs (@pxref{Macros}).
* Sequencing:: Evaluation in textual order.
* Conditionals:: @code{if}, @code{cond}.
* Combining Conditions:: @code{and}, @code{or}, @code{not}.
* Iteration:: @code{while} loops.
* Nonlocal Exits:: Jumping out of a sequence.
@end menu
@node Sequencing
@section Sequencing
Evaluating forms in the order they are written is the most common
control structure. Sometimes this happens automatically, such as in a
function body. Elsewhere you must use a control structure construct to
do this: @code{progn}, the simplest control construct of Lisp.
A @code{progn} special form looks like this:
(progn @var{a} @var{b} @var{c} @dots{})
@end group
@end example
and it says to execute the forms @var{a}, @var{b}, @var{c} and so on, in
that order. These forms are called the body of the @code{progn} form.
The value of the last form in the body becomes the value of the entire
@cindex implicit @code{progn}
In the early days of Lisp, @code{progn} was the only way to execute
two or more forms in succession and use the value of the last of them.
But programmers found they often needed to use a @code{progn} in the
body of a function, where (at that time) only one form was allowed. So
the body of a function was made into an ``implicit @code{progn}'':
several forms are allowed just as in the body of an actual @code{progn}.
Many other control structures likewise contain an implicit @code{progn}.
As a result, @code{progn} is not used as often as it used to be. It is
needed now most often inside of an @code{unwind-protect}, @code{and},
@code{or}, or the @var{else}-part of an @code{if}.
@defspec progn forms@dots{}
This special form evaluates all of the @var{forms}, in textual
order, returning the result of the final form.
(progn (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The third form"
@end group
@end example
@end defspec
Two other control constructs likewise evaluate a series of forms but return
a different value:
@defspec prog1 form1 forms@dots{}
This special form evaluates @var{form1} and all of the @var{forms}, in
textual order, returning the result of @var{form1}.
(prog1 (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The first form"
@end group
@end example
Here is a way to remove the first element from a list in the variable
@code{x}, then return the value of that former element:
(prog1 (car x) (setq x (cdr x)))
@end example
@end defspec
@defspec prog2 form1 form2 forms@dots{}
This special form evaluates @var{form1}, @var{form2}, and all of the
following @var{forms}, in textual order, returning the result of
(prog2 (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The second form"
@end group
@end example
@end defspec
@node Conditionals
@section Conditionals
@cindex conditional evaluation
Conditional control structures choose among alternatives. Emacs Lisp
has two conditional forms: @code{if}, which is much the same as in other
languages, and @code{cond}, which is a generalized case statement.
@defspec if condition then-form else-forms@dots{}
@code{if} chooses between the @var{then-form} and the @var{else-forms}
based on the value of @var{condition}. If the evaluated @var{condition} is
non-@code{nil}, @var{then-form} is evaluated and the result returned.
Otherwise, the @var{else-forms} are evaluated in textual order, and the
value of the last one is returned. (The @var{else} part of @code{if} is
an example of an implicit @code{progn}. @xref{Sequencing}.)
If @var{condition} has the value @code{nil}, and no @var{else-forms} are
given, @code{if} returns @code{nil}.
@code{if} is a special form because the branch which is not selected is
never evaluated---it is ignored. Thus, in the example below,
@code{true} is not printed because @code{print} is never called.
(if nil
(print 'true)
@result{} very-false
@end group
@end example
@end defspec
@defspec cond clause@dots{}
@code{cond} chooses among an arbitrary number of alternatives. Each
@var{clause} in the @code{cond} must be a list. The @sc{car} of this
list is the @var{condition}; the remaining elements, if any, the
@var{body-forms}. Thus, a clause looks like this:
(@var{condition} @var{body-forms}@dots{})
@end example
@code{cond} tries the clauses in textual order, by evaluating the
@var{condition} of each clause. If the value of @var{condition} is
non-@code{nil}, the clause ``succeeds''; then @code{cond} evaluates its
@var{body-forms}, and the value of the last of @var{body-forms} becomes
the value of the @code{cond}. The remaining clauses are ignored.
If the value of @var{condition} is @code{nil}, the clause ``fails'', so
the @code{cond} moves on to the following clause, trying its
If every @var{condition} evaluates to @code{nil}, so that every clause
fails, @code{cond} returns @code{nil}.
A clause may also look like this:
@end example
Then, if @var{condition} is non-@code{nil} when tested, the value of
@var{condition} becomes the value of the @code{cond} form.
The following example has four clauses, which test for the cases where
the value of @code{x} is a number, string, buffer and symbol,
(cond ((numberp x) x)
((stringp x) x)
((bufferp x)
(setq temporary-hack x) ; @r{multiple body-forms}
(buffer-name x)) ; @r{in one clause}
((symbolp x) (symbol-value x)))
@end group
@end example
Often we want to execute the last clause whenever none of the previous
clauses was successful. To do this, we use @code{t} as the
@var{condition} of the last clause, like this: @code{(t
@var{body-forms})}. The form @code{t} evaluates to @code{t}, which is
never @code{nil}, so this clause never fails, provided the @code{cond}
gets to it at all.
For example,
(cond ((eq a 1) 'foo)
(t "default"))
@result{} "default"
@end group
@end example
This expression is a @code{cond} which returns @code{foo} if the value
of @code{a} is 1, and returns the string @code{"default"} otherwise.
@end defspec
Both @code{cond} and @code{if} can usually be written in terms of the
other. Therefore, the choice between them is a matter of style. For
(if @var{a} @var{b} @var{c})
(cond (@var{a} @var{b}) (t @var{c}))
@end group
@end example
@node Combining Conditions
@section Constructs for Combining Conditions
This section describes three constructs that are often used together
with @code{if} and @code{cond} to express complicated conditions. The
constructs @code{and} and @code{or} can also be used individually as
kinds of multiple conditional constructs.
@defun not condition
This function tests for the falsehood of @var{condition}. It returns
@code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
The function @code{not} is identical to @code{null}, and we recommend
using the name @code{null} if you are testing for an empty list.
@end defun
@defspec and conditions@dots{}
The @code{and} special form tests whether all the @var{conditions} are
true. It works by evaluating the @var{conditions} one by one in the
order written.
If any of the @var{conditions} evaluates to @code{nil}, then the result
of the @code{and} must be @code{nil} regardless of the remaining
@var{conditions}; so @code{and} returns right away, ignoring the
remaining @var{conditions}.
If all the @var{conditions} turn out non-@code{nil}, then the value of
the last of them becomes the value of the @code{and} form.
Here is an example. The first condition returns the integer 1, which is
not @code{nil}. Similarly, the second condition returns the integer 2,
which is not @code{nil}. The third condition is @code{nil}, so the
remaining condition is never evaluated.
(and (print 1) (print 2) nil (print 3))
@print{} 1
@print{} 2
@result{} nil
@end group
@end example
Here is a more realistic example of using @code{and}:
(if (and (consp foo) (eq (car foo) 'x))
(message "foo is a list starting with x"))
@end group
@end example
Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
@code{nil}, thus avoiding an error.
@code{and} can be expressed in terms of either @code{if} or @code{cond}.
For example:
(and @var{arg1} @var{arg2} @var{arg3})
(if @var{arg1} (if @var{arg2} @var{arg3}))
(cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
@end group
@end example
@end defspec
@defspec or conditions@dots{}
The @code{or} special form tests whether at least one of the
@var{conditions} is true. It works by evaluating all the
@var{conditions} one by one in the order written.
If any of the @var{conditions} evaluates to a non-@code{nil} value, then
the result of the @code{or} must be non-@code{nil}; so @code{or} returns
right away, ignoring the remaining @var{conditions}. The value it
returns is the non-@code{nil} value of the condition just evaluated.
If all the @var{conditions} turn out @code{nil}, then the @code{or}
expression returns @code{nil}.
For example, this expression tests whether @code{x} is either 0 or
(or (eq x nil) (eq x 0))
@end example
Like the @code{and} construct, @code{or} can be written in terms of
@code{cond}. For example:
(or @var{arg1} @var{arg2} @var{arg3})
(cond (@var{arg1})
@end group
@end example
You could almost write @code{or} in terms of @code{if}, but not quite:
(if @var{arg1} @var{arg1}
(if @var{arg2} @var{arg2}
@end group
@end example
This is not completely equivalent because it can evaluate @var{arg1} or
@var{arg2} twice. By contrast, @code{(or @var{arg1} @var{arg2}
@var{arg3})} never evaluates any argument more than once.
@end defspec
@node Iteration
@section Iteration
@cindex iteration
@cindex recursion
Iteration means executing part of a program repetitively. For
example, you might want to repeat some computation once for each element
of a list, or once for each integer from 0 to @var{n}. You can do this
in Emacs Lisp with the special form @code{while}:
@defspec while condition forms@dots{}
@code{while} first evaluates @var{condition}. If the result is
non-@code{nil}, it evaluates @var{forms} in textual order. Then it
reevaluates @var{condition}, and if the result is non-@code{nil}, it
evaluates @var{forms} again. This process repeats until @var{condition}
evaluates to @code{nil}.
There is no limit on the number of iterations that may occur. The loop
will continue until either @var{condition} evaluates to @code{nil} or
until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
The value of a @code{while} form is always @code{nil}.
(setq num 0)
@result{} 0
@end group
(while (< num 4)
(princ (format "Iteration %d." num))
(setq num (1+ num)))
@print{} Iteration 0.
@print{} Iteration 1.
@print{} Iteration 2.
@print{} Iteration 3.
@result{} nil
@end group
@end example
If you would like to execute something on each iteration before the
end-test, put it together with the end-test in a @code{progn} as the
first argument of @code{while}, as shown here:
(while (progn
(forward-line 1)
(not (looking-at "^$"))))
@end group
@end example
This moves forward one line and continues moving by lines until an empty
line is reached.
@end defspec
@node Nonlocal Exits
@section Nonlocal Exits
@cindex nonlocal exits
A @dfn{nonlocal exit} is a transfer of control from one point in a
program to another remote point. Nonlocal exits can occur in Emacs Lisp
as a result of errors; you can also use them under explicit control.
Nonlocal exits unbind all variable bindings made by the constructs being
* Catch and Throw:: Nonlocal exits for the program's own purposes.
* Examples of Catch:: Showing how such nonlocal exits can be written.
* Errors:: How errors are signaled and handled.
* Cleanups:: Arranging to run a cleanup form if an error happens.
@end menu
@node Catch and Throw
@subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
Most control constructs affect only the flow of control within the
construct itself. The function @code{throw} is the exception to this
rule of normal program execution: it performs a nonlocal exit on
request. (There are other exceptions, but they are for error handling
only.) @code{throw} is used inside a @code{catch}, and jumps back to
that @code{catch}. For example:
(catch 'foo
(throw 'foo t)
@end group
@end example
The @code{throw} transfers control straight back to the corresponding
@code{catch}, which returns immediately. The code following the
@code{throw} is not executed. The second argument of @code{throw} is used
as the return value of the @code{catch}.
The @code{throw} and the @code{catch} are matched through the first
argument: @code{throw} searches for a @code{catch} whose first argument
is @code{eq} to the one specified. Thus, in the above example, the
@code{throw} specifies @code{foo}, and the @code{catch} specifies the
same symbol, so that @code{catch} is applicable. If there is more than
one applicable @code{catch}, the innermost one takes precedence.
Executing @code{throw} exits all Lisp constructs up to the matching
@code{catch}, including function calls. When binding constructs such as
@code{let} or function calls are exited in this way, the bindings are
unbound, just as they are when these constructs exit normally
(@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
and position saved by @code{save-excursion} (@pxref{Excursions}), and
the narrowing status saved by @code{save-restriction} and the window
selection saved by @code{save-window-excursion} (@pxref{Window
Configurations}). It also runs any cleanups established with the
@code{unwind-protect} special form when it exits that form.
The @code{throw} need not appear lexically within the @code{catch}
that it jumps to. It can equally well be called from another function
called within the @code{catch}. As long as the @code{throw} takes place
chronologically after entry to the @code{catch}, and chronologically
before exit from it, it has access to that @code{catch}. This is why
@code{throw} can be used in commands such as @code{exit-recursive-edit}
which throw back to the editor command loop (@pxref{Recursive Editing}).
@cindex CL note---only @code{throw} in Emacs
@b{Common Lisp note:} most other versions of Lisp, including Common Lisp,
have several ways of transferring control nonsequentially: @code{return},
@code{return-from}, and @code{go}, for example. Emacs Lisp has only
@end quotation
@defspec catch tag body@dots{}
@cindex tag on run time stack
@code{catch} establishes a return point for the @code{throw} function. The
return point is distinguished from other such return points by @var{tag},
which may be any Lisp object. The argument @var{tag} is evaluated normally
before the return point is established.
With the return point in effect, @code{catch} evaluates the forms of the
@var{body} in textual order. If the forms execute normally, without
error or nonlocal exit, the value of the last body form is returned from
the @code{catch}.
If a @code{throw} is done within @var{body} specifying the same value
@var{tag}, the @code{catch} exits immediately; the value it returns is
whatever was specified as the second argument of @code{throw}.
@end defspec
@defun throw tag value
The purpose of @code{throw} is to return from a return point previously
established with @code{catch}. The argument @var{tag} is used to choose
among the various existing return points; it must be @code{eq} to the value
specified in the @code{catch}. If multiple return points match @var{tag},
the innermost one is used.
The argument @var{value} is used as the value to return from that
@kindex no-catch
If no return point is in effect with tag @var{tag}, then a @code{no-catch}
error is signaled with data @code{(@var{tag} @var{value})}.
@end defun
@node Examples of Catch
@subsection Examples of @code{catch} and @code{throw}
One way to use @code{catch} and @code{throw} is to exit from a doubly
nested loop. (In most languages, this would be done with a ``go to''.)
Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
varying from 0 to 9:
(defun search-foo ()
(catch 'loop
(let ((i 0))
(while (< i 10)
(let ((j 0))
(while (< j 10)
(if (foo i j)
(throw 'loop (list i j)))
(setq j (1+ j))))
(setq i (1+ i))))))
@end group
@end example
If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
@code{catch} returns normally, and the value is @code{nil}, since that
is the result of the @code{while}.
Here are two tricky examples, slightly different, showing two
return points at once. First, two return points with the same tag,
(defun catch2 (tag)
(catch tag
(throw 'hack 'yes)))
@result{} catch2
@end group
(catch 'hack
(print (catch2 'hack))
@print{} yes
@result{} no
@end group
@end example
Since both return points have tags that match the @code{throw}, it goes to
the inner one, the one established in @code{catch2}. Therefore,
@code{catch2} returns normally with value @code{yes}, and this value is
printed. Finally the second body form in the outer @code{catch}, which is
@code{'no}, is evaluated and returned from the outer @code{catch}.
Now let's change the argument given to @code{catch2}:
(defun catch2 (tag)
(catch tag
(throw 'hack 'yes)))
@result{} catch2
@end group
(catch 'hack
(print (catch2 'quux))
@result{} yes
@end group
@end example
We still have two return points, but this time only the outer one has the
tag @code{hack}; the inner one has the tag @code{quux} instead. Therefore,
the @code{throw} returns the value @code{yes} from the outer return point.
The function @code{print} is never called, and the body-form @code{'no} is
never evaluated.
@node Errors
@subsection Errors
@cindex errors
When Emacs Lisp attempts to evaluate a form that, for some reason,
cannot be evaluated, it @dfn{signals} an @dfn{error}.
When an error is signaled, Emacs's default reaction is to print an
error message and terminate execution of the current command. This is
the right thing to do in most cases, such as if you type @kbd{C-f} at
the end of the buffer.
In complicated programs, simple termination may not be what you want.
For example, the program may have made temporary changes in data
structures, or created temporary buffers which should be deleted before
the program is finished. In such cases, you would use
@code{unwind-protect} to establish @dfn{cleanup expressions} to be
evaluated in case of error. Occasionally, you may wish the program to
continue execution despite an error in a subroutine. In these cases,
you would use @code{condition-case} to establish @dfn{error handlers} to
recover control in case of error.
Resist the temptation to use error handling to transfer control from
one part of the program to another; use @code{catch} and @code{throw}
instead. @xref{Catch and Throw}.
* Signaling Errors:: How to report an error.
* Processing of Errors:: What Emacs does when you report an error.
* Handling Errors:: How you can trap errors and continue execution.
* Error Names:: How errors are classified for trapping them.
@end menu
@node Signaling Errors
@subsubsection How to Signal an Error
@cindex signaling errors
Most errors are signaled ``automatically'' within Lisp primitives
which you call for other purposes, such as if you try to take the
@sc{car} of an integer or move forward a character at the end of the
buffer; you can also signal errors explicitly with the functions
@code{error} and @code{signal}.
Quitting, which happens when the user types @kbd{C-g}, is not
considered an error, but it is handled almost like an error.