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