comparison lispref/control.texi @ 7337:cd57cd335fff

*** empty log message ***
author Richard M. Stallman <rms@gnu.org>
date Thu, 05 May 1994 07:21:27 +0000
parents 974a37e5c414
children 2d4db32cccd5
comparison
equal deleted inserted replaced
7336:be8a00515620 7337:cd57cd335fff
9 @cindex control structures 9 @cindex control structures
10 10
11 A Lisp program consists of expressions or @dfn{forms} (@pxref{Forms}). 11 A Lisp program consists of expressions or @dfn{forms} (@pxref{Forms}).
12 We control the order of execution of the forms by enclosing them in 12 We control the order of execution of the forms by enclosing them in
13 @dfn{control structures}. Control structures are special forms which 13 @dfn{control structures}. Control structures are special forms which
14 control when, whether, or how many times to execute the forms they contain. 14 control when, whether, or how many times to execute the forms they
15 15 contain.
16 The simplest control structure is sequential execution: first form 16
17 The simplest order of execution is sequential execution: first form
17 @var{a}, then form @var{b}, and so on. This is what happens when you 18 @var{a}, then form @var{b}, and so on. This is what happens when you
18 write several forms in succession in the body of a function, or at top 19 write several forms in succession in the body of a function, or at top
19 level in a file of Lisp code---the forms are executed in the order they 20 level in a file of Lisp code---the forms are executed in the order
20 are written. We call this @dfn{textual order}. For example, if a 21 written. We call this @dfn{textual order}. For example, if a function
21 function body consists of two forms @var{a} and @var{b}, evaluation of 22 body consists of two forms @var{a} and @var{b}, evaluation of the
22 the function evaluates first @var{a} and then @var{b}, and the 23 function evaluates first @var{a} and then @var{b}, and the function's
23 function's value is the value of @var{b}. 24 value is the value of @var{b}.
25
26 Explicit control structures make possible an order of execution other
27 than sequential.
24 28
25 Emacs Lisp provides several kinds of control structure, including 29 Emacs Lisp provides several kinds of control structure, including
26 other varieties of sequencing, function calls, conditionals, iteration, 30 other varieties of sequencing, conditionals, iteration, and (controlled)
27 and (controlled) jumps. The built-in control structures are special 31 jumps---all discussed below. The built-in control structures are
28 forms since their subforms are not necessarily evaluated. You can use 32 special forms since their subforms are not necessarily evaluated or not
29 macros to define your own control structure constructs (@pxref{Macros}). 33 evaluated sequentially. You can use macros to define your own control
34 structure constructs (@pxref{Macros}).
30 35
31 @menu 36 @menu
32 * Sequencing:: Evaluation in textual order. 37 * Sequencing:: Evaluation in textual order.
33 * Conditionals:: @code{if}, @code{cond}. 38 * Conditionals:: @code{if}, @code{cond}.
34 * Combining Conditions:: @code{and}, @code{or}, @code{not}. 39 * Combining Conditions:: @code{and}, @code{or}, @code{not}.
37 @end menu 42 @end menu
38 43
39 @node Sequencing 44 @node Sequencing
40 @section Sequencing 45 @section Sequencing
41 46
42 Evaluating forms in the order they are written is the most common 47 Evaluating forms in the order they appear is the most common way
43 control structure. Sometimes this happens automatically, such as in a 48 control passes from one form to another. In some contexts, such as in a
44 function body. Elsewhere you must use a control structure construct to 49 function body, this happens automatically. Elsewhere you must use a
45 do this: @code{progn}, the simplest control construct of Lisp. 50 control structure construct to do this: @code{progn}, the simplest
51 control construct of Lisp.
46 52
47 A @code{progn} special form looks like this: 53 A @code{progn} special form looks like this:
48 54
49 @example 55 @example
50 @group 56 @group
65 body of a function, where (at that time) only one form was allowed. So 71 body of a function, where (at that time) only one form was allowed. So
66 the body of a function was made into an ``implicit @code{progn}'': 72 the body of a function was made into an ``implicit @code{progn}'':
67 several forms are allowed just as in the body of an actual @code{progn}. 73 several forms are allowed just as in the body of an actual @code{progn}.
68 Many other control structures likewise contain an implicit @code{progn}. 74 Many other control structures likewise contain an implicit @code{progn}.
69 As a result, @code{progn} is not used as often as it used to be. It is 75 As a result, @code{progn} is not used as often as it used to be. It is
70 needed now most often inside of an @code{unwind-protect}, @code{and}, 76 needed now most often inside an @code{unwind-protect}, @code{and},
71 @code{or}, or the @var{else}-part of an @code{if}. 77 @code{or}, or in the @var{then}-part of an @code{if}.
72 78
73 @defspec progn forms@dots{} 79 @defspec progn forms@dots{}
74 This special form evaluates all of the @var{forms}, in textual 80 This special form evaluates all of the @var{forms}, in textual
75 order, returning the result of the final form. 81 order, returning the result of the final form.
76 82
149 an example of an implicit @code{progn}. @xref{Sequencing}.) 155 an example of an implicit @code{progn}. @xref{Sequencing}.)
150 156
151 If @var{condition} has the value @code{nil}, and no @var{else-forms} are 157 If @var{condition} has the value @code{nil}, and no @var{else-forms} are
152 given, @code{if} returns @code{nil}. 158 given, @code{if} returns @code{nil}.
153 159
154 @code{if} is a special form because the branch which is not selected is 160 @code{if} is a special form because the branch that is not selected is
155 never evaluated---it is ignored. Thus, in the example below, 161 never evaluated---it is ignored. Thus, in the example below,
156 @code{true} is not printed because @code{print} is never called. 162 @code{true} is not printed because @code{print} is never called.
157 163
158 @example 164 @example
159 @group 165 @group
222 228
223 For example, 229 For example,
224 230
225 @example 231 @example
226 @group 232 @group
227 (cond ((eq a 1) 'foo) 233 (cond ((eq a 'hack) 'foo)
228 (t "default")) 234 (t "default"))
229 @result{} "default" 235 @result{} "default"
230 @end group 236 @end group
231 @end example 237 @end example
232 238
233 @noindent 239 @noindent
234 This expression is a @code{cond} which returns @code{foo} if the value 240 This expression is a @code{cond} which returns @code{foo} if the value
235 of @code{a} is 1, and returns the string @code{"default"} otherwise. 241 of @code{a} is 1, and returns the string @code{"default"} otherwise.
236 @end defspec 242 @end defspec
237 243
238 Both @code{cond} and @code{if} can usually be written in terms of the 244 Any conditional construct can be expressed with @code{cond} or with
239 other. Therefore, the choice between them is a matter of style. For 245 @code{if}. Therefore, the choice between them is a matter of style.
240 example: 246 For example:
241 247
242 @example 248 @example
243 @group 249 @group
244 (if @var{a} @var{b} @var{c}) 250 (if @var{a} @var{b} @var{c})
245 @equiv{} 251 @equiv{}
416 (not (looking-at "^$")))) 422 (not (looking-at "^$"))))
417 @end group 423 @end group
418 @end example 424 @end example
419 425
420 @noindent 426 @noindent
421 This moves forward one line and continues moving by lines until an empty 427 This moves forward one line and continues moving by lines until it
422 line is reached. 428 reaches an empty. It is unusual in that the @code{while} has no body,
429 just the end test (which also does the real work of moving point).
423 @end defspec 430 @end defspec
424 431
425 @node Nonlocal Exits 432 @node Nonlocal Exits
426 @section Nonlocal Exits 433 @section Nonlocal Exits
427 @cindex nonlocal exits 434 @cindex nonlocal exits
452 @example 459 @example
453 @group 460 @group
454 (catch 'foo 461 (catch 'foo
455 (progn 462 (progn
456 @dots{} 463 @dots{}
457 (throw 'foo t) 464 (throw 'foo t)
458 @dots{})) 465 @dots{}))
459 @end group 466 @end group
460 @end example 467 @end example
461 468
462 @noindent 469 @noindent
479 (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer 486 (@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
480 and position saved by @code{save-excursion} (@pxref{Excursions}), and 487 and position saved by @code{save-excursion} (@pxref{Excursions}), and
481 the narrowing status saved by @code{save-restriction} and the window 488 the narrowing status saved by @code{save-restriction} and the window
482 selection saved by @code{save-window-excursion} (@pxref{Window 489 selection saved by @code{save-window-excursion} (@pxref{Window
483 Configurations}). It also runs any cleanups established with the 490 Configurations}). It also runs any cleanups established with the
484 @code{unwind-protect} special form when it exits that form. 491 @code{unwind-protect} special form when it exits that form
492 (@pxref{Cleanups}).
485 493
486 The @code{throw} need not appear lexically within the @code{catch} 494 The @code{throw} need not appear lexically within the @code{catch}
487 that it jumps to. It can equally well be called from another function 495 that it jumps to. It can equally well be called from another function
488 called within the @code{catch}. As long as the @code{throw} takes place 496 called within the @code{catch}. As long as the @code{throw} takes place
489 chronologically after entry to the @code{catch}, and chronologically 497 chronologically after entry to the @code{catch}, and chronologically
490 before exit from it, it has access to that @code{catch}. This is why 498 before exit from it, it has access to that @code{catch}. This is why
491 @code{throw} can be used in commands such as @code{exit-recursive-edit} 499 @code{throw} can be used in commands such as @code{exit-recursive-edit}
492 which throw back to the editor command loop (@pxref{Recursive Editing}). 500 that throw back to the editor command loop (@pxref{Recursive Editing}).
493 501
494 @cindex CL note---only @code{throw} in Emacs 502 @cindex CL note---only @code{throw} in Emacs
495 @quotation 503 @quotation
496 @b{Common Lisp note:} most other versions of Lisp, including Common Lisp, 504 @b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
497 have several ways of transferring control nonsequentially: @code{return}, 505 have several ways of transferring control nonsequentially: @code{return},
498 @code{return-from}, and @code{go}, for example. Emacs Lisp has only 506 @code{return-from}, and @code{go}, for example. Emacs Lisp has only
499 @code{throw}. 507 @code{throw}.
500 @end quotation 508 @end quotation
501 509
605 @result{} yes 613 @result{} yes
606 @end group 614 @end group
607 @end example 615 @end example
608 616
609 @noindent 617 @noindent
610 We still have two return points, but this time only the outer one has the 618 We still have two return points, but this time only the outer one has
611 tag @code{hack}; the inner one has the tag @code{quux} instead. Therefore, 619 the tag @code{hack}; the inner one has the tag @code{quux} instead.
612 the @code{throw} returns the value @code{yes} from the outer return point. 620 Therefore, @code{throw} makes the outer @code{catch} return the value
613 The function @code{print} is never called, and the body-form @code{'no} is 621 @code{yes}. The function @code{print} is never called, and the
614 never evaluated. 622 body-form @code{'no} is never evaluated.
615 623
616 @node Errors 624 @node Errors
617 @subsection Errors 625 @subsection Errors
618 @cindex errors 626 @cindex errors
619 627
625 the right thing to do in most cases, such as if you type @kbd{C-f} at 633 the right thing to do in most cases, such as if you type @kbd{C-f} at
626 the end of the buffer. 634 the end of the buffer.
627 635
628 In complicated programs, simple termination may not be what you want. 636 In complicated programs, simple termination may not be what you want.
629 For example, the program may have made temporary changes in data 637 For example, the program may have made temporary changes in data
630 structures, or created temporary buffers which should be deleted before 638 structures, or created temporary buffers that should be deleted before
631 the program is finished. In such cases, you would use 639 the program is finished. In such cases, you would use
632 @code{unwind-protect} to establish @dfn{cleanup expressions} to be 640 @code{unwind-protect} to establish @dfn{cleanup expressions} to be
633 evaluated in case of error. Occasionally, you may wish the program to 641 evaluated in case of error. (@xref{Cleanups}.) Occasionally, you may
634 continue execution despite an error in a subroutine. In these cases, 642 wish the program to continue execution despite an error in a subroutine.
635 you would use @code{condition-case} to establish @dfn{error handlers} to 643 In these cases, you would use @code{condition-case} to establish
636 recover control in case of error. 644 @dfn{error handlers} to recover control in case of error.
637 645
638 Resist the temptation to use error handling to transfer control from 646 Resist the temptation to use error handling to transfer control from
639 one part of the program to another; use @code{catch} and @code{throw} 647 one part of the program to another; use @code{catch} and @code{throw}
640 instead. @xref{Catch and Throw}. 648 instead. @xref{Catch and Throw}.
641 649
642 @menu 650 @menu
643 * Signaling Errors:: How to report an error. 651 * Signaling Errors:: How to report an error.
644 * Processing of Errors:: What Emacs does when you report an error. 652 * Processing of Errors:: What Emacs does when you report an error.
645 * Handling Errors:: How you can trap errors and continue execution. 653 * Handling Errors:: How you can trap errors and continue execution.
646 * Error Names:: How errors are classified for trapping them. 654 * Error Symbols:: How errors are classified for trapping them.
647 @end menu 655 @end menu
648 656
649 @node Signaling Errors 657 @node Signaling Errors
650 @subsubsection How to Signal an Error 658 @subsubsection How to Signal an Error
651 @cindex signaling errors 659 @cindex signaling errors
701 condition names. This is how Emacs Lisp classifies different sorts of 709 condition names. This is how Emacs Lisp classifies different sorts of
702 errors. 710 errors.
703 711
704 The number and significance of the objects in @var{data} depends on 712 The number and significance of the objects in @var{data} depends on
705 @var{error-symbol}. For example, with a @code{wrong-type-arg} error, 713 @var{error-symbol}. For example, with a @code{wrong-type-arg} error,
706 there are two objects in the list: a predicate which describes the type 714 there are two objects in the list: a predicate that describes the type
707 that was expected, and the object which failed to fit that type. 715 that was expected, and the object that failed to fit that type.
708 @xref{Error Names}, for a description of error symbols. 716 @xref{Error Symbols}, for a description of error symbols.
709 717
710 Both @var{error-symbol} and @var{data} are available to any error 718 Both @var{error-symbol} and @var{data} are available to any error
711 handlers which handle the error: @code{condition-case} binds a local 719 handlers that handle the error: @code{condition-case} binds a local
712 variable to a list of the form @code{(@var{error-symbol} .@: 720 variable to a list of the form @code{(@var{error-symbol} .@:
713 @var{data})} (@pxref{Handling Errors}). If the error is not handled, 721 @var{data})} (@pxref{Handling Errors}). If the error is not handled,
714 these two values are used in printing the error message. 722 these two values are used in printing the error message.
715 723
716 The function @code{signal} never returns (though in older Emacs versions 724 The function @code{signal} never returns (though in older Emacs versions
741 When an error is signaled, @code{signal} searches for an active 749 When an error is signaled, @code{signal} searches for an active
742 @dfn{handler} for the error. A handler is a sequence of Lisp 750 @dfn{handler} for the error. A handler is a sequence of Lisp
743 expressions designated to be executed if an error happens in part of the 751 expressions designated to be executed if an error happens in part of the
744 Lisp program. If the error has an applicable handler, the handler is 752 Lisp program. If the error has an applicable handler, the handler is
745 executed, and control resumes following the handler. The handler 753 executed, and control resumes following the handler. The handler
746 executes in the environment of the @code{condition-case} which 754 executes in the environment of the @code{condition-case} that
747 established it; all functions called within that @code{condition-case} 755 established it; all functions called within that @code{condition-case}
748 have already been exited, and the handler cannot return to them. 756 have already been exited, and the handler cannot return to them.
749 757
750 If there is no applicable handler for the error, the current command is 758 If there is no applicable handler for the error, the current command is
751 terminated and control returns to the editor command loop, because the 759 terminated and control returns to the editor command loop, because the
786 The second argument of @code{condition-case} is called the 794 The second argument of @code{condition-case} is called the
787 @dfn{protected form}. (In the example above, the protected form is a 795 @dfn{protected form}. (In the example above, the protected form is a
788 call to @code{delete-file}.) The error handlers go into effect when 796 call to @code{delete-file}.) The error handlers go into effect when
789 this form begins execution and are deactivated when this form returns. 797 this form begins execution and are deactivated when this form returns.
790 They remain in effect for all the intervening time. In particular, they 798 They remain in effect for all the intervening time. In particular, they
791 are in effect during the execution of subroutines called by this form, 799 are in effect during the execution of functions called by this form, in
792 and their subroutines, and so on. This is a good thing, since, strictly 800 their subroutines, and so on. This is a good thing, since, strictly
793 speaking, errors can be signaled only by Lisp primitives (including 801 speaking, errors can be signaled only by Lisp primitives (including
794 @code{signal} and @code{error}) called by the protected form, not by the 802 @code{signal} and @code{error}) called by the protected form, not by the
795 protected form itself. 803 protected form itself.
796 804
797 The arguments after the protected form are handlers. Each handler 805 The arguments after the protected form are handlers. Each handler
828 836
829 Error signaling and handling have some resemblance to @code{throw} and 837 Error signaling and handling have some resemblance to @code{throw} and
830 @code{catch}, but they are entirely separate facilities. An error 838 @code{catch}, but they are entirely separate facilities. An error
831 cannot be caught by a @code{catch}, and a @code{throw} cannot be handled 839 cannot be caught by a @code{catch}, and a @code{throw} cannot be handled
832 by an error handler (though using @code{throw} when there is no suitable 840 by an error handler (though using @code{throw} when there is no suitable
833 @code{catch} signals an error which can be handled). 841 @code{catch} signals an error that can be handled).
834 842
835 @defspec condition-case var protected-form handlers@dots{} 843 @defspec condition-case var protected-form handlers@dots{}
836 This special form establishes the error handlers @var{handlers} around 844 This special form establishes the error handlers @var{handlers} around
837 the execution of @var{protected-form}. If @var{protected-form} executes 845 the execution of @var{protected-form}. If @var{protected-form} executes
838 without error, the value it returns becomes the value of the 846 without error, the value it returns becomes the value of the
856 (message 864 (message
857 "Either division by zero or failure to open a file")) 865 "Either division by zero or failure to open a file"))
858 @end group 866 @end group
859 @end smallexample 867 @end smallexample
860 868
861 Each error that occurs has an @dfn{error symbol} which describes what 869 Each error that occurs has an @dfn{error symbol} that describes what
862 kind of error it is. The @code{error-conditions} property of this 870 kind of error it is. The @code{error-conditions} property of this
863 symbol is a list of condition names (@pxref{Error Names}). Emacs 871 symbol is a list of condition names (@pxref{Error Symbols}). Emacs
864 searches all the active @code{condition-case} forms for a handler which 872 searches all the active @code{condition-case} forms for a handler that
865 specifies one or more of these condition names; the innermost matching 873 specifies one or more of these condition names; the innermost matching
866 @code{condition-case} handles the error. Within this 874 @code{condition-case} handles the error. Within this
867 @code{condition-case}, the first applicable handler handles the error. 875 @code{condition-case}, the first applicable handler handles the error.
868 876
869 After executing the body of the handler, the @code{condition-case} 877 After executing the body of the handler, the @code{condition-case}
939 @print{} The error was: (error "Rats! The variable baz was 34, not 35.") 947 @print{} The error was: (error "Rats! The variable baz was 34, not 35.")
940 @result{} 2 948 @result{} 2
941 @end group 949 @end group
942 @end smallexample 950 @end smallexample
943 951
944 @node Error Names 952 @node Error Symbols
945 @subsubsection Error Symbols and Condition Names 953 @subsubsection Error Symbols and Condition Names
946 @cindex error symbol 954 @cindex error symbol
947 @cindex error name 955 @cindex error name
948 @cindex condition name 956 @cindex condition name
949 @cindex user-defined error 957 @cindex user-defined error
964 is distinct from @code{error}, and perhaps some intermediate 972 is distinct from @code{error}, and perhaps some intermediate
965 classifications. 973 classifications.
966 974
967 In order for a symbol to be an error symbol, it must have an 975 In order for a symbol to be an error symbol, it must have an
968 @code{error-conditions} property which gives a list of condition names. 976 @code{error-conditions} property which gives a list of condition names.
969 This list defines the conditions which this kind of error belongs to. 977 This list defines the conditions that this kind of error belongs to.
970 (The error symbol itself, and the symbol @code{error}, should always be 978 (The error symbol itself, and the symbol @code{error}, should always be
971 members of this list.) Thus, the hierarchy of condition names is 979 members of this list.) Thus, the hierarchy of condition names is
972 defined by the @code{error-conditions} properties of the error symbols. 980 defined by the @code{error-conditions} properties of the error symbols.
973 981
974 In addition to the @code{error-conditions} list, the error symbol 982 In addition to the @code{error-conditions} list, the error symbol
997 This error has three condition names: @code{new-error}, the narrowest 1005 This error has three condition names: @code{new-error}, the narrowest
998 classification; @code{my-own-errors}, which we imagine is a wider 1006 classification; @code{my-own-errors}, which we imagine is a wider
999 classification; and @code{error}, which is the widest of all. 1007 classification; and @code{error}, which is the widest of all.
1000 1008
1001 Naturally, Emacs will never signal @code{new-error} on its own; only 1009 Naturally, Emacs will never signal @code{new-error} on its own; only
1002 an explicit call to @code{signal} (@pxref{Errors}) in your code can do 1010 an explicit call to @code{signal} (@pxref{Signaling Errors}) in your
1003 this: 1011 code can do this:
1004 1012
1005 @example 1013 @example
1006 @group 1014 @group
1007 (signal 'new-error '(x y)) 1015 (signal 'new-error '(x y))
1008 @error{} A new error: x, y 1016 @error{} A new error: x, y
1092 error after switching to a different buffer! (Alternatively, you could 1100 error after switching to a different buffer! (Alternatively, you could
1093 write another @code{save-excursion} around the body, to ensure that the 1101 write another @code{save-excursion} around the body, to ensure that the
1094 temporary buffer becomes current in time to kill it.) 1102 temporary buffer becomes current in time to kill it.)
1095 1103
1096 @findex ftp-login 1104 @findex ftp-login
1097 Here is an actual example taken from the file @file{ftp.el}. It creates 1105 Here is an actual example taken from the file @file{ftp.el}. It
1098 a process (@pxref{Processes}) to try to establish a connection to a remote 1106 creates a process (@pxref{Processes}) to try to establish a connection
1099 machine. As the function @code{ftp-login} is highly susceptible to 1107 to a remote machine. As the function @code{ftp-login} is highly
1100 numerous problems which the writer of the function cannot anticipate, it is 1108 susceptible to numerous problems that the writer of the function cannot
1101 protected with a form that guarantees deletion of the process in the event 1109 anticipate, it is protected with a form that guarantees deletion of the
1102 of failure. Otherwise, Emacs might fill up with useless subprocesses. 1110 process in the event of failure. Otherwise, Emacs might fill up with
1111 useless subprocesses.
1103 1112
1104 @smallexample 1113 @smallexample
1105 @group 1114 @group
1106 (let ((win nil)) 1115 (let ((win nil))
1107 (unwind-protect 1116 (unwind-protect