This commit was generated by cvs2svn to compensate for changes in r6453,
[chise/xemacs-chise.git.1] / info / lispref.info-8
1 This is Info file ../../info/lispref.info, produced by Makeinfo version
2 1.68 from the input file 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' and
945 `signal'.
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      These examples show typical uses of `error':
956
957           (error "You have committed an error.
958                   Try something else.")
959                error--> You have committed an error.
960                   Try something else.
961           
962           (error "You have committed %d errors." 10)
963                error--> You have committed 10 errors.
964
965      `error' works by calling `signal' with two arguments: the error
966      symbol `error', and a list containing the string returned by
967      `format'.
968
969      If you want to use your own string as an error message verbatim,
970      don't just write `(error STRING)'.  If STRING contains `%', it
971      will be interpreted as a format specifier, with undesirable
972      results.  Instead, use `(error "%s" STRING)'.
973
974  - Function: signal ERROR-SYMBOL DATA
975      This function signals an error named by ERROR-SYMBOL.  The
976      argument DATA is a list of additional Lisp objects relevant to the
977      circumstances of the error.
978
979      The argument ERROR-SYMBOL must be an "error symbol"--a symbol
980      bearing a property `error-conditions' whose value is a list of
981      condition names.  This is how XEmacs Lisp classifies different
982      sorts of errors.
983
984      The number and significance of the objects in DATA depends on
985      ERROR-SYMBOL.  For example, with a `wrong-type-arg' error, there
986      are two objects in the list: a predicate that describes the type
987      that was expected, and the object that failed to fit that type.
988      *Note Error Symbols::, for a description of error symbols.
989
990      Both ERROR-SYMBOL and DATA are available to any error handlers
991      that handle the error: `condition-case' binds a local variable to
992      a list of the form `(ERROR-SYMBOL .  DATA)' (*note Handling
993      Errors::.).  If the error is not handled, these two values are
994      used in printing the error message.
995
996      The function `signal' never returns (though in older Emacs versions
997      it could sometimes return).
998
999           (signal 'wrong-number-of-arguments '(x y))
1000                error--> Wrong number of arguments: x, y
1001
1002           (signal 'no-such-error '("My unknown error condition."))
1003                error--> peculiar error: "My unknown error condition."
1004
1005      Common Lisp note: XEmacs Lisp has nothing like the Common Lisp
1006      concept of continuable errors.
1007
1008 \1f
1009 File: lispref.info,  Node: Processing of Errors,  Next: Handling Errors,  Prev: Signaling Errors,  Up: Errors
1010
1011 How XEmacs Processes Errors
1012 ...........................
1013
1014    When an error is signaled, `signal' searches for an active "handler"
1015 for the error.  A handler is a sequence of Lisp expressions designated
1016 to be executed if an error happens in part of the Lisp program.  If the
1017 error has an applicable handler, the handler is executed, and control
1018 resumes following the handler.  The handler executes in the environment
1019 of the `condition-case' that established it; all functions called
1020 within that `condition-case' have already been exited, and the handler
1021 cannot return to them.
1022
1023    If there is no applicable handler for the error, the current command
1024 is terminated and control returns to the editor command loop, because
1025 the command loop has an implicit handler for all kinds of errors.  The
1026 command loop's handler uses the error symbol and associated data to
1027 print an error message.
1028
1029    An error that has no explicit handler may call the Lisp debugger.
1030 The debugger is enabled if the variable `debug-on-error' (*note Error
1031 Debugging::.) is non-`nil'.  Unlike error handlers, the debugger runs
1032 in the environment of the error, so that you can examine values of
1033 variables precisely as they were at the time of the error.
1034
1035 \1f
1036 File: lispref.info,  Node: Handling Errors,  Next: Error Symbols,  Prev: Processing of Errors,  Up: Errors
1037
1038 Writing Code to Handle Errors
1039 .............................
1040
1041    The usual effect of signaling an error is to terminate the command
1042 that is running and return immediately to the XEmacs editor command
1043 loop.  You can arrange to trap errors occurring in a part of your
1044 program by establishing an error handler, with the special form
1045 `condition-case'.  A simple example looks like this:
1046
1047      (condition-case nil
1048          (delete-file filename)
1049        (error nil))
1050
1051 This deletes the file named FILENAME, catching any error and returning
1052 `nil' if an error occurs.
1053
1054    The second argument of `condition-case' is called the "protected
1055 form".  (In the example above, the protected form is a call to
1056 `delete-file'.)  The error handlers go into effect when this form
1057 begins execution and are deactivated when this form returns.  They
1058 remain in effect for all the intervening time.  In particular, they are
1059 in effect during the execution of functions called by this form, in
1060 their subroutines, and so on.  This is a good thing, since, strictly
1061 speaking, errors can be signaled only by Lisp primitives (including
1062 `signal' and `error') called by the protected form, not by the
1063 protected form itself.
1064
1065    The arguments after the protected form are handlers.  Each handler
1066 lists one or more "condition names" (which are symbols) to specify
1067 which errors it will handle.  The error symbol specified when an error
1068 is signaled also defines a list of condition names.  A handler applies
1069 to an error if they have any condition names in common.  In the example
1070 above, there is one handler, and it specifies one condition name,
1071 `error', which covers all errors.
1072
1073    The search for an applicable handler checks all the established
1074 handlers starting with the most recently established one.  Thus, if two
1075 nested `condition-case' forms offer to handle the same error, the inner
1076 of the two will actually handle it.
1077
1078    When an error is handled, control returns to the handler.  Before
1079 this happens, XEmacs unbinds all variable bindings made by binding
1080 constructs that are being exited and executes the cleanups of all
1081 `unwind-protect' forms that are exited.  Once control arrives at the
1082 handler, the body of the handler is executed.
1083
1084    After execution of the handler body, execution continues by returning
1085 from the `condition-case' form.  Because the protected form is exited
1086 completely before execution of the handler, the handler cannot resume
1087 execution at the point of the error, nor can it examine variable
1088 bindings that were made within the protected form.  All it can do is
1089 clean up and proceed.
1090
1091    `condition-case' is often used to trap errors that are predictable,
1092 such as failure to open a file in a call to `insert-file-contents'.  It
1093 is also used to trap errors that are totally unpredictable, such as
1094 when the program evaluates an expression read from the user.
1095
1096    Error signaling and handling have some resemblance to `throw' and
1097 `catch', but they are entirely separate facilities.  An error cannot be
1098 caught by a `catch', and a `throw' cannot be handled by an error
1099 handler (though using `throw' when there is no suitable `catch' signals
1100 an error that can be handled).
1101
1102  - Special Form: condition-case VAR PROTECTED-FORM HANDLERS...
1103      This special form establishes the error handlers HANDLERS around
1104      the execution of PROTECTED-FORM.  If PROTECTED-FORM executes
1105      without error, the value it returns becomes the value of the
1106      `condition-case' form; in this case, the `condition-case' has no
1107      effect.  The `condition-case' form makes a difference when an
1108      error occurs during PROTECTED-FORM.
1109
1110      Each of the HANDLERS is a list of the form `(CONDITIONS BODY...)'.
1111      Here CONDITIONS is an error condition name to be handled, or a
1112      list of condition names; BODY is one or more Lisp expressions to
1113      be executed when this handler handles an error.  Here are examples
1114      of handlers:
1115
1116           (error nil)
1117           
1118           (arith-error (message "Division by zero"))
1119           
1120           ((arith-error file-error)
1121            (message
1122             "Either division by zero or failure to open a file"))
1123
1124      Each error that occurs has an "error symbol" that describes what
1125      kind of error it is.  The `error-conditions' property of this
1126      symbol is a list of condition names (*note Error Symbols::.).
1127      Emacs searches all the active `condition-case' forms for a handler
1128      that specifies one or more of these condition names; the innermost
1129      matching `condition-case' handles the error.  Within this
1130      `condition-case', the first applicable handler handles the error.
1131
1132      After executing the body of the handler, the `condition-case'
1133      returns normally, using the value of the last form in the handler
1134      body as the overall value.
1135
1136      The argument VAR is a variable.  `condition-case' does not bind
1137      this variable when executing the PROTECTED-FORM, only when it
1138      handles an error.  At that time, it binds VAR locally to a list of
1139      the form `(ERROR-SYMBOL . DATA)', giving the particulars of the
1140      error.  The handler can refer to this list to decide what to do.
1141      For example, if the error is for failure opening a file, the file
1142      name is the second element of DATA--the third element of VAR.
1143
1144      If VAR is `nil', that means no variable is bound.  Then the error
1145      symbol and associated data are not available to the handler.
1146
1147    Here is an example of using `condition-case' to handle the error
1148 that results from dividing by zero.  The handler prints out a warning
1149 message and returns a very large number.
1150
1151      (defun safe-divide (dividend divisor)
1152        (condition-case err
1153            ;; Protected form.
1154            (/ dividend divisor)
1155          ;; The handler.
1156          (arith-error                        ; Condition.
1157           (princ (format "Arithmetic error: %s" err))
1158           1000000)))
1159      => safe-divide
1160
1161      (safe-divide 5 0)
1162           -| Arithmetic error: (arith-error)
1163      => 1000000
1164
1165 The handler specifies condition name `arith-error' so that it will
1166 handle only division-by-zero errors.  Other kinds of errors will not be
1167 handled, at least not by this `condition-case'.  Thus,
1168
1169      (safe-divide nil 3)
1170           error--> Wrong type argument: integer-or-marker-p, nil
1171
1172    Here is a `condition-case' that catches all kinds of errors,
1173 including those signaled with `error':
1174
1175      (setq baz 34)
1176           => 34
1177
1178      (condition-case err
1179          (if (eq baz 35)
1180              t
1181            ;; This is a call to the function `error'.
1182            (error "Rats!  The variable %s was %s, not 35" 'baz baz))
1183        ;; This is the handler; it is not a form.
1184        (error (princ (format "The error was: %s" err))
1185               2))
1186      -| The error was: (error "Rats!  The variable baz was 34, not 35")
1187      => 2
1188
1189 \1f
1190 File: lispref.info,  Node: Error Symbols,  Prev: Handling Errors,  Up: Errors
1191
1192 Error Symbols and Condition Names
1193 .................................
1194
1195    When you signal an error, you specify an "error symbol" to specify
1196 the kind of error you have in mind.  Each error has one and only one
1197 error symbol to categorize it.  This is the finest classification of
1198 errors defined by the XEmacs Lisp language.
1199
1200    These narrow classifications are grouped into a hierarchy of wider
1201 classes called "error conditions", identified by "condition names".
1202 The narrowest such classes belong to the error symbols themselves: each
1203 error symbol is also a condition name.  There are also condition names
1204 for more extensive classes, up to the condition name `error' which
1205 takes in all kinds of errors.  Thus, each error has one or more
1206 condition names: `error', the error symbol if that is distinct from
1207 `error', and perhaps some intermediate classifications.
1208
1209    In order for a symbol to be an error symbol, it must have an
1210 `error-conditions' property which gives a list of condition names.
1211 This list defines the conditions that this kind of error belongs to.
1212 (The error symbol itself, and the symbol `error', should always be
1213 members of this list.)  Thus, the hierarchy of condition names is
1214 defined by the `error-conditions' properties of the error symbols.
1215
1216    In addition to the `error-conditions' list, the error symbol should
1217 have an `error-message' property whose value is a string to be printed
1218 when that error is signaled but not handled.  If the `error-message'
1219 property exists, but is not a string, the error message `peculiar
1220 error' is used.
1221
1222    Here is how we define a new error symbol, `new-error':
1223
1224      (put 'new-error
1225           'error-conditions
1226           '(error my-own-errors new-error))
1227      => (error my-own-errors new-error)
1228      (put 'new-error 'error-message "A new error")
1229      => "A new error"
1230
1231 This error has three condition names: `new-error', the narrowest
1232 classification; `my-own-errors', which we imagine is a wider
1233 classification; and `error', which is the widest of all.
1234
1235    The error string should start with a capital letter but it should
1236 not end with a period.  This is for consistency with the rest of Emacs.
1237
1238    Naturally, XEmacs will never signal `new-error' on its own; only an
1239 explicit call to `signal' (*note Signaling Errors::.) in your code can
1240 do this:
1241
1242      (signal 'new-error '(x y))
1243           error--> A new error: x, y
1244
1245    This error can be handled through any of the three condition names.
1246 This example handles `new-error' and any other errors in the class
1247 `my-own-errors':
1248
1249      (condition-case foo
1250          (bar nil t)
1251        (my-own-errors nil))
1252
1253    The significant way that errors are classified is by their condition
1254 names--the names used to match errors with handlers.  An error symbol
1255 serves only as a convenient way to specify the intended error message
1256 and list of condition names.  It would be cumbersome to give `signal' a
1257 list of condition names rather than one error symbol.
1258
1259    By contrast, using only error symbols without condition names would
1260 seriously decrease the power of `condition-case'.  Condition names make
1261 it possible to categorize errors at various levels of generality when
1262 you write an error handler.  Using error symbols alone would eliminate
1263 all but the narrowest level of classification.
1264
1265    *Note Standard Errors::, for a list of all the standard error symbols
1266 and their conditions.
1267