e9ddbe6419d1bf974ed8064fc1b2bcf67d5abbe7
[chise/xemacs-chise.git.1] / info / lispref.info-8
1 This is ../info/lispref.info, produced by makeinfo version 4.0 from
2 lispref/lispref.texi.
3
4 INFO-DIR-SECTION XEmacs Editor
5 START-INFO-DIR-ENTRY
6 * Lispref: (lispref).           XEmacs Lisp Reference Manual.
7 END-INFO-DIR-ENTRY
8
9    Edition History:
10
11    GNU Emacs Lisp Reference Manual Second Edition (v2.01), May 1993 GNU
12 Emacs Lisp Reference Manual Further Revised (v2.02), August 1993 Lucid
13 Emacs Lisp Reference Manual (for 19.10) First Edition, March 1994
14 XEmacs Lisp Programmer's Manual (for 19.12) Second Edition, April 1995
15 GNU Emacs Lisp Reference Manual v2.4, June 1995 XEmacs Lisp
16 Programmer's Manual (for 19.13) Third Edition, July 1995 XEmacs Lisp
17 Reference Manual (for 19.14 and 20.0) v3.1, March 1996 XEmacs Lisp
18 Reference Manual (for 19.15 and 20.1, 20.2, 20.3) v3.2, April, May,
19 November 1997 XEmacs Lisp Reference Manual (for 21.0) v3.3, April 1998
20
21    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995 Free Software
22 Foundation, Inc.  Copyright (C) 1994, 1995 Sun Microsystems, Inc.
23 Copyright (C) 1995, 1996 Ben Wing.
24
25    Permission is granted to make and distribute verbatim copies of this
26 manual provided the copyright notice and this permission notice are
27 preserved on all copies.
28
29    Permission is granted to copy and distribute modified versions of
30 this manual under the conditions for verbatim copying, provided that the
31 entire resulting derived work is distributed under the terms of a
32 permission notice identical to this one.
33
34    Permission is granted to copy and distribute translations of this
35 manual into another language, under the above conditions for modified
36 versions, except that this permission notice may be stated in a
37 translation approved by the Foundation.
38
39    Permission is granted to copy and distribute modified versions of
40 this manual under the conditions for verbatim copying, provided also
41 that the section entitled "GNU General Public License" is included
42 exactly as in the original, and provided that the entire resulting
43 derived work is distributed under the terms of a permission notice
44 identical to this one.
45
46    Permission is granted to copy and distribute translations of this
47 manual into another language, under the above conditions for modified
48 versions, except that the section entitled "GNU General Public License"
49 may be included in a translation approved by the Free Software
50 Foundation instead of in the original English.
51
52 \1f
53 File: lispref.info,  Node: Self-Evaluating Forms,  Next: Symbol Forms,  Up: Forms
54
55 Self-Evaluating Forms
56 ---------------------
57
58    A "self-evaluating form" is any form that is not a list or symbol.
59 Self-evaluating forms evaluate to themselves: the result of evaluation
60 is the same object that was evaluated.  Thus, the number 25 evaluates to
61 25, and the string `"foo"' evaluates to the string `"foo"'.  Likewise,
62 evaluation of a vector does not cause evaluation of the elements of the
63 vector--it returns the same vector with its contents unchanged.
64
65      '123               ; An object, shown without evaluation.
66           => 123
67      123                ; Evaluated as usual--result is the same.
68           => 123
69      (eval '123)        ; Evaluated "by hand"--result is the same.
70           => 123
71      (eval (eval '123)) ; Evaluating twice changes nothing.
72           => 123
73
74    It is common to write numbers, characters, strings, and even vectors
75 in Lisp code, taking advantage of the fact that they self-evaluate.
76 However, it is quite unusual to do this for types that lack a read
77 syntax, because there's no way to write them textually.  It is possible
78 to construct Lisp expressions containing these types by means of a Lisp
79 program.  Here is an example:
80
81      ;; Build an expression containing a buffer object.
82      (setq buffer (list 'print (current-buffer)))
83           => (print #<buffer eval.texi>)
84      ;; Evaluate it.
85      (eval buffer)
86           -| #<buffer eval.texi>
87           => #<buffer eval.texi>
88
89 \1f
90 File: lispref.info,  Node: Symbol Forms,  Next: Classifying Lists,  Prev: Self-Evaluating Forms,  Up: Forms
91
92 Symbol Forms
93 ------------
94
95    When a symbol is evaluated, it is treated as a variable.  The result
96 is the variable's value, if it has one.  If it has none (if its value
97 cell is void), an error is signaled.  For more information on the use of
98 variables, see *Note Variables::.
99
100    In the following example, we set the value of a symbol with `setq'.
101 Then we evaluate the symbol, and get back the value that `setq' stored.
102
103      (setq a 123)
104           => 123
105      (eval 'a)
106           => 123
107      a
108           => 123
109
110    The symbols `nil' and `t' are treated specially, so that the value
111 of `nil' is always `nil', and the value of `t' is always `t'; you
112 cannot set or bind them to any other values.  Thus, these two symbols
113 act like self-evaluating forms, even though `eval' treats them like any
114 other symbol.
115
116 \1f
117 File: lispref.info,  Node: Classifying Lists,  Next: Function Indirection,  Prev: Symbol Forms,  Up: Forms
118
119 Classification of List Forms
120 ----------------------------
121
122    A form that is a nonempty list is either a function call, a macro
123 call, or a special form, according to its first element.  These three
124 kinds of forms are evaluated in different ways, described below.  The
125 remaining list elements constitute the "arguments" for the function,
126 macro, or special form.
127
128    The first step in evaluating a nonempty list is to examine its first
129 element.  This element alone determines what kind of form the list is
130 and how the rest of the list is to be processed.  The first element is
131 _not_ evaluated, as it would be in some Lisp dialects such as Scheme.
132
133 \1f
134 File: lispref.info,  Node: Function Indirection,  Next: Function Forms,  Prev: Classifying Lists,  Up: Forms
135
136 Symbol Function Indirection
137 ---------------------------
138
139    If the first element of the list is a symbol then evaluation examines
140 the symbol's function cell, and uses its contents instead of the
141 original symbol.  If the contents are another symbol, this process,
142 called "symbol function indirection", is repeated until it obtains a
143 non-symbol.  *Note Function Names::, for more information about using a
144 symbol as a name for a function stored in the function cell of the
145 symbol.
146
147    One possible consequence of this process is an infinite loop, in the
148 event that a symbol's function cell refers to the same symbol.  Or a
149 symbol may have a void function cell, in which case the subroutine
150 `symbol-function' signals a `void-function' error.  But if neither of
151 these things happens, we eventually obtain a non-symbol, which ought to
152 be a function or other suitable object.
153
154    More precisely, we should now have a Lisp function (a lambda
155 expression), a byte-code function, a primitive function, a Lisp macro, a
156 special form, or an autoload object.  Each of these types is a case
157 described in one of the following sections.  If the object is not one of
158 these types, the error `invalid-function' is signaled.
159
160    The following example illustrates the symbol indirection process.  We
161 use `fset' to set the function cell of a symbol and `symbol-function'
162 to get the function cell contents (*note Function Cells::).
163 Specifically, we store the symbol `car' into the function cell of
164 `first', and the symbol `first' into the function cell of `erste'.
165
166      ;; Build this function cell linkage:
167      ;;   -------------       -----        -------        -------
168      ;;  | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
169      ;;   -------------       -----        -------        -------
170
171      (symbol-function 'car)
172           => #<subr car>
173      (fset 'first 'car)
174           => car
175      (fset 'erste 'first)
176           => first
177      (erste '(1 2 3))   ; Call the function referenced by `erste'.
178           => 1
179
180    By contrast, the following example calls a function without any
181 symbol function indirection, because the first element is an anonymous
182 Lisp function, not a symbol.
183
184      ((lambda (arg) (erste arg))
185       '(1 2 3))
186           => 1
187
188 Executing the function itself evaluates its body; this does involve
189 symbol function indirection when calling `erste'.
190
191    The built-in function `indirect-function' provides an easy way to
192 perform symbol function indirection explicitly.
193
194  - Function: indirect-function function
195      This function returns the meaning of FUNCTION as a function.  If
196      FUNCTION is a symbol, then it finds FUNCTION's function definition
197      and starts over with that value.  If FUNCTION is not a symbol,
198      then it returns FUNCTION itself.
199
200      Here is how you could define `indirect-function' in Lisp:
201
202           (defun indirect-function (function)
203             (if (symbolp function)
204                 (indirect-function (symbol-function function))
205               function))
206
207 \1f
208 File: lispref.info,  Node: Function Forms,  Next: Macro Forms,  Prev: Function Indirection,  Up: Forms
209
210 Evaluation of Function Forms
211 ----------------------------
212
213    If the first element of a list being evaluated is a Lisp function
214 object, byte-code object or primitive function object, then that list is
215 a "function call".  For example, here is a call to the function `+':
216
217      (+ 1 x)
218
219    The first step in evaluating a function call is to evaluate the
220 remaining elements of the list from left to right.  The results are the
221 actual argument values, one value for each list element.  The next step
222 is to call the function with this list of arguments, effectively using
223 the function `apply' (*note Calling Functions::).  If the function is
224 written in Lisp, the arguments are used to bind the argument variables
225 of the function (*note Lambda Expressions::); then the forms in the
226 function body are evaluated in order, and the value of the last body
227 form becomes the value of the function call.
228
229 \1f
230 File: lispref.info,  Node: Macro Forms,  Next: Special Forms,  Prev: Function Forms,  Up: Forms
231
232 Lisp Macro Evaluation
233 ---------------------
234
235    If the first element of a list being evaluated is a macro object,
236 then the list is a "macro call".  When a macro call is evaluated, the
237 elements of the rest of the list are _not_ initially evaluated.
238 Instead, these elements themselves are used as the arguments of the
239 macro.  The macro definition computes a replacement form, called the
240 "expansion" of the macro, to be evaluated in place of the original
241 form.  The expansion may be any sort of form: a self-evaluating
242 constant, a symbol, or a list.  If the expansion is itself a macro call,
243 this process of expansion repeats until some other sort of form results.
244
245    Ordinary evaluation of a macro call finishes by evaluating the
246 expansion.  However, the macro expansion is not necessarily evaluated
247 right away, or at all, because other programs also expand macro calls,
248 and they may or may not evaluate the expansions.
249
250    Normally, the argument expressions are not evaluated as part of
251 computing the macro expansion, but instead appear as part of the
252 expansion, so they are computed when the expansion is computed.
253
254    For example, given a macro defined as follows:
255
256      (defmacro cadr (x)
257        (list 'car (list 'cdr x)))
258
259 an expression such as `(cadr (assq 'handler list))' is a macro call,
260 and its expansion is:
261
262      (car (cdr (assq 'handler list)))
263
264 Note that the argument `(assq 'handler list)' appears in the expansion.
265
266    *Note Macros::, for a complete description of XEmacs Lisp macros.
267
268 \1f
269 File: lispref.info,  Node: Special Forms,  Next: Autoloading,  Prev: Macro Forms,  Up: Forms
270
271 Special Forms
272 -------------
273
274    A "special form" is a primitive function specially marked so that
275 its arguments are not all evaluated.  Most special forms define control
276 structures or perform variable bindings--things which functions cannot
277 do.
278
279    Each special form has its own rules for which arguments are evaluated
280 and which are used without evaluation.  Whether a particular argument is
281 evaluated may depend on the results of evaluating other arguments.
282
283    Here is a list, in alphabetical order, of all of the special forms in
284 XEmacs Lisp with a reference to where each is described.
285
286 `and'
287      *note Combining Conditions::
288
289 `catch'
290      *note Catch and Throw::
291
292 `cond'
293      *note Conditionals::
294
295 `condition-case'
296      *note Handling Errors::
297
298 `defconst'
299      *note Defining Variables::
300
301 `defmacro'
302      *note Defining Macros::
303
304 `defun'
305      *note Defining Functions::
306
307 `defvar'
308      *note Defining Variables::
309
310 `function'
311      *note Anonymous Functions::
312
313 `if'
314      *note Conditionals::
315
316 `interactive'
317      *note Interactive Call::
318
319 `let'
320 `let*'
321      *note Local Variables::
322
323 `or'
324      *note Combining Conditions::
325
326 `prog1'
327 `prog2'
328 `progn'
329      *note Sequencing::
330
331 `quote'
332      *note Quoting::
333
334 `save-current-buffer'
335      *note Excursions::
336
337 `save-excursion'
338      *note Excursions::
339
340 `save-restriction'
341      *note Narrowing::
342
343 `save-selected-window'
344      *note Excursions::
345
346 `save-window-excursion'
347      *note Window Configurations::
348
349 `setq'
350      *note Setting Variables::
351
352 `setq-default'
353      *note Creating Buffer-Local::
354
355 `unwind-protect'
356      *note Nonlocal Exits::
357
358 `while'
359      *note Iteration::
360
361 `with-output-to-temp-buffer'
362      *note Temporary Displays::
363
364      Common Lisp note: here are some comparisons of special forms in
365      XEmacs Lisp and Common Lisp.  `setq', `if', and `catch' are
366      special forms in both XEmacs Lisp and Common Lisp.  `defun' is a
367      special form in XEmacs Lisp, but a macro in Common Lisp.
368      `save-excursion' is a special form in XEmacs Lisp, but doesn't
369      exist in Common Lisp.  `throw' is a special form in Common Lisp
370      (because it must be able to throw multiple values), but it is a
371      function in XEmacs Lisp (which doesn't have multiple values).
372
373 \1f
374 File: lispref.info,  Node: Autoloading,  Prev: Special Forms,  Up: Forms
375
376 Autoloading
377 -----------
378
379    The "autoload" feature allows you to call a function or macro whose
380 function definition has not yet been loaded into XEmacs.  It specifies
381 which file contains the definition.  When an autoload object appears as
382 a symbol's function definition, calling that symbol as a function
383 automatically loads the specified file; then it calls the real
384 definition loaded from that file.  *Note Autoload::.
385
386 \1f
387 File: lispref.info,  Node: Quoting,  Prev: Forms,  Up: Evaluation
388
389 Quoting
390 =======
391
392    The special form `quote' returns its single argument, as written,
393 without evaluating it.  This provides a way to include constant symbols
394 and lists, which are not self-evaluating objects, in a program.  (It is
395 not necessary to quote self-evaluating objects such as numbers, strings,
396 and vectors.)
397
398  - Special Form: quote object
399      This special form returns OBJECT, without evaluating it.
400
401    Because `quote' is used so often in programs, Lisp provides a
402 convenient read syntax for it.  An apostrophe character (`'') followed
403 by a Lisp object (in read syntax) expands to a list whose first element
404 is `quote', and whose second element is the object.  Thus, the read
405 syntax `'x' is an abbreviation for `(quote x)'.
406
407    Here are some examples of expressions that use `quote':
408
409      (quote (+ 1 2))
410           => (+ 1 2)
411      (quote foo)
412           => foo
413      'foo
414           => foo
415      ''foo
416           => (quote foo)
417      '(quote foo)
418           => (quote foo)
419      ['foo]
420           => [(quote foo)]
421
422    Other quoting constructs include `function' (*note Anonymous
423 Functions::), which causes an anonymous lambda expression written in
424 Lisp to be compiled, and ``' (*note Backquote::), which is used to quote
425 only part of a list, while computing and substituting other parts.
426
427 \1f
428 File: lispref.info,  Node: Control Structures,  Next: Variables,  Prev: Evaluation,  Up: Top
429
430 Control Structures
431 ******************
432
433    A Lisp program consists of expressions or "forms" (*note Forms::).
434 We control the order of execution of the forms by enclosing them in
435 "control structures".  Control structures are special forms which
436 control when, whether, or how many times to execute the forms they
437 contain.
438
439    The simplest order of execution is sequential execution: first form
440 A, then form B, and so on.  This is what happens when you write several
441 forms in succession in the body of a function, or at top level in a
442 file of Lisp code--the forms are executed in the order written.  We
443 call this "textual order".  For example, if a function body consists of
444 two forms A and B, evaluation of the function evaluates first A and
445 then B, and the function's value is the value of B.
446
447    Explicit control structures make possible an order of execution other
448 than sequential.
449
450    XEmacs Lisp provides several kinds of control structure, including
451 other varieties of sequencing, conditionals, iteration, and (controlled)
452 jumps--all discussed below.  The built-in control structures are
453 special forms since their subforms are not necessarily evaluated or not
454 evaluated sequentially.  You can use macros to define your own control
455 structure constructs (*note Macros::).
456
457 * Menu:
458
459 * Sequencing::             Evaluation in textual order.
460 * Conditionals::           `if', `cond'.
461 * Combining Conditions::   `and', `or', `not'.
462 * Iteration::              `while' loops.
463 * Nonlocal Exits::         Jumping out of a sequence.
464
465 \1f
466 File: lispref.info,  Node: Sequencing,  Next: Conditionals,  Up: Control Structures
467
468 Sequencing
469 ==========
470
471    Evaluating forms in the order they appear is the most common way
472 control passes from one form to another.  In some contexts, such as in a
473 function body, this happens automatically.  Elsewhere you must use a
474 control structure construct to do this: `progn', the simplest control
475 construct of Lisp.
476
477    A `progn' special form looks like this:
478
479      (progn A B C ...)
480
481 and it says to execute the forms A, B, C and so on, in that order.
482 These forms are called the body of the `progn' form.  The value of the
483 last form in the body becomes the value of the entire `progn'.
484
485    In the early days of Lisp, `progn' was the only way to execute two
486 or more forms in succession and use the value of the last of them.  But
487 programmers found they often needed to use a `progn' in the body of a
488 function, where (at that time) only one form was allowed.  So the body
489 of a function was made into an "implicit `progn'": several forms are
490 allowed just as in the body of an actual `progn'.  Many other control
491 structures likewise contain an implicit `progn'.  As a result, `progn'
492 is not used as often as it used to be.  It is needed now most often
493 inside an `unwind-protect', `and', `or', or in the THEN-part of an `if'.
494
495  - Special Form: progn forms...
496      This special form evaluates all of the FORMS, in textual order,
497      returning the result of the final form.
498
499           (progn (print "The first form")
500                  (print "The second form")
501                  (print "The third form"))
502                -| "The first form"
503                -| "The second form"
504                -| "The third form"
505           => "The third form"
506
507    Two other control constructs likewise evaluate a series of forms but
508 return a different value:
509
510  - Special Form: prog1 form1 forms...
511      This special form evaluates FORM1 and all of the FORMS, in textual
512      order, returning the result of FORM1.
513
514           (prog1 (print "The first form")
515                  (print "The second form")
516                  (print "The third form"))
517                -| "The first form"
518                -| "The second form"
519                -| "The third form"
520           => "The first form"
521
522      Here is a way to remove the first element from a list in the
523      variable `x', then return the value of that former element:
524
525           (prog1 (car x) (setq x (cdr x)))
526
527  - Special Form: prog2 form1 form2 forms...
528      This special form evaluates FORM1, FORM2, and all of the following
529      FORMS, in textual order, returning the result of FORM2.
530
531           (prog2 (print "The first form")
532                  (print "The second form")
533                  (print "The third form"))
534                -| "The first form"
535                -| "The second form"
536                -| "The third form"
537           => "The second form"
538
539 \1f
540 File: lispref.info,  Node: Conditionals,  Next: Combining Conditions,  Prev: Sequencing,  Up: Control Structures
541
542 Conditionals
543 ============
544
545    Conditional control structures choose among alternatives.  XEmacs
546 Lisp has two conditional forms: `if', which is much the same as in other
547 languages, and `cond', which is a generalized case statement.
548
549  - Special Form: if condition then-form else-forms...
550      `if' chooses between the THEN-FORM and the ELSE-FORMS based on the
551      value of CONDITION.  If the evaluated CONDITION is non-`nil',
552      THEN-FORM is evaluated and the result returned.  Otherwise, the
553      ELSE-FORMS are evaluated in textual order, and the value of the
554      last one is returned.  (The ELSE part of `if' is an example of an
555      implicit `progn'.  *Note Sequencing::.)
556
557      If CONDITION has the value `nil', and no ELSE-FORMS are given,
558      `if' returns `nil'.
559
560      `if' is a special form because the branch that is not selected is
561      never evaluated--it is ignored.  Thus, in the example below,
562      `true' is not printed because `print' is never called.
563
564           (if nil
565               (print 'true)
566             'very-false)
567           => very-false
568
569  - Special Form: cond clause...
570      `cond' chooses among an arbitrary number of alternatives.  Each
571      CLAUSE in the `cond' must be a list.  The CAR of this list is the
572      CONDITION; the remaining elements, if any, the BODY-FORMS.  Thus,
573      a clause looks like this:
574
575           (CONDITION BODY-FORMS...)
576
577      `cond' tries the clauses in textual order, by evaluating the
578      CONDITION of each clause.  If the value of CONDITION is non-`nil',
579      the clause "succeeds"; then `cond' evaluates its BODY-FORMS, and
580      the value of the last of BODY-FORMS becomes the value of the
581      `cond'.  The remaining clauses are ignored.
582
583      If the value of CONDITION is `nil', the clause "fails", so the
584      `cond' moves on to the following clause, trying its CONDITION.
585
586      If every CONDITION evaluates to `nil', so that every clause fails,
587      `cond' returns `nil'.
588
589      A clause may also look like this:
590
591           (CONDITION)
592
593      Then, if CONDITION is non-`nil' when tested, the value of
594      CONDITION becomes the value of the `cond' form.
595
596      The following example has four clauses, which test for the cases
597      where the value of `x' is a number, string, buffer and symbol,
598      respectively:
599
600           (cond ((numberp x) x)
601                 ((stringp x) x)
602                 ((bufferp x)
603                  (setq temporary-hack x) ; multiple body-forms
604                  (buffer-name x))        ; in one clause
605                 ((symbolp x) (symbol-value x)))
606
607      Often we want to execute the last clause whenever none of the
608      previous clauses was successful.  To do this, we use `t' as the
609      CONDITION of the last clause, like this: `(t BODY-FORMS)'.  The
610      form `t' evaluates to `t', which is never `nil', so this clause
611      never fails, provided the `cond' gets to it at all.
612
613      For example,
614
615           (cond ((eq a 'hack) 'foo)
616                 (t "default"))
617           => "default"
618
619      This expression is a `cond' which returns `foo' if the value of
620      `a' is 1, and returns the string `"default"' otherwise.
621
622    Any conditional construct can be expressed with `cond' or with `if'.
623 Therefore, the choice between them is a matter of style.  For example:
624
625      (if A B C)
626      ==
627      (cond (A B) (t C))
628
629 \1f
630 File: lispref.info,  Node: Combining Conditions,  Next: Iteration,  Prev: Conditionals,  Up: Control Structures
631
632 Constructs for Combining Conditions
633 ===================================
634
635    This section describes three constructs that are often used together
636 with `if' and `cond' to express complicated conditions.  The constructs
637 `and' and `or' can also be used individually as kinds of multiple
638 conditional constructs.
639
640  - Function: not condition
641      This function tests for the falsehood of CONDITION.  It returns
642      `t' if CONDITION is `nil', and `nil' otherwise.  The function
643      `not' is identical to `null', and we recommend using the name
644      `null' if you are testing for an empty list.
645
646  - Special Form: and conditions...
647      The `and' special form tests whether all the CONDITIONS are true.
648      It works by evaluating the CONDITIONS one by one in the order
649      written.
650
651      If any of the CONDITIONS evaluates to `nil', then the result of
652      the `and' must be `nil' regardless of the remaining CONDITIONS; so
653      `and' returns right away, ignoring the remaining CONDITIONS.
654
655      If all the CONDITIONS turn out non-`nil', then the value of the
656      last of them becomes the value of the `and' form.
657
658      Here is an example.  The first condition returns the integer 1,
659      which is not `nil'.  Similarly, the second condition returns the
660      integer 2, which is not `nil'.  The third condition is `nil', so
661      the remaining condition is never evaluated.
662
663           (and (print 1) (print 2) nil (print 3))
664                -| 1
665                -| 2
666           => nil
667
668      Here is a more realistic example of using `and':
669
670           (if (and (consp foo) (eq (car foo) 'x))
671               (message "foo is a list starting with x"))
672
673      Note that `(car foo)' is not executed if `(consp foo)' returns
674      `nil', thus avoiding an error.
675
676      `and' can be expressed in terms of either `if' or `cond'.  For
677      example:
678
679           (and ARG1 ARG2 ARG3)
680           ==
681           (if ARG1 (if ARG2 ARG3))
682           ==
683           (cond (ARG1 (cond (ARG2 ARG3))))
684
685  - Special Form: or conditions...
686      The `or' special form tests whether at least one of the CONDITIONS
687      is true.  It works by evaluating all the CONDITIONS one by one in
688      the order written.
689
690      If any of the CONDITIONS evaluates to a non-`nil' value, then the
691      result of the `or' must be non-`nil'; so `or' returns right away,
692      ignoring the remaining CONDITIONS.  The value it returns is the
693      non-`nil' value of the condition just evaluated.
694
695      If all the CONDITIONS turn out `nil', then the `or' expression
696      returns `nil'.
697
698      For example, this expression tests whether `x' is either 0 or
699      `nil':
700
701           (or (eq x nil) (eq x 0))
702
703      Like the `and' construct, `or' can be written in terms of `cond'.
704      For example:
705
706           (or ARG1 ARG2 ARG3)
707           ==
708           (cond (ARG1)
709                 (ARG2)
710                 (ARG3))
711
712      You could almost write `or' in terms of `if', but not quite:
713
714           (if ARG1 ARG1
715             (if ARG2 ARG2
716               ARG3))
717
718      This is not completely equivalent because it can evaluate ARG1 or
719      ARG2 twice.  By contrast, `(or ARG1 ARG2 ARG3)' never evaluates
720      any argument more than once.
721
722 \1f
723 File: lispref.info,  Node: Iteration,  Next: Nonlocal Exits,  Prev: Combining Conditions,  Up: Control Structures
724
725 Iteration
726 =========
727
728    Iteration means executing part of a program repetitively.  For
729 example, you might want to repeat some computation once for each element
730 of a list, or once for each integer from 0 to N.  You can do this in
731 XEmacs Lisp with the special form `while':
732
733  - Special Form: while condition forms...
734      `while' first evaluates CONDITION.  If the result is non-`nil', it
735      evaluates FORMS in textual order.  Then it reevaluates CONDITION,
736      and if the result is non-`nil', it evaluates FORMS again.  This
737      process repeats until CONDITION evaluates to `nil'.
738
739      There is no limit on the number of iterations that may occur.  The
740      loop will continue until either CONDITION evaluates to `nil' or
741      until an error or `throw' jumps out of it (*note Nonlocal Exits::).
742
743      The value of a `while' form is always `nil'.
744
745           (setq num 0)
746                => 0
747           (while (< num 4)
748             (princ (format "Iteration %d." num))
749             (setq num (1+ num)))
750                -| Iteration 0.
751                -| Iteration 1.
752                -| Iteration 2.
753                -| Iteration 3.
754                => nil
755
756      If you would like to execute something on each iteration before the
757      end-test, put it together with the end-test in a `progn' as the
758      first argument of `while', as shown here:
759
760           (while (progn
761                    (forward-line 1)
762                    (not (looking-at "^$"))))
763
764      This moves forward one line and continues moving by lines until it
765      reaches an empty.  It is unusual in that the `while' has no body,
766      just the end test (which also does the real work of moving point).
767
768 \1f
769 File: lispref.info,  Node: Nonlocal Exits,  Prev: Iteration,  Up: Control Structures
770
771 Nonlocal Exits
772 ==============
773
774    A "nonlocal exit" is a transfer of control from one point in a
775 program to another remote point.  Nonlocal exits can occur in XEmacs
776 Lisp as a result of errors; you can also use them under explicit
777 control.  Nonlocal exits unbind all variable bindings made by the
778 constructs being exited.
779
780 * Menu:
781
782 * Catch and Throw::     Nonlocal exits for the program's own purposes.
783 * Examples of Catch::   Showing how such nonlocal exits can be written.
784 * Errors::              How errors are signaled and handled.
785 * Cleanups::            Arranging to run a cleanup form if an error happens.
786
787 \1f
788 File: lispref.info,  Node: Catch and Throw,  Next: Examples of Catch,  Up: Nonlocal Exits
789
790 Explicit Nonlocal Exits: `catch' and `throw'
791 --------------------------------------------
792
793    Most control constructs affect only the flow of control within the
794 construct itself.  The function `throw' is the exception to this rule
795 of normal program execution: it performs a nonlocal exit on request.
796 (There are other exceptions, but they are for error handling only.)
797 `throw' is used inside a `catch', and jumps back to that `catch'.  For
798 example:
799
800      (catch 'foo
801        (progn
802          ...
803          (throw 'foo t)
804          ...))
805
806 The `throw' transfers control straight back to the corresponding
807 `catch', which returns immediately.  The code following the `throw' is
808 not executed.  The second argument of `throw' is used as the return
809 value of the `catch'.
810
811    The `throw' and the `catch' are matched through the first argument:
812 `throw' searches for a `catch' whose first argument is `eq' to the one
813 specified.  Thus, in the above example, the `throw' specifies `foo',
814 and the `catch' specifies the same symbol, so that `catch' is
815 applicable.  If there is more than one applicable `catch', the
816 innermost one takes precedence.
817
818    Executing `throw' exits all Lisp constructs up to the matching
819 `catch', including function calls.  When binding constructs such as
820 `let' or function calls are exited in this way, the bindings are
821 unbound, just as they are when these constructs exit normally (*note
822 Local Variables::).  Likewise, `throw' restores the buffer and position
823 saved by `save-excursion' (*note Excursions::), and the narrowing
824 status saved by `save-restriction' and the window selection saved by
825 `save-window-excursion' (*note Window Configurations::).  It also runs
826 any cleanups established with the `unwind-protect' special form when it
827 exits that form (*note Cleanups::).
828
829    The `throw' need not appear lexically within the `catch' that it
830 jumps to.  It can equally well be called from another function called
831 within the `catch'.  As long as the `throw' takes place chronologically
832 after entry to the `catch', and chronologically before exit from it, it
833 has access to that `catch'.  This is why `throw' can be used in
834 commands such as `exit-recursive-edit' that throw back to the editor
835 command loop (*note Recursive Editing::).
836
837      Common Lisp note: Most other versions of Lisp, including Common
838      Lisp, have several ways of transferring control nonsequentially:
839      `return', `return-from', and `go', for example.  XEmacs Lisp has
840      only `throw'.
841
842  - Special Form: catch tag body...
843      `catch' establishes a return point for the `throw' function.  The
844      return point is distinguished from other such return points by TAG,
845      which may be any Lisp object.  The argument TAG is evaluated
846      normally before the return point is established.
847
848      With the return point in effect, `catch' evaluates the forms of the
849      BODY in textual order.  If the forms execute normally, without
850      error or nonlocal exit, the value of the last body form is
851      returned from the `catch'.
852
853      If a `throw' is done within BODY specifying the same value TAG,
854      the `catch' exits immediately; the value it returns is whatever
855      was specified as the second argument of `throw'.
856
857  - Function: throw tag value
858      The purpose of `throw' is to return from a return point previously
859      established with `catch'.  The argument TAG is used to choose
860      among the various existing return points; it must be `eq' to the
861      value specified in the `catch'.  If multiple return points match
862      TAG, the innermost one is used.
863
864      The argument VALUE is used as the value to return from that
865      `catch'.
866
867      If no return point is in effect with tag TAG, then a `no-catch'
868      error is signaled with data `(TAG VALUE)'.
869
870 \1f
871 File: lispref.info,  Node: Examples of Catch,  Next: Errors,  Prev: Catch and Throw,  Up: Nonlocal Exits
872
873 Examples of `catch' and `throw'
874 -------------------------------
875
876    One way to use `catch' and `throw' is to exit from a doubly nested
877 loop.  (In most languages, this would be done with a "go to".)  Here we
878 compute `(foo I J)' for I and J varying from 0 to 9:
879
880      (defun search-foo ()
881        (catch 'loop
882          (let ((i 0))
883            (while (< i 10)
884              (let ((j 0))
885                (while (< j 10)
886                  (if (foo i j)
887                      (throw 'loop (list i j)))
888                  (setq j (1+ j))))
889              (setq i (1+ i))))))
890
891 If `foo' ever returns non-`nil', we stop immediately and return a list
892 of I and J.  If `foo' always returns `nil', the `catch' returns
893 normally, and the value is `nil', since that is the result of the
894 `while'.
895
896    Here are two tricky examples, slightly different, showing two return
897 points at once.  First, two return points with the same tag, `hack':
898
899      (defun catch2 (tag)
900        (catch tag
901          (throw 'hack 'yes)))
902      => catch2
903      
904      (catch 'hack
905        (print (catch2 'hack))
906        'no)
907      -| yes
908      => no
909
910 Since both return points have tags that match the `throw', it goes to
911 the inner one, the one established in `catch2'.  Therefore, `catch2'
912 returns normally with value `yes', and this value is printed.  Finally
913 the second body form in the outer `catch', which is `'no', is evaluated
914 and returned from the outer `catch'.
915
916    Now let's change the argument given to `catch2':
917
918      (defun catch2 (tag)
919        (catch tag
920          (throw 'hack 'yes)))
921      => catch2
922      
923      (catch 'hack
924        (print (catch2 'quux))
925        'no)
926      => yes
927
928 We still have two return points, but this time only the outer one has
929 the tag `hack'; the inner one has the tag `quux' instead.  Therefore,
930 `throw' makes the outer `catch' return the value `yes'.  The function
931 `print' is never called, and the body-form `'no' is never evaluated.
932
933 \1f
934 File: lispref.info,  Node: Errors,  Next: Cleanups,  Prev: Examples of Catch,  Up: Nonlocal Exits
935
936 Errors
937 ------
938
939    When XEmacs Lisp attempts to evaluate a form that, for some reason,
940 cannot be evaluated, it "signals" an "error".
941
942    When an error is signaled, XEmacs's default reaction is to print an
943 error message and terminate execution of the current command.  This is
944 the right thing to do in most cases, such as if you type `C-f' at the
945 end of the buffer.
946
947    In complicated programs, simple termination may not be what you want.
948 For example, the program may have made temporary changes in data
949 structures, or created temporary buffers that should be deleted before
950 the program is finished.  In such cases, you would use `unwind-protect'
951 to establish "cleanup expressions" to be evaluated in case of error.
952 (*Note Cleanups::.)  Occasionally, you may wish the program to continue
953 execution despite an error in a subroutine.  In these cases, you would
954 use `condition-case' to establish "error handlers" to recover control
955 in case of error.
956
957    Resist the temptation to use error handling to transfer control from
958 one part of the program to another; use `catch' and `throw' instead.
959 *Note Catch and Throw::.
960
961 * Menu:
962
963 * Signaling Errors::      How to report an error.
964 * Processing of Errors::  What XEmacs does when you report an error.
965 * Handling Errors::       How you can trap errors and continue execution.
966 * Error Symbols::         How errors are classified for trapping them.
967
968 \1f
969 File: lispref.info,  Node: Signaling Errors,  Next: Processing of Errors,  Up: Errors
970
971 How to Signal an Error
972 ......................
973
974    Most errors are signaled "automatically" within Lisp primitives
975 which you call for other purposes, such as if you try to take the CAR
976 of an integer or move forward a character at the end of the buffer; you
977 can also signal errors explicitly with the functions `error', `signal',
978 and others.
979
980    Quitting, which happens when the user types `C-g', is not considered
981 an error, but it is handled almost like an error.  *Note Quitting::.
982
983  - Function: error format-string &rest args
984      This function signals an error with an error message constructed by
985      applying `format' (*note String Conversion::) to FORMAT-STRING and
986      ARGS.
987
988      This error is not continuable: you cannot continue execution after
989      the error using the debugger `r' or `c' commands.  If you wish the
990      user to be able to continue execution, use `cerror' or `signal'
991      instead.
992
993      These examples show typical uses of `error':
994
995           (error "You have committed an error.
996                   Try something else.")
997                error--> You have committed an error.
998                   Try something else.
999           
1000           (error "You have committed %d errors." 10)
1001                error--> You have committed 10 errors.
1002
1003      `error' works by calling `signal' with two arguments: the error
1004      symbol `error', and a list containing the string returned by
1005      `format'.  This is repeated in an endless loop, to ensure that
1006      `error' never returns.
1007
1008      If you want to use your own string as an error message verbatim,
1009      don't just write `(error STRING)'.  If STRING contains `%', it
1010      will be interpreted as a format specifier, with undesirable
1011      results.  Instead, use `(error "%s" STRING)'.
1012
1013  - Function: cerror format-string &rest args
1014      This function behaves like `error', except that the error it
1015      signals is continuable.  That means that debugger commands `c' and
1016      `r' can resume execution.
1017
1018  - Function: signal error-symbol data
1019      This function signals a continuable error named by ERROR-SYMBOL.
1020      The argument DATA is a list of additional Lisp objects relevant to
1021      the circumstances of the error.
1022
1023      The argument ERROR-SYMBOL must be an "error symbol"--a symbol
1024      bearing a property `error-conditions' whose value is a list of
1025      condition names.  This is how XEmacs Lisp classifies different
1026      sorts of errors.
1027
1028      The number and significance of the objects in DATA depends on
1029      ERROR-SYMBOL.  For example, with a `wrong-type-argument' error,
1030      there are two objects in the list: a predicate that describes the
1031      type that was expected, and the object that failed to fit that
1032      type.  *Note Error Symbols::, for a description of error symbols.
1033
1034      Both ERROR-SYMBOL and DATA are available to any error handlers
1035      that handle the error: `condition-case' binds a local variable to
1036      a list of the form `(ERROR-SYMBOL .  DATA)' (*note Handling
1037      Errors::).  If the error is not handled, these two values are used
1038      in printing the error message.
1039
1040      The function `signal' can return, if the debugger is invoked and
1041      the user invokes the "return from signal" option.  If you want the
1042      error not to be continuable, use `signal-error' instead.  Note that
1043      in FSF Emacs `signal' never returns.
1044
1045           (signal 'wrong-number-of-arguments '(x y))
1046                error--> Wrong number of arguments: x, y
1047           
1048           (signal 'no-such-error '("My unknown error condition"))
1049                error--> Peculiar error (no-such-error "My unknown error condition")
1050
1051  - Function: signal-error error-symbol data
1052      This function behaves like `signal', except that the error it
1053      signals is not continuable.
1054
1055  - Macro: check-argument-type predicate argument
1056      This macro checks that ARGUMENT satisfies PREDICATE.  If that is
1057      not the case, it signals a continuable `wrong-type-argument' error
1058      until the returned value satisfies PREDICATE, and assigns the
1059      returned value to ARGUMENT.  In other words, execution of the
1060      program will not continue until PREDICATE is met.
1061
1062      ARGUMENT is not evaluated, and should be a symbol.  PREDICATE is
1063      evaluated, and should name a function.
1064
1065      As shown in the following example, `check-argument-type' is useful
1066      in low-level code that attempts to ensure the sanity of its data
1067      before proceeding.
1068
1069           (defun cache-object-internal (object wlist)
1070             ;; Before doing anything, make sure that WLIST is indeed
1071             ;; a weak list, which is what we expect.
1072             (check-argument-type 'weak-list-p wlist)
1073             ...)
1074
1075 \1f
1076 File: lispref.info,  Node: Processing of Errors,  Next: Handling Errors,  Prev: Signaling Errors,  Up: Errors
1077
1078 How XEmacs Processes Errors
1079 ...........................
1080
1081    When an error is signaled, `signal' searches for an active "handler"
1082 for the error.  A handler is a sequence of Lisp expressions designated
1083 to be executed if an error happens in part of the Lisp program.  If the
1084 error has an applicable handler, the handler is executed, and control
1085 resumes following the handler.  The handler executes in the environment
1086 of the `condition-case' that established it; all functions called
1087 within that `condition-case' have already been exited, and the handler
1088 cannot return to them.
1089
1090    If there is no applicable handler for the error, the current command
1091 is terminated and control returns to the editor command loop, because
1092 the command loop has an implicit handler for all kinds of errors.  The
1093 command loop's handler uses the error symbol and associated data to
1094 print an error message.
1095
1096    Errors in command loop are processed using the `command-error'
1097 function, which takes care of some necessary cleanup, and prints a
1098 formatted error message to the echo area.  The functions that do the
1099 formatting are explained below.
1100
1101  - Function: display-error error-object stream
1102      This function displays ERROR-OBJECT on STREAM.  ERROR-OBJECT is a
1103      cons of error type, a symbol, and error arguments, a list.  If the
1104      error type symbol of one of its error condition superclasses has
1105      an `display-error' property, that function is invoked for printing
1106      the actual error message.  Otherwise, the error is printed as
1107      `Error: arg1, arg2, ...'.
1108
1109  - Function: error-message-string error-object
1110      This function converts ERROR-OBJECT to an error message string,
1111      and returns it.  The message is equivalent to the one that would be
1112      printed by `display-error', except that it is conveniently returned
1113      in string form.
1114
1115    An error that has no explicit handler may call the Lisp debugger.
1116 The debugger is enabled if the variable `debug-on-error' (*note Error
1117 Debugging::) is non-`nil'.  Unlike error handlers, the debugger runs in
1118 the environment of the error, so that you can examine values of
1119 variables precisely as they were at the time of the error.
1120
1121 \1f
1122 File: lispref.info,  Node: Handling Errors,  Next: Error Symbols,  Prev: Processing of Errors,  Up: Errors
1123
1124 Writing Code to Handle Errors
1125 .............................
1126
1127    The usual effect of signaling an error is to terminate the command
1128 that is running and return immediately to the XEmacs editor command
1129 loop.  You can arrange to trap errors occurring in a part of your
1130 program by establishing an error handler, with the special form
1131 `condition-case'.  A simple example looks like this:
1132
1133      (condition-case nil
1134          (delete-file filename)
1135        (error nil))
1136
1137 This deletes the file named FILENAME, catching any error and returning
1138 `nil' if an error occurs.
1139
1140    The second argument of `condition-case' is called the "protected
1141 form".  (In the example above, the protected form is a call to
1142 `delete-file'.)  The error handlers go into effect when this form
1143 begins execution and are deactivated when this form returns.  They
1144 remain in effect for all the intervening time.  In particular, they are
1145 in effect during the execution of functions called by this form, in
1146 their subroutines, and so on.  This is a good thing, since, strictly
1147 speaking, errors can be signaled only by Lisp primitives (including
1148 `signal' and `error') called by the protected form, not by the
1149 protected form itself.
1150
1151    The arguments after the protected form are handlers.  Each handler
1152 lists one or more "condition names" (which are symbols) to specify
1153 which errors it will handle.  The error symbol specified when an error
1154 is signaled also defines a list of condition names.  A handler applies
1155 to an error if they have any condition names in common.  In the example
1156 above, there is one handler, and it specifies one condition name,
1157 `error', which covers all errors.
1158
1159    The search for an applicable handler checks all the established
1160 handlers starting with the most recently established one.  Thus, if two
1161 nested `condition-case' forms offer to handle the same error, the inner
1162 of the two will actually handle it.
1163
1164    When an error is handled, control returns to the handler.  Before
1165 this happens, XEmacs unbinds all variable bindings made by binding
1166 constructs that are being exited and executes the cleanups of all
1167 `unwind-protect' forms that are exited.  Once control arrives at the
1168 handler, the body of the handler is executed.
1169
1170    After execution of the handler body, execution continues by returning
1171 from the `condition-case' form.  Because the protected form is exited
1172 completely before execution of the handler, the handler cannot resume
1173 execution at the point of the error, nor can it examine variable
1174 bindings that were made within the protected form.  All it can do is
1175 clean up and proceed.
1176
1177    `condition-case' is often used to trap errors that are predictable,
1178 such as failure to open a file in a call to `insert-file-contents'.  It
1179 is also used to trap errors that are totally unpredictable, such as
1180 when the program evaluates an expression read from the user.
1181
1182    Even when an error is handled, the debugger may still be called if
1183 the variable `debug-on-signal' (*note Error Debugging::) is non-`nil'.
1184 Note that this may yield unpredictable results with code that traps
1185 expected errors as normal part of its operation.  Do not set
1186 `debug-on-signal' unless you know what you are doing.
1187
1188    Error signaling and handling have some resemblance to `throw' and
1189 `catch', but they are entirely separate facilities.  An error cannot be
1190 caught by a `catch', and a `throw' cannot be handled by an error
1191 handler (though using `throw' when there is no suitable `catch' signals
1192 an error that can be handled).
1193
1194  - Special Form: condition-case var protected-form handlers...
1195      This special form establishes the error handlers HANDLERS around
1196      the execution of PROTECTED-FORM.  If PROTECTED-FORM executes
1197      without error, the value it returns becomes the value of the
1198      `condition-case' form; in this case, the `condition-case' has no
1199      effect.  The `condition-case' form makes a difference when an
1200      error occurs during PROTECTED-FORM.
1201
1202      Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
1203      Here CONDITIONS is an error condition name to be handled, or a
1204      list of condition names; BODY is one or more Lisp expressions to
1205      be executed when this handler handles an error.  Here are examples
1206      of handlers:
1207
1208           (error nil)
1209           
1210           (arith-error (message "Division by zero"))
1211           
1212           ((arith-error file-error)
1213            (message
1214             "Either division by zero or failure to open a file"))
1215
1216      Each error that occurs has an "error symbol" that describes what
1217      kind of error it is.  The `error-conditions' property of this
1218      symbol is a list of condition names (*note Error Symbols::).  Emacs
1219      searches all the active `condition-case' forms for a handler that
1220      specifies one or more of these condition names; the innermost
1221      matching `condition-case' handles the error.  Within this
1222      `condition-case', the first applicable handler handles the error.
1223
1224      After executing the body of the handler, the `condition-case'
1225      returns normally, using the value of the last form in the handler
1226      body as the overall value.
1227
1228      The argument VAR is a variable.  `condition-case' does not bind
1229      this variable when executing the PROTECTED-FORM, only when it
1230      handles an error.  At that time, it binds VAR locally to a list of
1231      the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
1232      error.  The handler can refer to this list to decide what to do.
1233      For example, if the error is for failure opening a file, the file
1234      name is the second element of DATA--the third element of VAR.
1235
1236      If VAR is `nil', that means no variable is bound.  Then the error
1237      symbol and associated data are not available to the handler.
1238
1239    Here is an example of using `condition-case' to handle the error
1240 that results from dividing by zero.  The handler prints out a warning
1241 message and returns a very large number.
1242
1243      (defun safe-divide (dividend divisor)
1244        (condition-case err
1245            ;; Protected form.
1246            (/ dividend divisor)
1247          ;; The handler.
1248          (arith-error                        ; Condition.
1249           (princ (format "Arithmetic error: %s" err))
1250           1000000)))
1251      => safe-divide
1252      
1253      (safe-divide 5 0)
1254           -| Arithmetic error: (arith-error)
1255      => 1000000
1256
1257 The handler specifies condition name `arith-error' so that it will
1258 handle only division-by-zero errors.  Other kinds of errors will not be
1259 handled, at least not by this `condition-case'.  Thus,
1260
1261      (safe-divide nil 3)
1262           error--> Wrong type argument: integer-or-marker-p, nil
1263
1264    Here is a `condition-case' that catches all kinds of errors,
1265 including those signaled with `error':
1266
1267      (setq baz 34)
1268           => 34
1269      
1270      (condition-case err
1271          (if (eq baz 35)
1272              t
1273            ;; This is a call to the function `error'.
1274            (error "Rats!  The variable %s was %s, not 35" 'baz baz))
1275        ;; This is the handler; it is not a form.
1276        (error (princ (format "The error was: %s" err))
1277               2))
1278      -| The error was: (error "Rats!  The variable baz was 34, not 35")
1279      => 2
1280