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