This commit was generated by cvs2svn to compensate for changes in r5197,
[chise/xemacs-chise.git.1] / info / cl.info-2
1 This is Info file ../info/cl.info, produced by Makeinfo version 1.68
2 from the input file cl.texi.
3
4 INFO-DIR-SECTION XEmacs Editor
5 START-INFO-DIR-ENTRY
6 * Common Lisp: (cl).            GNU Emacs Common Lisp emulation package.
7 END-INFO-DIR-ENTRY
8
9    This file documents the GNU Emacs Common Lisp emulation package.
10
11    Copyright (C) 1993 Free Software Foundation, Inc.
12
13    Permission is granted to make and distribute verbatim copies of this
14 manual provided the copyright notice and this permission notice are
15 preserved on all copies.
16
17    Permission is granted to copy and distribute modified versions of
18 this manual under the conditions for verbatim copying, provided also
19 that the section entitled "GNU General Public License" is included
20 exactly as in the original, and provided that the entire resulting
21 derived work is distributed under the terms of a permission notice
22 identical to this one.
23
24    Permission is granted to copy and distribute translations of this
25 manual into another language, under the above conditions for modified
26 versions, except that the section entitled "GNU General Public License"
27 may be included in a translation approved by the author instead of in
28 the original English.
29
30 \1f
31 File: cl.info,  Node: Modify Macros,  Next: Customizing Setf,  Prev: Basic Setf,  Up: Generalized Variables
32
33 Modify Macros
34 -------------
35
36 This package defines a number of other macros besides `setf' that
37 operate on generalized variables.  Many are interesting and useful even
38 when the PLACE is just a variable name.
39
40  - Special Form: psetf [PLACE FORM]...
41      This macro is to `setf' what `psetq' is to `setq': When several
42      PLACEs and FORMs are involved, the assignments take place in
43      parallel rather than sequentially.  Specifically, all subforms are
44      evaluated from left to right, then all the assignments are done
45      (in an undefined order).
46
47  - Special Form: incf PLACE &optional X
48      This macro increments the number stored in PLACE by one, or by X
49      if specified.  The incremented value is returned.  For example,
50      `(incf i)' is equivalent to `(setq i (1+ i))', and `(incf (car x)
51      2)' is equivalent to `(setcar x (+ (car x) 2))'.
52
53      Once again, care is taken to preserve the "apparent" order of
54      evaluation.  For example,
55
56           (incf (aref vec (incf i)))
57
58      appears to increment `i' once, then increment the element of `vec'
59      addressed by `i'; this is indeed exactly what it does, which means
60      the above form is *not* equivalent to the "obvious" expansion,
61
62           (setf (aref vec (incf i)) (1+ (aref vec (incf i))))   ; Wrong!
63
64      but rather to something more like
65
66           (let ((temp (incf i)))
67             (setf (aref vec temp) (1+ (aref vec temp))))
68
69      Again, all of this is taken care of automatically by `incf' and
70      the other generalized-variable macros.
71
72      As a more Emacs-specific example of `incf', the expression `(incf
73      (point) N)' is essentially equivalent to `(forward-char N)'.
74
75  - Special Form: decf PLACE &optional X
76      This macro decrements the number stored in PLACE by one, or by X
77      if specified.
78
79  - Special Form: pop PLACE
80      This macro removes and returns the first element of the list stored
81      in PLACE.  It is analogous to `(prog1 (car PLACE) (setf PLACE (cdr
82      PLACE)))', except that it takes care to evaluate all subforms only
83      once.
84
85  - Special Form: push X PLACE
86      This macro inserts X at the front of the list stored in PLACE.  It
87      is analogous to `(setf PLACE (cons X PLACE))', except for
88      evaluation of the subforms.
89
90  - Special Form: pushnew X PLACE &key :test :test-not :key
91      This macro inserts X at the front of the list stored in PLACE, but
92      only if X was not `eql' to any existing element of the list.  The
93      optional keyword arguments are interpreted in the same way as for
94      `adjoin'.  *Note Lists as Sets::.
95
96  - Special Form: shiftf PLACE... NEWVALUE
97      This macro shifts the PLACEs left by one, shifting in the value of
98      NEWVALUE (which may be any Lisp expression, not just a generalized
99      variable), and returning the value shifted out of the first PLACE.
100      Thus, `(shiftf A B C D)' is equivalent to
101
102           (prog1
103               A
104             (psetf A B
105                    B C
106                    C D))
107
108      except that the subforms of A, B, and C are actually evaluated
109      only once each and in the apparent order.
110
111  - Special Form: rotatef PLACE...
112      This macro rotates the PLACEs left by one in circular fashion.
113      Thus, `(rotatef A B C D)' is equivalent to
114
115           (psetf A B
116                  B C
117                  C D
118                  D A)
119
120      except for the evaluation of subforms.  `rotatef' always returns
121      `nil'.  Note that `(rotatef A B)' conveniently exchanges A and B.
122
123    The following macros were invented for this package; they have no
124 analogues in Common Lisp.
125
126  - Special Form: letf (BINDINGS...) FORMS...
127      This macro is analogous to `let', but for generalized variables
128      rather than just symbols.  Each BINDING should be of the form
129      `(PLACE VALUE)'; the original contents of the PLACEs are saved,
130      the VALUEs are stored in them, and then the body FORMs are
131      executed.  Afterwards, the PLACES are set back to their original
132      saved contents.  This cleanup happens even if the FORMs exit
133      irregularly due to a `throw' or an error.
134
135      For example,
136
137           (letf (((point) (point-min))
138                  (a 17))
139             ...)
140
141      moves "point" in the current buffer to the beginning of the buffer,
142      and also binds `a' to 17 (as if by a normal `let', since `a' is
143      just a regular variable).  After the body exits, `a' is set back
144      to its original value and point is moved back to its original
145      position.
146
147      Note that `letf' on `(point)' is not quite like a
148      `save-excursion', as the latter effectively saves a marker which
149      tracks insertions and deletions in the buffer.  Actually, a `letf'
150      of `(point-marker)' is much closer to this behavior.  (`point' and
151      `point-marker' are equivalent as `setf' places; each will accept
152      either an integer or a marker as the stored value.)
153
154      Since generalized variables look like lists, `let''s shorthand of
155      using `foo' for `(foo nil)' as a BINDING would be ambiguous in
156      `letf' and is not allowed.
157
158      However, a BINDING specifier may be a one-element list `(PLACE)',
159      which is similar to `(PLACE PLACE)'.  In other words, the PLACE is
160      not disturbed on entry to the body, and the only effect of the
161      `letf' is to restore the original value of PLACE afterwards.  (The
162      redundant access-and-store suggested by the `(PLACE PLACE)'
163      example does not actually occur.)
164
165      In most cases, the PLACE must have a well-defined value on entry
166      to the `letf' form.  The only exceptions are plain variables and
167      calls to `symbol-value' and `symbol-function'.  If the symbol is
168      not bound on entry, it is simply made unbound by `makunbound' or
169      `fmakunbound' on exit.
170
171  - Special Form: letf* (BINDINGS...) FORMS...
172      This macro is to `letf' what `let*' is to `let': It does the
173      bindings in sequential rather than parallel order.
174
175  - Special Form: callf FUNCTION PLACE ARGS...
176      This is the "generic" modify macro.  It calls FUNCTION, which
177      should be an unquoted function name, macro name, or lambda.  It
178      passes PLACE and ARGS as arguments, and assigns the result back to
179      PLACE.  For example, `(incf PLACE N)' is the same as `(callf +
180      PLACE N)'.  Some more examples:
181
182           (callf abs my-number)
183           (callf concat (buffer-name) "<" (int-to-string n) ">")
184           (callf union happy-people (list joe bob) :test 'same-person)
185
186      *Note Customizing Setf::, for `define-modify-macro', a way to
187      create even more concise notations for modify macros.  Note again
188      that `callf' is an extension to standard Common Lisp.
189
190  - Special Form: callf2 FUNCTION ARG1 PLACE ARGS...
191      This macro is like `callf', except that PLACE is the *second*
192      argument of FUNCTION rather than the first.  For example, `(push X
193      PLACE)' is equivalent to `(callf2 cons X PLACE)'.
194
195    The `callf' and `callf2' macros serve as building blocks for other
196 macros like `incf', `pushnew', and `define-modify-macro'.  The `letf'
197 and `letf*' macros are used in the processing of symbol macros; *note
198 Macro Bindings::..
199
200 \1f
201 File: cl.info,  Node: Customizing Setf,  Prev: Modify Macros,  Up: Generalized Variables
202
203 Customizing Setf
204 ----------------
205
206 Common Lisp defines three macros, `define-modify-macro', `defsetf', and
207 `define-setf-method', that allow the user to extend generalized
208 variables in various ways.
209
210  - Special Form: define-modify-macro NAME ARGLIST FUNCTION [DOC-STRING]
211      This macro defines a "read-modify-write" macro similar to `incf'
212      and `decf'.  The macro NAME is defined to take a PLACE argument
213      followed by additional arguments described by ARGLIST.  The call
214
215           (NAME PLACE ARGS...)
216
217      will be expanded to
218
219           (callf FUNC PLACE ARGS...)
220
221      which in turn is roughly equivalent to
222
223           (setf PLACE (FUNC PLACE ARGS...))
224
225      For example:
226
227           (define-modify-macro incf (&optional (n 1)) +)
228           (define-modify-macro concatf (&rest args) concat)
229
230      Note that `&key' is not allowed in ARGLIST, but `&rest' is
231      sufficient to pass keywords on to the function.
232
233      Most of the modify macros defined by Common Lisp do not exactly
234      follow the pattern of `define-modify-macro'.  For example, `push'
235      takes its arguments in the wrong order, and `pop' is completely
236      irregular.  You can define these macros "by hand" using
237      `get-setf-method', or consult the source file `cl-macs.el' to see
238      how to use the internal `setf' building blocks.
239
240  - Special Form: defsetf ACCESS-FN UPDATE-FN
241      This is the simpler of two `defsetf' forms.  Where ACCESS-FN is
242      the name of a function which accesses a place, this declares
243      UPDATE-FN to be the corresponding store function.  From now on,
244
245           (setf (ACCESS-FN ARG1 ARG2 ARG3) VALUE)
246
247      will be expanded to
248
249           (UPDATE-FN ARG1 ARG2 ARG3 VALUE)
250
251      The UPDATE-FN is required to be either a true function, or a macro
252      which evaluates its arguments in a function-like way.  Also, the
253      UPDATE-FN is expected to return VALUE as its result.  Otherwise,
254      the above expansion would not obey the rules for the way `setf' is
255      supposed to behave.
256
257      As a special (non-Common-Lisp) extension, a third argument of `t'
258      to `defsetf' says that the `update-fn''s return value is not
259      suitable, so that the above `setf' should be expanded to something
260      more like
261
262           (let ((temp VALUE))
263             (UPDATE-FN ARG1 ARG2 ARG3 temp)
264             temp)
265
266      Some examples of the use of `defsetf', drawn from the standard
267      suite of setf methods, are:
268
269           (defsetf car setcar)
270           (defsetf symbol-value set)
271           (defsetf buffer-name rename-buffer t)
272
273  - Special Form: defsetf ACCESS-FN ARGLIST (STORE-VAR) FORMS...
274      This is the second, more complex, form of `defsetf'.  It is rather
275      like `defmacro' except for the additional STORE-VAR argument.  The
276      FORMS should return a Lisp form which stores the value of
277      STORE-VAR into the generalized variable formed by a call to
278      ACCESS-FN with arguments described by ARGLIST.  The FORMS may
279      begin with a string which documents the `setf' method (analogous
280      to the doc string that appears at the front of a function).
281
282      For example, the simple form of `defsetf' is shorthand for
283
284           (defsetf ACCESS-FN (&rest args) (store)
285             (append '(UPDATE-FN) args (list store)))
286
287      The Lisp form that is returned can access the arguments from
288      ARGLIST and STORE-VAR in an unrestricted fashion; macros like
289      `setf' and `incf' which invoke this setf-method will insert
290      temporary variables as needed to make sure the apparent order of
291      evaluation is preserved.
292
293      Another example drawn from the standard package:
294
295           (defsetf nth (n x) (store)
296             (list 'setcar (list 'nthcdr n x) store))
297
298  - Special Form: define-setf-method ACCESS-FN ARGLIST FORMS...
299      This is the most general way to create new place forms.  When a
300      `setf' to ACCESS-FN with arguments described by ARGLIST is
301      expanded, the FORMS are evaluated and must return a list of five
302      items:
303
304        1. A list of "temporary variables".
305
306        2. A list of "value forms" corresponding to the temporary
307           variables above.  The temporary variables will be bound to
308           these value forms as the first step of any operation on the
309           generalized variable.
310
311        3. A list of exactly one "store variable" (generally obtained
312           from a call to `gensym').
313
314        4. A Lisp form which stores the contents of the store variable
315           into the generalized variable, assuming the temporaries have
316           been bound as described above.
317
318        5. A Lisp form which accesses the contents of the generalized
319           variable, assuming the temporaries have been bound.
320
321      This is exactly like the Common Lisp macro of the same name,
322      except that the method returns a list of five values rather than
323      the five values themselves, since Emacs Lisp does not support
324      Common Lisp's notion of multiple return values.
325
326      Once again, the FORMS may begin with a documentation string.
327
328      A setf-method should be maximally conservative with regard to
329      temporary variables.  In the setf-methods generated by `defsetf',
330      the second return value is simply the list of arguments in the
331      place form, and the first return value is a list of a
332      corresponding number of temporary variables generated by `gensym'.
333      Macros like `setf' and `incf' which use this setf-method will
334      optimize away most temporaries that turn out to be unnecessary, so
335      there is little reason for the setf-method itself to optimize.
336
337  - Function: get-setf-method PLACE &optional ENV
338      This function returns the setf-method for PLACE, by invoking the
339      definition previously recorded by `defsetf' or
340      `define-setf-method'.  The result is a list of five values as
341      described above.  You can use this function to build your own
342      `incf'-like modify macros.  (Actually, it is better to use the
343      internal functions `cl-setf-do-modify' and `cl-setf-do-store',
344      which are a bit easier to use and which also do a number of
345      optimizations; consult the source code for the `incf' function for
346      a simple example.)
347
348      The argument ENV specifies the "environment" to be passed on to
349      `macroexpand' if `get-setf-method' should need to expand a macro
350      in PLACE.  It should come from an `&environment' argument to the
351      macro or setf-method that called `get-setf-method'.
352
353      See also the source code for the setf-methods for `apply' and
354      `substring', each of which works by calling `get-setf-method' on a
355      simpler case, then massaging the result in various ways.
356
357    Modern Common Lisp defines a second, independent way to specify the
358 `setf' behavior of a function, namely "`setf' functions" whose names
359 are lists `(setf NAME)' rather than symbols.  For example, `(defun
360 (setf foo) ...)'  defines the function that is used when `setf' is
361 applied to `foo'.  This package does not currently support `setf'
362 functions.  In particular, it is a compile-time error to use `setf' on
363 a form which has not already been `defsetf''d or otherwise declared; in
364 newer Common Lisps, this would not be an error since the function
365 `(setf FUNC)' might be defined later.
366
367 \1f
368 File: cl.info,  Node: Variable Bindings,  Next: Conditionals,  Prev: Generalized Variables,  Up: Control Structure
369
370 Variable Bindings
371 =================
372
373 These Lisp forms make bindings to variables and function names,
374 analogous to Lisp's built-in `let' form.
375
376    *Note Modify Macros::, for the `letf' and `letf*' forms which are
377 also related to variable bindings.
378
379 * Menu:
380
381 * Dynamic Bindings::     The `progv' form
382 * Lexical Bindings::     `lexical-let' and lexical closures
383 * Function Bindings::    `flet' and `labels'
384 * Macro Bindings::       `macrolet' and `symbol-macrolet'
385
386 \1f
387 File: cl.info,  Node: Dynamic Bindings,  Next: Lexical Bindings,  Prev: Variable Bindings,  Up: Variable Bindings
388
389 Dynamic Bindings
390 ----------------
391
392 The standard `let' form binds variables whose names are known at
393 compile-time.  The `progv' form provides an easy way to bind variables
394 whose names are computed at run-time.
395
396  - Special Form: progv SYMBOLS VALUES FORMS...
397      This form establishes `let'-style variable bindings on a set of
398      variables computed at run-time.  The expressions SYMBOLS and
399      VALUES are evaluated, and must return lists of symbols and values,
400      respectively.  The symbols are bound to the corresponding values
401      for the duration of the body FORMs.  If VALUES is shorter than
402      SYMBOLS, the last few symbols are made unbound (as if by
403      `makunbound') inside the body.  If SYMBOLS is shorter than VALUES,
404      the excess values are ignored.
405
406 \1f
407 File: cl.info,  Node: Lexical Bindings,  Next: Function Bindings,  Prev: Dynamic Bindings,  Up: Variable Bindings
408
409 Lexical Bindings
410 ----------------
411
412 The "CL" package defines the following macro which more closely follows
413 the Common Lisp `let' form:
414
415  - Special Form: lexical-let (BINDINGS...) FORMS...
416      This form is exactly like `let' except that the bindings it
417      establishes are purely lexical.  Lexical bindings are similar to
418      local variables in a language like C:  Only the code physically
419      within the body of the `lexical-let' (after macro expansion) may
420      refer to the bound variables.
421
422           (setq a 5)
423           (defun foo (b) (+ a b))
424           (let ((a 2)) (foo a))
425                => 4
426           (lexical-let ((a 2)) (foo a))
427                => 7
428
429      In this example, a regular `let' binding of `a' actually makes a
430      temporary change to the global variable `a', so `foo' is able to
431      see the binding of `a' to 2.  But `lexical-let' actually creates a
432      distinct local variable `a' for use within its body, without any
433      effect on the global variable of the same name.
434
435      The most important use of lexical bindings is to create "closures".
436      A closure is a function object that refers to an outside lexical
437      variable.  For example:
438
439           (defun make-adder (n)
440             (lexical-let ((n n))
441               (function (lambda (m) (+ n m)))))
442           (setq add17 (make-adder 17))
443           (funcall add17 4)
444                => 21
445
446      The call `(make-adder 17)' returns a function object which adds 17
447      to its argument.  If `let' had been used instead of `lexical-let',
448      the function object would have referred to the global `n', which
449      would have been bound to 17 only during the call to `make-adder'
450      itself.
451
452           (defun make-counter ()
453             (lexical-let ((n 0))
454               (function* (lambda (&optional (m 1)) (incf n m)))))
455           (setq count-1 (make-counter))
456           (funcall count-1 3)
457                => 3
458           (funcall count-1 14)
459                => 17
460           (setq count-2 (make-counter))
461           (funcall count-2 5)
462                => 5
463           (funcall count-1 2)
464                => 19
465           (funcall count-2)
466                => 6
467
468      Here we see that each call to `make-counter' creates a distinct
469      local variable `n', which serves as a private counter for the
470      function object that is returned.
471
472      Closed-over lexical variables persist until the last reference to
473      them goes away, just like all other Lisp objects.  For example,
474      `count-2' refers to a function object which refers to an instance
475      of the variable `n'; this is the only reference to that variable,
476      so after `(setq count-2 nil)' the garbage collector would be able
477      to delete this instance of `n'.  Of course, if a `lexical-let'
478      does not actually create any closures, then the lexical variables
479      are free as soon as the `lexical-let' returns.
480
481      Many closures are used only during the extent of the bindings they
482      refer to; these are known as "downward funargs" in Lisp parlance.
483      When a closure is used in this way, regular Emacs Lisp dynamic
484      bindings suffice and will be more efficient than `lexical-let'
485      closures:
486
487           (defun add-to-list (x list)
488             (mapcar (function (lambda (y) (+ x y))) list))
489           (add-to-list 7 '(1 2 5))
490                => (8 9 12)
491
492      Since this lambda is only used while `x' is still bound, it is not
493      necessary to make a true closure out of it.
494
495      You can use `defun' or `flet' inside a `lexical-let' to create a
496      named closure.  If several closures are created in the body of a
497      single `lexical-let', they all close over the same instance of the
498      lexical variable.
499
500      The `lexical-let' form is an extension to Common Lisp.  In true
501      Common Lisp, all bindings are lexical unless declared otherwise.
502
503  - Special Form: lexical-let* (BINDINGS...) FORMS...
504      This form is just like `lexical-let', except that the bindings are
505      made sequentially in the manner of `let*'.
506
507 \1f
508 File: cl.info,  Node: Function Bindings,  Next: Macro Bindings,  Prev: Lexical Bindings,  Up: Variable Bindings
509
510 Function Bindings
511 -----------------
512
513 These forms make `let'-like bindings to functions instead of variables.
514
515  - Special Form: flet (BINDINGS...) FORMS...
516      This form establishes `let'-style bindings on the function cells
517      of symbols rather than on the value cells.  Each BINDING must be a
518      list of the form `(NAME ARGLIST FORMS...)', which defines a
519      function exactly as if it were a `defun*' form.  The function NAME
520      is defined accordingly for the duration of the body of the `flet';
521      then the old function definition, or lack thereof, is restored.
522
523      While `flet' in Common Lisp establishes a lexical binding of NAME,
524      Emacs Lisp `flet' makes a dynamic binding.  The result is that
525      `flet' affects indirect calls to a function as well as calls
526      directly inside the `flet' form itself.
527
528      You can use `flet' to disable or modify the behavior of a function
529      in a temporary fashion.  This will even work on Emacs primitives,
530      although note that some calls to primitive functions internal to
531      Emacs are made without going through the symbol's function cell,
532      and so will not be affected by `flet'.  For example,
533
534           (flet ((message (&rest args) (push args saved-msgs)))
535             (do-something))
536
537      This code attempts to replace the built-in function `message' with
538      a function that simply saves the messages in a list rather than
539      displaying them.  The original definition of `message' will be
540      restored after `do-something' exits.  This code will work fine on
541      messages generated by other Lisp code, but messages generated
542      directly inside Emacs will not be caught since they make direct
543      C-language calls to the message routines rather than going through
544      the Lisp `message' function.
545
546      Functions defined by `flet' may use the full Common Lisp argument
547      notation supported by `defun*'; also, the function body is
548      enclosed in an implicit block as if by `defun*'.  *Note Program
549      Structure::.
550
551  - Special Form: labels (BINDINGS...) FORMS...
552      The `labels' form is a synonym for `flet'.  (In Common Lisp,
553      `labels' and `flet' differ in ways that depend on their lexical
554      scoping; these distinctions vanish in dynamically scoped Emacs
555      Lisp.)
556
557 \1f
558 File: cl.info,  Node: Macro Bindings,  Prev: Function Bindings,  Up: Variable Bindings
559
560 Macro Bindings
561 --------------
562
563 These forms create local macros and "symbol macros."
564
565  - Special Form: macrolet (BINDINGS...) FORMS...
566      This form is analogous to `flet', but for macros instead of
567      functions.  Each BINDING is a list of the same form as the
568      arguments to `defmacro*' (i.e., a macro name, argument list, and
569      macro-expander forms).  The macro is defined accordingly for use
570      within the body of the `macrolet'.
571
572      Because of the nature of macros, `macrolet' is lexically scoped
573      even in Emacs Lisp:  The `macrolet' binding will affect only calls
574      that appear physically within the body FORMS, possibly after
575      expansion of other macros in the body.
576
577  - Special Form: symbol-macrolet (BINDINGS...) FORMS...
578      This form creates "symbol macros", which are macros that look like
579      variable references rather than function calls.  Each BINDING is a
580      list `(VAR EXPANSION)'; any reference to VAR within the body FORMS
581      is replaced by EXPANSION.
582
583           (setq bar '(5 . 9))
584           (symbol-macrolet ((foo (car bar)))
585             (incf foo))
586           bar
587                => (6 . 9)
588
589      A `setq' of a symbol macro is treated the same as a `setf'.  I.e.,
590      `(setq foo 4)' in the above would be equivalent to `(setf foo 4)',
591      which in turn expands to `(setf (car bar) 4)'.
592
593      Likewise, a `let' or `let*' binding a symbol macro is treated like
594      a `letf' or `letf*'.  This differs from true Common Lisp, where
595      the rules of lexical scoping cause a `let' binding to shadow a
596      `symbol-macrolet' binding.  In this package, only `lexical-let'
597      and `lexical-let*' will shadow a symbol macro.
598
599      There is no analogue of `defmacro' for symbol macros; all symbol
600      macros are local.  A typical use of `symbol-macrolet' is in the
601      expansion of another macro:
602
603           (defmacro* my-dolist ((x list) &rest body)
604             (let ((var (gensym)))
605               (list 'loop 'for var 'on list 'do
606                     (list* 'symbol-macrolet (list (list x (list 'car var)))
607                            body))))
608           
609           (setq mylist '(1 2 3 4))
610           (my-dolist (x mylist) (incf x))
611           mylist
612                => (2 3 4 5)
613
614      In this example, the `my-dolist' macro is similar to `dolist'
615      (*note Iteration::.) except that the variable `x' becomes a true
616      reference onto the elements of the list.  The `my-dolist' call
617      shown here expands to
618
619           (loop for G1234 on mylist do
620                 (symbol-macrolet ((x (car G1234)))
621                   (incf x)))
622
623      which in turn expands to
624
625           (loop for G1234 on mylist do (incf (car G1234)))
626
627      *Note Loop Facility::, for a description of the `loop' macro.
628      This package defines a nonstandard `in-ref' loop clause that works
629      much like `my-dolist'.
630
631 \1f
632 File: cl.info,  Node: Conditionals,  Next: Blocks and Exits,  Prev: Variable Bindings,  Up: Control Structure
633
634 Conditionals
635 ============
636
637 These conditional forms augment Emacs Lisp's simple `if', `and', `or',
638 and `cond' forms.
639
640  - Special Form: when TEST FORMS...
641      This is a variant of `if' where there are no "else" forms, and
642      possibly several "then" forms.  In particular,
643
644           (when TEST A B C)
645
646      is entirely equivalent to
647
648           (if TEST (progn A B C) nil)
649
650  - Special Form: unless TEST FORMS...
651      This is a variant of `if' where there are no "then" forms, and
652      possibly several "else" forms:
653
654           (unless TEST A B C)
655
656      is entirely equivalent to
657
658           (when (not TEST) A B C)
659
660  - Special Form: case KEYFORM CLAUSE...
661      This macro evaluates KEYFORM, then compares it with the key values
662      listed in the various CLAUSEs.  Whichever clause matches the key
663      is executed; comparison is done by `eql'.  If no clause matches,
664      the `case' form returns `nil'.  The clauses are of the form
665
666           (KEYLIST BODY-FORMS...)
667
668      where KEYLIST is a list of key values.  If there is exactly one
669      value, and it is not a cons cell or the symbol `nil' or `t', then
670      it can be used by itself as a KEYLIST without being enclosed in a
671      list.  All key values in the `case' form must be distinct.  The
672      final clauses may use `t' in place of a KEYLIST to indicate a
673      default clause that should be taken if none of the other clauses
674      match.  (The symbol `otherwise' is also recognized in place of
675      `t'.  To make a clause that matches the actual symbol `t', `nil',
676      or `otherwise', enclose the symbol in a list.)
677
678      For example, this expression reads a keystroke, then does one of
679      four things depending on whether it is an `a', a `b', a <RET> or
680      <LFD>, or anything else.
681
682           (case (read-char)
683             (?a (do-a-thing))
684             (?b (do-b-thing))
685             ((?\r ?\n) (do-ret-thing))
686             (t (do-other-thing)))
687
688  - Special Form: ecase KEYFORM CLAUSE...
689      This macro is just like `case', except that if the key does not
690      match any of the clauses, an error is signalled rather than simply
691      returning `nil'.
692
693  - Special Form: typecase KEYFORM CLAUSE...
694      This macro is a version of `case' that checks for types rather
695      than values.  Each CLAUSE is of the form `(TYPE BODY...)'.  *Note
696      Type Predicates::, for a description of type specifiers.  For
697      example,
698
699           (typecase x
700             (integer (munch-integer x))
701             (float (munch-float x))
702             (string (munch-integer (string-to-int x)))
703             (t (munch-anything x)))
704
705      The type specifier `t' matches any type of object; the word
706      `otherwise' is also allowed.  To make one clause match any of
707      several types, use an `(or ...)' type specifier.
708
709  - Special Form: etypecase KEYFORM CLAUSE...
710      This macro is just like `typecase', except that if the key does
711      not match any of the clauses, an error is signalled rather than
712      simply returning `nil'.
713
714 \1f
715 File: cl.info,  Node: Blocks and Exits,  Next: Iteration,  Prev: Conditionals,  Up: Control Structure
716
717 Blocks and Exits
718 ================
719
720 Common Lisp "blocks" provide a non-local exit mechanism very similar to
721 `catch' and `throw', but lexically rather than dynamically scoped.
722 This package actually implements `block' in terms of `catch'; however,
723 the lexical scoping allows the optimizing byte-compiler to omit the
724 costly `catch' step if the body of the block does not actually
725 `return-from' the block.
726
727  - Special Form: block NAME FORMS...
728      The FORMS are evaluated as if by a `progn'.  However, if any of
729      the FORMS execute `(return-from NAME)', they will jump out and
730      return directly from the `block' form.  The `block' returns the
731      result of the last FORM unless a `return-from' occurs.
732
733      The `block'/`return-from' mechanism is quite similar to the
734      `catch'/`throw' mechanism.  The main differences are that block
735      NAMEs are unevaluated symbols, rather than forms (such as quoted
736      symbols) which evaluate to a tag at run-time; and also that blocks
737      are lexically scoped whereas `catch'/`throw' are dynamically
738      scoped.  This means that functions called from the body of a
739      `catch' can also `throw' to the `catch', but the `return-from'
740      referring to a block name must appear physically within the FORMS
741      that make up the body of the block.  They may not appear within
742      other called functions, although they may appear within macro
743      expansions or `lambda's in the body.  Block names and `catch'
744      names form independent name-spaces.
745
746      In true Common Lisp, `defun' and `defmacro' surround the function
747      or expander bodies with implicit blocks with the same name as the
748      function or macro.  This does not occur in Emacs Lisp, but this
749      package provides `defun*' and `defmacro*' forms which do create
750      the implicit block.
751
752      The Common Lisp looping constructs defined by this package, such
753      as `loop' and `dolist', also create implicit blocks just as in
754      Common Lisp.
755
756      Because they are implemented in terms of Emacs Lisp `catch' and
757      `throw', blocks have the same overhead as actual `catch'
758      constructs (roughly two function calls).  However, Zawinski and
759      Furuseth's optimizing byte compiler (standard in Emacs 19) will
760      optimize away the `catch' if the block does not in fact contain
761      any `return' or `return-from' calls that jump to it.  This means
762      that `do' loops and `defun*' functions which don't use `return'
763      don't pay the overhead to support it.
764
765  - Special Form: return-from NAME [RESULT]
766      This macro returns from the block named NAME, which must be an
767      (unevaluated) symbol.  If a RESULT form is specified, it is
768      evaluated to produce the result returned from the `block'.
769      Otherwise, `nil' is returned.
770
771  - Special Form: return [RESULT]
772      This macro is exactly like `(return-from nil RESULT)'.  Common
773      Lisp loops like `do' and `dolist' implicitly enclose themselves in
774      `nil' blocks.
775
776 \1f
777 File: cl.info,  Node: Iteration,  Next: Loop Facility,  Prev: Blocks and Exits,  Up: Control Structure
778
779 Iteration
780 =========
781
782 The macros described here provide more sophisticated, high-level
783 looping constructs to complement Emacs Lisp's basic `while' loop.
784
785  - Special Form: loop FORMS...
786      The "CL" package supports both the simple, old-style meaning of
787      `loop' and the extremely powerful and flexible feature known as
788      the "Loop Facility" or "Loop Macro".  This more advanced facility
789      is discussed in the following section; *note Loop Facility::..
790      The simple form of `loop' is described here.
791
792      If `loop' is followed by zero or more Lisp expressions, then
793      `(loop EXPRS...)' simply creates an infinite loop executing the
794      expressions over and over.  The loop is enclosed in an implicit
795      `nil' block.  Thus,
796
797           (loop (foo)  (if (no-more) (return 72))  (bar))
798
799      is exactly equivalent to
800
801           (block nil (while t (foo)  (if (no-more) (return 72))  (bar)))
802
803      If any of the expressions are plain symbols, the loop is instead
804      interpreted as a Loop Macro specification as described later.
805      (This is not a restriction in practice, since a plain symbol in
806      the above notation would simply access and throw away the value of
807      a variable.)
808
809  - Special Form: do (SPEC...) (END-TEST [RESULT...]) FORMS...
810      This macro creates a general iterative loop.  Each SPEC is of the
811      form
812
813           (VAR [INIT [STEP]])
814
815      The loop works as follows:  First, each VAR is bound to the
816      associated INIT value as if by a `let' form.  Then, in each
817      iteration of the loop, the END-TEST is evaluated; if true, the
818      loop is finished.  Otherwise, the body FORMS are evaluated, then
819      each VAR is set to the associated STEP expression (as if by a
820      `psetq' form) and the next iteration begins.  Once the END-TEST
821      becomes true, the RESULT forms are evaluated (with the VARs still
822      bound to their values) to produce the result returned by `do'.
823
824      The entire `do' loop is enclosed in an implicit `nil' block, so
825      that you can use `(return)' to break out of the loop at any time.
826
827      If there are no RESULT forms, the loop returns `nil'.  If a given
828      VAR has no STEP form, it is bound to its INIT value but not
829      otherwise modified during the `do' loop (unless the code
830      explicitly modifies it); this case is just a shorthand for putting
831      a `(let ((VAR INIT)) ...)'  around the loop.  If INIT is also
832      omitted it defaults to `nil', and in this case a plain `VAR' can
833      be used in place of `(VAR)', again following the analogy with
834      `let'.
835
836      This example (from Steele) illustrates a loop which applies the
837      function `f' to successive pairs of values from the lists `foo'
838      and `bar'; it is equivalent to the call `(mapcar* 'f foo bar)'.
839      Note that this loop has no body FORMS at all, performing all its
840      work as side effects of the rest of the loop.
841
842           (do ((x foo (cdr x))
843                (y bar (cdr y))
844                (z nil (cons (f (car x) (car y)) z)))
845             ((or (null x) (null y))
846              (nreverse z)))
847
848  - Special Form: do* (SPEC...) (END-TEST [RESULT...]) FORMS...
849      This is to `do' what `let*' is to `let'.  In particular, the
850      initial values are bound as if by `let*' rather than `let', and
851      the steps are assigned as if by `setq' rather than `psetq'.
852
853      Here is another way to write the above loop:
854
855           (do* ((xp foo (cdr xp))
856                 (yp bar (cdr yp))
857                 (x (car xp) (car xp))
858                 (y (car yp) (car yp))
859                 z)
860             ((or (null xp) (null yp))
861              (nreverse z))
862             (push (f x y) z))
863
864  - Special Form: dolist (VAR LIST [RESULT]) FORMS...
865      This is a more specialized loop which iterates across the elements
866      of a list.  LIST should evaluate to a list; the body FORMS are
867      executed with VAR bound to each element of the list in turn.
868      Finally, the RESULT form (or `nil') is evaluated with VAR bound to
869      `nil' to produce the result returned by the loop.  The loop is
870      surrounded by an implicit `nil' block.
871
872  - Special Form: dotimes (VAR COUNT [RESULT]) FORMS...
873      This is a more specialized loop which iterates a specified number
874      of times.  The body is executed with VAR bound to the integers
875      from zero (inclusive) to COUNT (exclusive), in turn.  Then the
876      `result' form is evaluated with VAR bound to the total number of
877      iterations that were done (i.e., `(max 0 COUNT)') to get the
878      return value for the loop form.  The loop is surrounded by an
879      implicit `nil' block.
880
881  - Special Form: do-symbols (VAR [OBARRAY [RESULT]]) FORMS...
882      This loop iterates over all interned symbols.  If OBARRAY is
883      specified and is not `nil', it loops over all symbols in that
884      obarray.  For each symbol, the body FORMS are evaluated with VAR
885      bound to that symbol.  The symbols are visited in an unspecified
886      order.  Afterward the RESULT form, if any, is evaluated (with VAR
887      bound to `nil') to get the return value.  The loop is surrounded
888      by an implicit `nil' block.
889
890  - Special Form: do-all-symbols (VAR [RESULT]) FORMS...
891      This is identical to `do-symbols' except that the OBARRAY argument
892      is omitted; it always iterates over the default obarray.
893
894    *Note Mapping over Sequences::, for some more functions for
895 iterating over vectors or lists.
896
897 \1f
898 File: cl.info,  Node: Loop Facility,  Next: Multiple Values,  Prev: Iteration,  Up: Control Structure
899
900 Loop Facility
901 =============
902
903 A common complaint with Lisp's traditional looping constructs is that
904 they are either too simple and limited, such as Common Lisp's `dotimes'
905 or Emacs Lisp's `while', or too unreadable and obscure, like Common
906 Lisp's `do' loop.
907
908    To remedy this, recent versions of Common Lisp have added a new
909 construct called the "Loop Facility" or "`loop' macro," with an
910 easy-to-use but very powerful and expressive syntax.
911
912 * Menu:
913
914 * Loop Basics::           `loop' macro, basic clause structure
915 * Loop Examples::         Working examples of `loop' macro
916 * For Clauses::           Clauses introduced by `for' or `as'
917 * Iteration Clauses::     `repeat', `while', `thereis', etc.
918 * Accumulation Clauses::  `collect', `sum', `maximize', etc.
919 * Other Clauses::         `with', `if', `initially', `finally'
920
921 \1f
922 File: cl.info,  Node: Loop Basics,  Next: Loop Examples,  Prev: Loop Facility,  Up: Loop Facility
923
924 Loop Basics
925 -----------
926
927 The `loop' macro essentially creates a mini-language within Lisp that
928 is specially tailored for describing loops.  While this language is a
929 little strange-looking by the standards of regular Lisp, it turns out
930 to be very easy to learn and well-suited to its purpose.
931
932    Since `loop' is a macro, all parsing of the loop language takes
933 place at byte-compile time; compiled `loop's are just as efficient as
934 the equivalent `while' loops written longhand.
935
936  - Special Form: loop CLAUSES...
937      A loop construct consists of a series of CLAUSEs, each introduced
938      by a symbol like `for' or `do'.  Clauses are simply strung
939      together in the argument list of `loop', with minimal extra
940      parentheses.  The various types of clauses specify
941      initializations, such as the binding of temporary variables,
942      actions to be taken in the loop, stepping actions, and final
943      cleanup.
944
945      Common Lisp specifies a certain general order of clauses in a loop:
946
947           (loop NAME-CLAUSE
948                 VAR-CLAUSES...
949                 ACTION-CLAUSES...)
950
951      The NAME-CLAUSE optionally gives a name to the implicit block that
952      surrounds the loop.  By default, the implicit block is named
953      `nil'.  The VAR-CLAUSES specify what variables should be bound
954      during the loop, and how they should be modified or iterated
955      throughout the course of the loop.  The ACTION-CLAUSES are things
956      to be done during the loop, such as computing, collecting, and
957      returning values.
958
959      The Emacs version of the `loop' macro is less restrictive about
960      the order of clauses, but things will behave most predictably if
961      you put the variable-binding clauses `with', `for', and `repeat'
962      before the action clauses.  As in Common Lisp, `initially' and
963      `finally' clauses can go anywhere.
964
965      Loops generally return `nil' by default, but you can cause them to
966      return a value by using an accumulation clause like `collect', an
967      end-test clause like `always', or an explicit `return' clause to
968      jump out of the implicit block.  (Because the loop body is
969      enclosed in an implicit block, you can also use regular Lisp
970      `return' or `return-from' to break out of the loop.)
971
972    The following sections give some examples of the Loop Macro in
973 action, and describe the particular loop clauses in great detail.
974 Consult the second edition of Steele's "Common Lisp, the Language", for
975 additional discussion and examples of the `loop' macro.
976
977 \1f
978 File: cl.info,  Node: Loop Examples,  Next: For Clauses,  Prev: Loop Basics,  Up: Loop Facility
979
980 Loop Examples
981 -------------
982
983 Before listing the full set of clauses that are allowed, let's look at
984 a few example loops just to get a feel for the `loop' language.
985
986      (loop for buf in (buffer-list)
987            collect (buffer-file-name buf))
988
989 This loop iterates over all Emacs buffers, using the list returned by
990 `buffer-list'.  For each buffer `buf', it calls `buffer-file-name' and
991 collects the results into a list, which is then returned from the
992 `loop' construct.  The result is a list of the file names of all the
993 buffers in Emacs' memory.  The words `for', `in', and `collect' are
994 reserved words in the `loop' language.
995
996      (loop repeat 20 do (insert "Yowsa\n"))
997
998 This loop inserts the phrase "Yowsa" twenty times in the current buffer.
999
1000      (loop until (eobp) do (munch-line) (forward-line 1))
1001
1002 This loop calls `munch-line' on every line until the end of the buffer.
1003 If point is already at the end of the buffer, the loop exits
1004 immediately.
1005
1006      (loop do (munch-line) until (eobp) do (forward-line 1))
1007
1008 This loop is similar to the above one, except that `munch-line' is
1009 always called at least once.
1010
1011      (loop for x from 1 to 100
1012            for y = (* x x)
1013            until (>= y 729)
1014            finally return (list x (= y 729)))
1015
1016 This more complicated loop searches for a number `x' whose square is
1017 729.  For safety's sake it only examines `x' values up to 100; dropping
1018 the phrase `to 100' would cause the loop to count upwards with no
1019 limit.  The second `for' clause defines `y' to be the square of `x'
1020 within the loop; the expression after the `=' sign is reevaluated each
1021 time through the loop.  The `until' clause gives a condition for
1022 terminating the loop, and the `finally' clause says what to do when the
1023 loop finishes.  (This particular example was written less concisely
1024 than it could have been, just for the sake of illustration.)
1025
1026    Note that even though this loop contains three clauses (two `for's
1027 and an `until') that would have been enough to define loops all by
1028 themselves, it still creates a single loop rather than some sort of
1029 triple-nested loop.  You must explicitly nest your `loop' constructs if
1030 you want nested loops.
1031