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