root/trunk/man/cl.texi

Revision 4220, 207.8 kB (checked in by miyoshi, 5 months ago)

Sync up with Emacs22.2.

Line 
1 \input texinfo    @c -*-texinfo-*-
2 @setfilename ../info/cl
3 @settitle Common Lisp Extensions
4
5 @copying
6 This file documents the GNU Emacs Common Lisp emulation package.
7
8 Copyright @copyright{} 1993, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
9 Free Software Foundation, Inc.
10
11 @quotation
12 Permission is granted to copy, distribute and/or modify this document
13 under the terms of the GNU Free Documentation License, Version 1.2 or
14 any later version published by the Free Software Foundation; with no
15 Invariant Sections, with the Front-Cover texts being ``A GNU
16 Manual'', and with the Back-Cover Texts as in (a) below.  A copy of the
17 license is included in the section entitled ``GNU Free Documentation
18 License'' in the Emacs manual.
19
20 (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
21 this GNU Manual, like GNU software.  Copies published by the Free
22 Software Foundation raise funds for GNU development.''
23
24 This document is part of a collection distributed under the GNU Free
25 Documentation License.  If you want to distribute this document
26 separately from the collection, you can do so by adding a copy of the
27 license to the document, as described in section 6 of the license.
28 @end quotation
29 @end copying
30
31 @dircategory Emacs
32 @direntry
33 * CL: (cl).             Partial Common Lisp support for Emacs Lisp.
34 @end direntry
35
36 @finalout
37
38 @titlepage
39 @sp 6
40 @center @titlefont{Common Lisp Extensions}
41 @sp 4
42 @center For GNU Emacs Lisp
43 @sp 1
44 @center Version 2.02
45 @sp 5
46 @center Dave Gillespie
47 @center daveg@@synaptics.com
48 @page
49 @vskip 0pt plus 1filll
50 @insertcopying
51 @end titlepage
52
53 @node Top, Overview, (dir), (dir)
54 @chapter Introduction
55
56 @noindent
57 This document describes a set of Emacs Lisp facilities borrowed from
58 Common Lisp.  All the facilities are described here in detail.  While
59 this document does not assume any prior knowledge of Common Lisp, it
60 does assume a basic familiarity with Emacs Lisp.
61
62 @menu
63 * Overview::             Installation, usage, etc.
64 * Program Structure::    Arglists, `eval-when', `defalias'
65 * Predicates::           `typep' and `equalp'
66 * Control Structure::    `setf', `do', `loop', etc.
67 * Macros::               Destructuring, `define-compiler-macro'
68 * Declarations::         `proclaim', `declare', etc.
69 * Symbols::              Property lists, `gensym'
70 * Numbers::              Predicates, functions, random numbers
71 * Sequences::            Mapping, functions, searching, sorting
72 * Lists::                `caddr', `sublis', `member*', `assoc*', etc.
73 * Structures::           `defstruct'
74 * Assertions::           `check-type', `assert', `ignore-errors'.
75
76 * Efficiency Concerns::         Hints and techniques
77 * Common Lisp Compatibility::   All known differences with Steele
78 * Old CL Compatibility::        All known differences with old cl.el
79 * Porting Common Lisp::         Hints for porting Common Lisp code
80
81 * GNU Free Documentation License:: The license for this documentation.
82 * Function Index::
83 * Variable Index::
84 @end menu
85
86 @node Overview, Program Structure, Top, Top
87 @ifnottex
88 @chapter Overview
89 @end ifnottex
90
91 @noindent
92 Common Lisp is a huge language, and Common Lisp systems tend to be
93 massive and extremely complex.  Emacs Lisp, by contrast, is rather
94 minimalist in the choice of Lisp features it offers the programmer.
95 As Emacs Lisp programmers have grown in number, and the applications
96 they write have grown more ambitious, it has become clear that Emacs
97 Lisp could benefit from many of the conveniences of Common Lisp.
98
99 The @dfn{CL} package adds a number of Common Lisp functions and
100 control structures to Emacs Lisp.  While not a 100% complete
101 implementation of Common Lisp, @dfn{CL} adds enough functionality
102 to make Emacs Lisp programming significantly more convenient.
103
104 @strong{Please note:} the @dfn{CL} functions are not standard parts of
105 the Emacs Lisp name space, so it is legitimate for users to define
106 them with other, conflicting meanings.  To avoid conflicting with
107 those user activities, we have a policy that packages installed in
108 Emacs must not load @dfn{CL} at run time.  (It is ok for them to load
109 @dfn{CL} at compile time only, with @code{eval-when-compile}, and use
110 the macros it provides.)  If you are writing packages that you plan to
111 distribute and invite widespread use for, you might want to observe
112 the same rule.
113
114 Some Common Lisp features have been omitted from this package
115 for various reasons:
116
117 @itemize @bullet
118 @item
119 Some features are too complex or bulky relative to their benefit
120 to Emacs Lisp programmers.  CLOS and Common Lisp streams are fine
121 examples of this group.
122
123 @item
124 Other features cannot be implemented without modification to the
125 Emacs Lisp interpreter itself, such as multiple return values,
126 lexical scoping, case-insensitive symbols, and complex numbers.
127 The @dfn{CL} package generally makes no attempt to emulate these
128 features.
129
130 @item
131 Some features conflict with existing things in Emacs Lisp.  For
132 example, Emacs' @code{assoc} function is incompatible with the
133 Common Lisp @code{assoc}.  In such cases, this package usually
134 adds the suffix @samp{*} to the function name of the Common
135 Lisp version of the function (e.g., @code{assoc*}).
136 @end itemize
137
138 The package described here was written by Dave Gillespie,
139 @file{daveg@@synaptics.com}.  It is a total rewrite of the original
140 1986 @file{cl.el} package by Cesar Quiroz.  Most features of the
141 Quiroz package have been retained; any incompatibilities are
142 noted in the descriptions below.  Care has been taken in this
143 version to ensure that each function is defined efficiently,
144 concisely, and with minimal impact on the rest of the Emacs
145 environment.
146
147 @menu
148 * Usage::                How to use the CL package
149 * Organization::         The package's five component files
150 * Installation::         Compiling and installing CL
151 * Naming Conventions::   Notes on CL function names
152 @end menu
153
154 @node Usage, Organization, Overview, Overview
155 @section Usage
156
157 @noindent
158 Lisp code that uses features from the @dfn{CL} package should
159 include at the beginning:
160
161 @example
162 (require 'cl)
163 @end example
164
165 @noindent
166 If you want to ensure that the new (Gillespie) version of @dfn{CL}
167 is the one that is present, add an additional @code{(require 'cl-19)}
168 call:
169
170 @example
171 (require 'cl)
172 (require 'cl-19)
173 @end example
174
175 @noindent
176 The second call will fail (with ``@file{cl-19.el} not found'') if
177 the old @file{cl.el} package was in use.
178
179 It is safe to arrange to load @dfn{CL} at all times, e.g.,
180 in your @file{.emacs} file.  But it's a good idea, for portability,
181 to @code{(require 'cl)} in your code even if you do this.
182
183 @node Organization, Installation, Usage, Overview
184 @section Organization
185
186 @noindent
187 The Common Lisp package is organized into four files:
188
189 @table @file
190 @item cl.el
191 This is the ``main'' file, which contains basic functions
192 and information about the package.  This file is relatively
193 compact---about 700 lines.
194
195 @item cl-extra.el
196 This file contains the larger, more complex or unusual functions.
197 It is kept separate so that packages which only want to use Common
198 Lisp fundamentals like the @code{cadr} function won't need to pay
199 the overhead of loading the more advanced functions.
200
201 @item cl-seq.el
202 This file contains most of the advanced functions for operating
203 on sequences or lists, such as @code{delete-if} and @code{assoc*}.
204
205 @item cl-macs.el
206 This file contains the features of the packages which are macros
207 instead of functions.  Macros expand when the caller is compiled,
208 not when it is run, so the macros generally only need to be
209 present when the byte-compiler is running (or when the macros are
210 used in uncompiled code such as a @file{.emacs} file).  Most of
211 the macros of this package are isolated in @file{cl-macs.el} so
212 that they won't take up memory unless you are compiling.
213 @end table
214
215 The file @file{cl.el} includes all necessary @code{autoload}
216 commands for the functions and macros in the other three files.
217 All you have to do is @code{(require 'cl)}, and @file{cl.el}
218 will take care of pulling in the other files when they are
219 needed.
220
221 There is another file, @file{cl-compat.el}, which defines some
222 routines from the older @file{cl.el} package that are no longer
223 present in the new package.  This includes internal routines
224 like @code{setelt} and @code{zip-lists}, deprecated features
225 like @code{defkeyword}, and an emulation of the old-style
226 multiple-values feature.  @xref{Old CL Compatibility}.
227
228 @node Installation, Naming Conventions, Organization, Overview
229 @section Installation
230
231 @noindent
232 Installation of the @dfn{CL} package is simple:  Just put the
233 byte-compiled files @file{cl.elc}, @file{cl-extra.elc},
234 @file{cl-seq.elc}, @file{cl-macs.elc}, and @file{cl-compat.elc}
235 into a directory on your @code{load-path}.
236
237 There are no special requirements to compile this package:
238 The files do not have to be loaded before they are compiled,
239 nor do they need to be compiled in any particular order.
240
241 You may choose to put the files into your main @file{lisp/}
242 directory, replacing the original @file{cl.el} file there.  Or,
243 you could put them into a directory that comes before @file{lisp/}
244 on your @code{load-path} so that the old @file{cl.el} is
245 effectively hidden.
246
247 Also, format the @file{cl.texinfo} file and put the resulting
248 Info files in the @file{info/} directory or another suitable place.
249
250 You may instead wish to leave this package's components all in
251 their own directory, and then add this directory to your
252 @code{load-path} and @code{Info-directory-list}.
253 Add the directory to the front of the list so the old @dfn{CL}
254 package and its documentation are hidden.
255
256 @node Naming Conventions,  , Installation, Overview
257 @section Naming Conventions
258
259 @noindent
260 Except where noted, all functions defined by this package have the
261 same names and calling conventions as their Common Lisp counterparts.
262
263 Following is a complete list of functions whose names were changed
264 from Common Lisp, usually to avoid conflicts with Emacs.  In each
265 case, a @samp{*} has been appended to the Common Lisp name to obtain
266 the Emacs name:
267
268 @example
269 defun*        defsubst*     defmacro*     function*
270 member*       assoc*        rassoc*       get*
271 remove*       delete*       mapcar*       sort*
272 floor*        ceiling*      truncate*     round*
273 mod*          rem*          random*
274 @end example
275
276 Internal function and variable names in the package are prefixed
277 by @code{cl-}.  Here is a complete list of functions @emph{not}
278 prefixed by @code{cl-} which were not taken from Common Lisp:
279
280 @example
281 floatp-safe   lexical-let   lexical-let*
282 callf         callf2        letf          letf*
283 defsubst*
284 @end example
285
286 The following simple functions and macros are defined in @file{cl.el};
287 they do not cause other components like @file{cl-extra} to be loaded.
288
289 @example
290 floatp-safe   endp
291 evenp         oddp          plusp         minusp
292 caaar .. cddddr
293 list*         ldiff         rest          first .. tenth
294 copy-list     subst         mapcar* [2]
295 adjoin [3]    acons         pairlis       pop [4]
296 push [4]      pushnew [3,4] incf [4]      decf [4]
297 proclaim      declaim
298 @end example
299
300 @noindent
301 [2] Only for one sequence argument or two list arguments.
302
303 @noindent
304 [3] Only if @code{:test} is @code{eq}, @code{equal}, or unspecified,
305 and @code{:key} is not used.
306
307 @noindent
308 [4] Only when @var{place} is a plain variable name.
309
310 @iftex
311 @chapno=4
312 @end iftex
313
314 @node Program Structure, Predicates, Overview, Top
315 @chapter Program Structure
316
317 @noindent
318 This section describes features of the @dfn{CL} package which have to
319 do with programs as a whole: advanced argument lists for functions,
320 and the @code{eval-when} construct.
321
322 @menu
323 * Argument Lists::       `&key', `&aux', `defun*', `defmacro*'.
324 * Time of Evaluation::   The `eval-when' construct.
325 @end menu
326
327 @iftex
328 @secno=1
329 @end iftex
330
331 @node Argument Lists, Time of Evaluation, Program Structure, Program Structure
332 @section Argument Lists
333
334 @noindent
335 Emacs Lisp's notation for argument lists of functions is a subset of
336 the Common Lisp notation.  As well as the familiar @code{&optional}
337 and @code{&rest} markers, Common Lisp allows you to specify default
338 values for optional arguments, and it provides the additional markers
339 @code{&key} and @code{&aux}.
340
341 Since argument parsing is built-in to Emacs, there is no way for
342 this package to implement Common Lisp argument lists seamlessly.
343 Instead, this package defines alternates for several Lisp forms
344 which you must use if you need Common Lisp argument lists.
345
346 @defspec defun* name arglist body...
347 This form is identical to the regular @code{defun} form, except
348 that @var{arglist} is allowed to be a full Common Lisp argument
349 list.  Also, the function body is enclosed in an implicit block
350 called @var{name}; @pxref{Blocks and Exits}.
351 @end defspec
352
353 @defspec defsubst* name arglist body...
354 This is just like @code{defun*}, except that the function that
355 is defined is automatically proclaimed @code{inline}, i.e.,
356 calls to it may be expanded into in-line code by the byte compiler.
357 This is analogous to the @code{defsubst} form;
358 @code{defsubst*} uses a different method (compiler macros) which
359 works in all version of Emacs, and also generates somewhat more
360 efficient inline expansions.  In particular, @code{defsubst*}
361 arranges for the processing of keyword arguments, default values,
362 etc., to be done at compile-time whenever possible.
363 @end defspec
364
365 @defspec defmacro* name arglist body...
366 This is identical to the regular @code{defmacro} form,
367 except that @var{arglist} is allowed to be a full Common Lisp
368 argument list.  The @code{&environment} keyword is supported as
369 described in Steele.  The @code{&whole} keyword is supported only
370 within destructured lists (see below); top-level @code{&whole}
371 cannot be implemented with the current Emacs Lisp interpreter.
372 The macro expander body is enclosed in an implicit block called
373 @var{name}.
374 @end defspec
375
376 @defspec function* symbol-or-lambda
377 This is identical to the regular @code{function} form,
378 except that if the argument is a @code{lambda} form then that
379 form may use a full Common Lisp argument list.
380 @end defspec
381
382 Also, all forms (such as @code{defsetf} and @code{flet}) defined
383 in this package that include @var{arglist}s in their syntax allow
384 full Common Lisp argument lists.
385
386 Note that it is @emph{not} necessary to use @code{defun*} in
387 order to have access to most @dfn{CL} features in your function.
388 These features are always present; @code{defun*}'s only
389 difference from @code{defun} is its more flexible argument
390 lists and its implicit block.
391
392 The full form of a Common Lisp argument list is
393
394 @example
395 (@var{var}...
396  &optional (@var{var} @var{initform} @var{svar})...
397  &rest @var{var}
398  &key ((@var{keyword} @var{var}) @var{initform} @var{svar})...
399  &aux (@var{var} @var{initform})...)
400 @end example
401
402 Each of the five argument list sections is optional.  The @var{svar},
403 @var{initform}, and @var{keyword} parts are optional; if they are
404 omitted, then @samp{(@var{var})} may be written simply @samp{@var{var}}.
405
406 The first section consists of zero or more @dfn{required} arguments.
407 These arguments must always be specified in a call to the function;
408 there is no difference between Emacs Lisp and Common Lisp as far as
409 required arguments are concerned.
410
411 The second section consists of @dfn{optional} arguments.  These
412 arguments may be specified in the function call; if they are not,
413 @var{initform} specifies the default value used for the argument.
414 (No @var{initform} means to use @code{nil} as the default.)  The
415 @var{initform} is evaluated with the bindings for the preceding
416 arguments already established; @code{(a &optional (b (1+ a)))}
417 matches one or two arguments, with the second argument defaulting
418 to one plus the first argument.  If the @var{svar} is specified,
419 it is an auxiliary variable which is bound to @code{t} if the optional
420 argument was specified, or to @code{nil} if the argument was omitted.
421 If you don't use an @var{svar}, then there will be no way for your
422 function to tell whether it was called with no argument, or with
423 the default value passed explicitly as an argument.
424
425 The third section consists of a single @dfn{rest} argument.  If
426 more arguments were passed to the function than are accounted for
427 by the required and optional arguments, those extra arguments are
428 collected into a list and bound to the ``rest'' argument variable.
429 Common Lisp's @code{&rest} is equivalent to that of Emacs Lisp.
430 Common Lisp accepts @code{&body} as a synonym for @code{&rest} in
431 macro contexts; this package accepts it all the time.
432
433 The fourth section consists of @dfn{keyword} arguments.  These
434 are optional arguments which are specified by name rather than
435 positionally in the argument list.  For example,
436
437 @example
438 (defun* foo (a &optional b &key c d (e 17)))
439 @end example
440
441 @noindent
442 defines a function which may be called with one, two, or more
443 arguments.  The first two arguments are bound to @code{a} and
444 @code{b} in the usual way.  The remaining arguments must be
445 pairs of the form @code{:c}, @code{:d}, or @code{:e} followed
446 by the value to be bound to the corresponding argument variable.
447 (Symbols whose names begin with a colon are called @dfn{keywords},
448 and they are self-quoting in the same way as @code{nil} and
449 @code{t}.)
450
451 For example, the call @code{(foo 1 2 :d 3 :c 4)} sets the five
452 arguments to 1, 2, 4, 3, and 17, respectively.  If the same keyword
453 appears more than once in the function call, the first occurrence
454 takes precedence over the later ones.  Note that it is not possible
455 to specify keyword arguments without specifying the optional
456 argument @code{b} as well, since @code{(foo 1 :c 2)} would bind
457 @code{b} to the keyword @code{:c}, then signal an error because
458 @code{2} is not a valid keyword.
459
460 If a @var{keyword} symbol is explicitly specified in the argument
461 list as shown in the above diagram, then that keyword will be
462 used instead of just the variable name prefixed with a colon.
463 You can specify a @var{keyword} symbol which does not begin with
464 a colon at all, but such symbols will not be self-quoting; you
465 will have to quote them explicitly with an apostrophe in the
466 function call.
467
468 Ordinarily it is an error to pass an unrecognized keyword to
469 a function, e.g., @code{(foo 1 2 :c 3 :goober 4)}.  You can ask
470 Lisp to ignore unrecognized keywords, either by adding the
471 marker @code{&allow-other-keys} after the keyword section
472 of the argument list, or by specifying an @code{:allow-other-keys}
473 argument in the call whose value is non-@code{nil}.  If the
474 function uses both @code{&rest} and @code{&key} at the same time,
475 the ``rest'' argument is bound to the keyword list as it appears
476 in the call.  For example:
477
478 @smallexample
479 (defun* find-thing (thing &rest rest &key need &allow-other-keys)
480   (or (apply 'member* thing thing-list :allow-other-keys t rest)
481       (if need (error "Thing not found"))))
482 @end smallexample
483
484 @noindent
485 This function takes a @code{:need} keyword argument, but also
486 accepts other keyword arguments which are passed on to the
487 @code{member*} function.  @code{allow-other-keys} is used to
488 keep both @code{find-thing} and @code{member*} from complaining
489 about each others' keywords in the arguments.
490
491 The fifth section of the argument list consists of @dfn{auxiliary
492 variables}.  These are not really arguments at all, but simply
493 variables which are bound to @code{nil} or to the specified
494 @var{initforms} during execution of the function.  There is no
495 difference between the following two functions, except for a
496 matter of stylistic taste:
497
498 @example
499 (defun* foo (a b &aux (c (+ a b)) d)
500   @var{body})
501
502 (defun* foo (a b)
503   (let ((c (+ a b)) d)
504     @var{body}))
505 @end example
506
507 Argument lists support @dfn{destructuring}.  In Common Lisp,
508 destructuring is only allowed with @code{defmacro}; this package
509 allows it with @code{defun*} and other argument lists as well.
510 In destructuring, any argument variable (@var{var} in the above
511 diagram) can be replaced by a list of variables, or more generally,
512 a recursive argument list.  The corresponding argument value must
513 be a list whose elements match this recursive argument list.
514 For example:
515
516 @example
517 (defmacro* dolist ((var listform &optional resultform)
518                    &rest body)
519   ...)
520 @end example
521
522 This says that the first argument of @code{dolist} must be a list
523 of two or three items; if there are other arguments as well as this
524 list, they are stored in @code{body}.  All features allowed in
525 regular argument lists are allowed in these recursive argument lists.
526 In addition, the clause @samp{&whole @var{var}} is allowed at the
527 front of a recursive argument list.  It binds @var{var} to the
528 whole list being matched; thus @code{(&whole all a b)} matches
529 a list of two things, with @code{a} bound to the first thing,
530 @code{b} bound to the second thing, and @code{all} bound to the
531 list itself.  (Common Lisp allows @code{&whole} in top-level
532 @code{defmacro} argument lists as well, but Emacs Lisp does not
533 support this usage.)
534
535 One last feature of destructuring is that the argument list may be
536 dotted, so that the argument list @code{(a b . c)} is functionally
537 equivalent to @code{(a b &rest c)}.
538
539 If the optimization quality @code{safety} is set to 0
540 (@pxref{Declarations}), error checking for wrong number of
541 arguments and invalid keyword arguments is disabled.  By default,
542 argument lists are rigorously checked.
543
544 @node Time of Evaluation,  , Argument Lists, Program Structure
545 @section Time of Evaluation
546
547 @noindent
548 Normally, the byte-compiler does not actually execute the forms in
549 a file it compiles.  For example, if a file contains @code{(setq foo t)},
550 the act of compiling it will not actually set @code{foo} to @code{t}.
551 This is true even if the @code{setq} was a top-level form (i.e., not
552 enclosed in a @code{defun} or other form).  Sometimes, though, you
553 would like to have certain top-level forms evaluated at compile-time.
554 For example, the compiler effectively evaluates @code{defmacro} forms
555 at compile-time so that later parts of the file can refer to the
556 macros that are defined.
557
558 @defspec eval-when (situations...) forms...
559 This form controls when the body @var{forms} are evaluated.
560 The @var{situations} list may contain any set of the symbols
561 @code{compile}, @code{load}, and @code{eval} (or their long-winded
562 ANSI equivalents, @code{:compile-toplevel}, @code{:load-toplevel},
563 and @code{:execute}).
564
565 The @code{eval-when} form is handled differently depending on
566 whether or not it is being compiled as a top-level form.
567 Specifically, it gets special treatment if it is being compiled
568 by a command such as @code{byte-compile-file} which compiles files
569 or buffers of code, and it appears either literally at the
570 top level of the file or inside a top-level @code{progn}.
571
572 For compiled top-level @code{eval-when}s, the body @var{forms} are
573 executed at compile-time if @code{compile} is in the @var{situations}
574 list, and the @var{forms} are written out to the file (to be executed
575 at load-time) if @code{load} is in the @var{situations} list.
576
577 For non-compiled-top-level forms, only the @code{eval} situation is
578 relevant.  (This includes forms executed by the interpreter, forms
579 compiled with @code{byte-compile} rather than @code{byte-compile-file},
580 and non-top-level forms.)  The @code{eval-when} acts like a
581 @code{progn} if @code{eval} is specified, and like @code{nil}
582 (ignoring the body @var{forms}) if not.
583
584 The rules become more subtle when @code{eval-when}s are nested;
585 consult Steele (second edition) for the gruesome details (and
586 some gruesome examples).
587
588 Some simple examples:
589
590 @example
591 ;; Top-level forms in foo.el:
592 (eval-when (compile)           (setq foo1 'bar))
593 (eval-when (load)              (setq foo2 'bar))
594 (eval-when (compile load)      (setq foo3 'bar))
595 (eval-when (eval)              (setq foo4 'bar))
596 (eval-when (eval compile)      (setq foo5 'bar))
597 (eval-when (eval load)         (setq foo6 'bar))
598 (eval-when (eval compile load) (setq foo7 'bar))
599 @end example
600
601 When @file{foo.el} is compiled, these variables will be set during
602 the compilation itself:
603
604 @example
605 foo1  foo3  foo5  foo7      ; `compile'
606 @end example
607
608 When @file{foo.elc} is loaded, these variables will be set:
609
610 @example
611 foo2  foo3  foo6  foo7      ; `load'
612 @end example
613
614 And if @file{foo.el} is loaded uncompiled, these variables will
615 be set:
616
617 @example
618 foo4  foo5  foo6  foo7      ; `eval'
619 @end example
620
621 If these seven @code{eval-when}s had been, say, inside a @code{defun},
622 then the first three would have been equivalent to @code{nil} and the
623 last four would have been equivalent to the corresponding @code{setq}s.
624
625 Note that @code{(eval-when (load eval) @dots{})} is equivalent
626 to @code{(progn @dots{})} in all contexts.  The compiler treats
627 certain top-level forms, like @code{defmacro} (sort-of) and
628 @code{require}, as if they were wrapped in @code{(eval-when
629 (compile load eval) @dots{})}.
630 @end defspec
631
632 Emacs includes two special forms related to @code{eval-when}.
633 One of these, @code{eval-when-compile}, is not quite equivalent to
634 any @code{eval-when} construct and is described below.
635
636 The other form, @code{(eval-and-compile @dots{})}, is exactly
637 equivalent to @samp{(eval-when (compile load eval) @dots{})} and
638 so is not itself defined by this package.
639
640 @defspec eval-when-compile forms...
641 The @var{forms} are evaluated at compile-time; at execution time,
642 this form acts like a quoted constant of the resulting value.  Used
643 at top-level, @code{eval-when-compile} is just like @samp{eval-when
644 (compile eval)}.  In other contexts, @code{eval-when-compile}
645 allows code to be evaluated once at compile-time for efficiency
646 or other reasons.
647
648 This form is similar to the @samp{#.} syntax of true Common Lisp.
649 @end defspec
650
651 @defspec load-time-value form
652 The @var{form} is evaluated at load-time; at execution time,
653 this form acts like a quoted constant of the resulting value.
654
655 Early Common Lisp had a @samp{#,} syntax that was similar to
656 this, but ANSI Common Lisp replaced it with @code{load-time-value}
657 and gave it more well-defined semantics.
658
659 In a compiled file, @code{load-time-value} arranges for @var{form}
660 to be evaluated when the @file{.elc} file is loaded and then used
661 as if it were a quoted constant.  In code compiled by
662 @code{byte-compile} rather than @code{byte-compile-file}, the
663 effect is identical to @code{eval-when-compile}.  In uncompiled
664 code, both @code{eval-when-compile} and @code{load-time-value}
665 act exactly like @code{progn}.
666
667 @example
668 (defun report ()
669   (insert "This function was executed on: "
670           (current-time-string)
671           ", compiled on: "
672           (eval-when-compile (current-time-string))
673           ;; or '#.(current-time-string) in real Common Lisp
674           ", and loaded on: "
675           (load-time-value (current-time-string))))
676 @end example
677
678 @noindent
679 Byte-compiled, the above defun will result in the following code
680 (or its compiled equivalent, of course) in the @file{.elc} file:
681
682 @example
683 (setq --temp-- (current-time-string))
684 (defun report ()
685   (insert "This function was executed on: "
686           (current-time-string)
687           ", compiled on: "
688           '"Wed Jun 23 18:33:43 1993"
689           ", and loaded on: "
690           --temp--))
691 @end example
692 @end defspec
693
694 @node Predicates, Control Structure, Program Structure, Top
695 @chapter Predicates
696
697 @noindent
698 This section describes functions for testing whether various
699 facts are true or false.
700
701 @menu
702 * Type Predicates::      `typep', `deftype', and `coerce'
703 * Equality Predicates::  `equalp'
704 @end menu
705
706 @node Type Predicates, Equality Predicates, Predicates, Predicates
707 @section Type Predicates
708
709 @noindent
710 The @dfn{CL} package defines a version of the Common Lisp @code{typep}
711 predicate.
712
713 @defun typep object type
714 Check if @var{object} is of type @var{type}, where @var{type} is a
715 (quoted) type name of the sort used by Common Lisp.  For example,
716 @code{(typep foo 'integer)} is equivalent to @code{(integerp foo)}.
717 @end defun
718
719 The @var{type} argument to the above function is either a symbol
720 or a list beginning with a symbol.
721
722 @itemize @bullet
723 @item
724 If the type name is a symbol, Emacs appends @samp{-p} to the
725 symbol name to form the name of a predicate function for testing
726 the type.  (Built-in predicates whose names end in @samp{p} rather
727 than @samp{-p} are used when appropriate.)
728
729 @item
730 The type symbol @code{t} stands for the union of all types.
731 @code{(typep @var{object} t)} is always true.  Likewise, the
732 type symbol @code{nil} stands for nothing at all, and
733 @code{(typep @var{object} nil)} is always false.
734
735 @item
736 The type symbol @code{null} represents the symbol @code{nil}.
737 Thus @code{(typep @var{object} 'null)} is equivalent to
738 @code{(null @var{object})}.
739
740 @item
741 The type symbol @code{atom} represents all objects that are not cons
742 cells. Thus @code{(typep @var{object} 'atom)} is equivalent to
743 @code{(atom @var{object})}.
744
745 @item
746 The type symbol @code{real} is a synonym for @code{number}, and
747 @code{fixnum} is a synonym for @code{integer}.
748
749 @item
750 The type symbols @code{character} and @code{string-char} match
751 integers in the range from 0 to 255.
752
753 @item
754 The type symbol @code{float} uses the @code{floatp-safe} predicate
755 defined by this package rather than @code{floatp}, so it will work
756 correctly even in Emacs versions without floating-point support.
757
758 @item
759 The type list @code{(integer @var{low} @var{high})} represents all
760 integers between @var{low} and @var{high}, inclusive.  Either bound
761 may be a list of a single integer to specify an exclusive limit,
762 or a @code{*} to specify no limit.  The type @code{(integer * *)}
763 is thus equivalent to @code{integer}.
764
765 @item
766 Likewise, lists beginning with @code{float}, @code{real}, or
767 @code{number} represent numbers of that type falling in a particular
768 range.
769
770 @item
771 Lists beginning with @code{and}, @code{or}, and @code{not} form
772 combinations of types.  For example, @code{(or integer (float 0 *))}
773 represents all objects that are integers or non-negative floats.
774
775 @item
776 Lists beginning with @code{member} or @code{member*} represent
777 objects @code{eql} to any of the following values.  For example,
778 @code{(member 1 2 3 4)} is equivalent to @code{(integer 1 4)},
779 and @code{(member nil)} is equivalent to @code{null}.
780
781 @item
782 Lists of the form @code{(satisfies @var{predicate})} represent
783 all objects for which @var{predicate} returns true when called
784 with that object as an argument.
785 @end itemize
786
787 The following function and macro (not technically predicates) are
788 related to @code{typep}.
789
790 @defun coerce object type
791 This function attempts to convert @var{object} to the specified
792 @var{type}.  If @var{object} is already of that type as determined by
793 @code{typep}, it is simply returned.  Otherwise, certain types of
794 conversions will be made:  If @var{type} is any sequence type
795 (@code{string}, @code{list}, etc.) then @var{object} will be
796 converted to that type if possible.  If @var{type} is
797 @code{character}, then strings of length one and symbols with
798 one-character names can be coerced.  If @var{type} is @code{float},
799 then integers can be coerced in versions of Emacs that support
800 floats.  In all other circumstances, @code{coerce} signals an
801 error.
802 @end defun
803
804 @defspec deftype name arglist forms...
805 This macro defines a new type called @var{name}.  It is similar
806 to @code{defmacro} in many ways; when @var{name} is encountered
807 as a type name, the body @var{forms} are evaluated and should
808 return a type specifier that is equivalent to the type.  The
809 @var{arglist} is a Common Lisp argument list of the sort accepted
810 by @code{defmacro*}.  The type specifier @samp{(@var{name} @var{args}...)}
811 is expanded by calling the expander with those arguments; the type
812 symbol @samp{@var{name}} is expanded by calling the expander with
813 no arguments.  The @var{arglist} is processed the same as for
814 @code{defmacro*} except that optional arguments without explicit
815 defaults use @code{*} instead of @code{nil} as the ``default''
816 default.  Some examples:
817
818 @example
819 (deftype null () '(satisfies null))    ; predefined
820 (deftype list () '(or null cons))      ; predefined
821 (deftype unsigned-byte (&optional bits)
822   (list 'integer 0 (if (eq bits '*) bits (1- (lsh 1 bits)))))
823 (unsigned-byte 8)  @equiv{}  (integer 0 255)
824 (unsigned-byte)  @equiv{}  (integer 0 *)
825 unsigned-byte  @equiv{}  (integer 0 *)
826 @end example
827
828 @noindent
829 The last example shows how the Common Lisp @code{unsigned-byte}
830 type specifier could be implemented if desired; this package does
831 not implement @code{unsigned-byte} by default.
832 @end defspec
833
834 The @code{typecase} and @code{check-type} macros also use type
835 names.  @xref{Conditionals}.  @xref{Assertions}.  The @code{map},
836 @code{concatenate}, and @code{merge} functions take type-name
837 arguments to specify the type of sequence to return.  @xref{Sequences}.
838
839 @node Equality Predicates,  , Type Predicates, Predicates
840 @section Equality Predicates
841
842 @noindent
843 This package defines the Common Lisp predicate @code{equalp}.
844
845 @defun equalp a b
846 This function is a more flexible version of @code{equal}.  In
847 particular, it compares strings case-insensitively, and it compares
848 numbers without regard to type (so that @code{(equalp 3 3.0)} is
849 true).  Vectors and conses are compared recursively.  All other
850 objects are compared as if by @code{equal}.
851
852 This function differs from Common Lisp @code{equalp} in several
853 respects.  First, Common Lisp's @code{equalp} also compares
854 @emph{characters} case-insensitively, which would be impractical
855 in this package since Emacs does not distinguish between integers
856 and characters.  In keeping with the idea that strings are less
857 vector-like in Emacs Lisp, this package's @code{equalp} also will
858 not compare strings against vectors of integers.
859 @end defun
860
861 Also note that the Common Lisp functions @code{member} and @code{assoc}
862 use @code{eql} to compare elements, whereas Emacs Lisp follows the
863 MacLisp tradition and uses @code{equal} for these two functions.
864 In Emacs, use @code{member*} and @code{assoc*} to get functions
865 which use @code{eql} for comparisons.
866
867 @node Control Structure, Macros, Predicates, Top
868 @chapter Control Structure
869
870 @noindent
871 The features described in the following sections implement
872 various advanced control structures, including the powerful
873 @code{setf} facility and a number of looping and conditional
874 constructs.
875
876 @menu
877 * Assignment::             The `psetq' form
878 * Generalized Variables::  `setf', `incf', `push', etc.
879 * Variable Bindings::      `progv', `lexical-let', `flet', `macrolet'
880 * Conditionals::           `case', `typecase'
881 * Blocks and Exits::       `block', `return', `return-from'
882 * Iteration::              `do', `dotimes', `dolist', `do-symbols'
883 * Loop Facility::          The Common Lisp `loop' macro
884 * Multiple Values::        `values', `multiple-value-bind', etc.
885 @end menu
886
887 @node Assignment, Generalized Variables, Control Structure, Control Structure
888 @section Assignment
889
890 @noindent
891 The @code{psetq} form is just like @code{setq}, except that multiple
892 assignments are done in parallel rather than sequentially.
893
894 @defspec psetq [symbol form]@dots{}
895 This special form (actually a macro) is used to assign to several
896 variables simultaneously.  Given only one @var{symbol} and @var{form},
897 it has the same effect as @code{setq}.  Given several @var{symbol}
898 and @var{form} pairs, it evaluates all the @var{form}s in advance
899 and then stores the corresponding variables afterwards.
900
901 @example
902 (setq x 2 y 3)
903 (setq x (+ x y)  y (* x y))
904 x
905      @result{} 5
906 y                     ; @r{@code{y} was computed after @code{x} was set.}
907      @result{} 15
908 (setq x 2 y 3)
909 (psetq x (+ x y)  y (* x y))
910 x
911      @result{} 5
912 y                     ; @r{@code{y} was computed before @code{x} was set.}
913      @result{} 6
914 @end example
915
916 The simplest use of @code{psetq} is @code{(psetq x y y x)}, which
917 exchanges the values of two variables.  (The @code{rotatef} form
918 provides an even more convenient way to swap two variables;
919 @pxref{Modify Macros}.)
920
921 @code{psetq} always returns @code{nil}.
922 @end defspec
923
924 @node Generalized Variables, Variable Bindings, Assignment, Control Structure
925 @section Generalized Variables
926
927 @noindent
928 A ``generalized variable'' or ``place form'' is one of the many places
929 in Lisp memory where values can be stored.  The simplest place form is
930 a regular Lisp variable.  But the cars and cdrs of lists, elements
931 of arrays, properties of symbols, and many other locations are also
932 places where Lisp values are stored.
933
934 The @code{setf} form is like @code{setq}, except that it accepts
935 arbitrary place forms on the left side rather than just
936 symbols.  For example, @code{(setf (car a) b)} sets the car of
937 @code{a} to @code{b}, doing the same operation as @code{(setcar a b)}
938 but without having to remember two separate functions for setting
939 and accessing every type of place.
940
941 Generalized variables are analogous to ``lvalues'' in the C
942 language, where @samp{x = a[i]} gets an element from an array
943 and @samp{a[i] = x} stores an element using the same notation.
944 Just as certain forms like @code{a[i]} can be lvalues in C, there
945 is a set of forms that can be generalized variables in Lisp.
946
947 @menu
948 * Basic Setf::         `setf' and place forms
949 * Modify Macros::      `incf', `push', `rotatef', `letf', `callf', etc.
950 * Customizing Setf::   `define-modify-macro', `defsetf', `define-setf-method'
951 @end menu
952
953 @node Basic Setf, Modify Macros, Generalized Variables, Generalized Variables
954 @subsection Basic Setf
955
956 @noindent
957 The @code{setf} macro is the most basic way to operate on generalized
958 variables.
959
960 @defspec setf [place form]@dots{}
961 This macro evaluates @var{form} and stores it in @var{place}, which
962 must be a valid generalized variable form.  If there are several
963 @var{place} and @var{form} pairs, the assignments are done sequentially
964 just as with @code{setq}.  @code{setf} returns the value of the last
965 @var{form}.
966
967 The following Lisp forms will work as generalized variables, and
968 so may appear in the @var{place} argument of @code{setf}:
969
970 @itemize @bullet
971 @item
972 A symbol naming a variable.  In other words, @code{(setf x y)} is
973 exactly equivalent to @code{(setq x y)}, and @code{setq} itself is
974 strictly speaking redundant now that @code{setf} exists.  Many
975 programmers continue to prefer @code{setq} for setting simple
976 variables, though, purely for stylistic or historical reasons.
977 The macro @code{(setf x y)} actually expands to @code{(setq x y)},
978 so there is no performance penalty for using it in compiled code.
979
980 @item
981 A call to any of the following Lisp functions:
982
983 @smallexample
984 car                 cdr                 caar .. cddddr
985 nth                 rest                first .. tenth
986 aref                elt                 nthcdr
987 symbol-function     symbol-value        symbol-plist
988 get                 get*                getf
989 gethash             subseq
990 @end smallexample
991
992 @noindent
993 Note that for @code{nthcdr} and @code{getf}, the list argument
994 of the function must itself be a valid @var{place} form.  For
995 example, @code{(setf (nthcdr 0 foo) 7)} will set @code{foo} itself
996 to 7.  Note that @code{push} and @code{pop} on an @code{nthcdr}
997 place can be used to insert or delete at any position in a list.
998 The use of @code{nthcdr} as a @var{place} form is an extension
999 to standard Common Lisp.
1000
1001 @item
1002 The following Emacs-specific functions are also @code{setf}-able.
1003
1004 @smallexample
1005 buffer-file-name                  marker-position
1006 buffer-modified-p                 match-data
1007 buffer-name                       mouse-position
1008 buffer-string                     overlay-end
1009 buffer-substring                  overlay-get
1010 current-buffer                    overlay-start
1011 current-case-table                point
1012 current-column                    point-marker
1013 current-global-map                point-max
1014 current-input-mode                point-min
1015 current-local-map                 process-buffer
1016 current-window-configuration      process-filter
1017 default-file-modes                process-sentinel
1018 default-value                     read-mouse-position
1019 documentation-property            screen-height
1020 extent-data                       screen-menubar
1021 extent-end-position               screen-width
1022 extent-start-position             selected-window
1023 face-background                   selected-screen
1024 face-background-pixmap            selected-frame
1025 face-font                         standard-case-table
1026 face-foreground                   syntax-table
1027 face-underline-p                  window-buffer
1028 file-modes                        window-dedicated-p
1029 frame-height                      window-display-table
1030 frame-parameters                  window-height
1031 frame-visible-p                   window-hscroll
1032 frame-width                       window-point
1033 get-register                      window-start
1034 getenv                            window-width
1035 global-key-binding                x-get-cut-buffer
1036 keymap-parent                     x-get-cutbuffer
1037 local-key-binding                 x-get-secondary-selection
1038 mark                              x-get-selection
1039 mark-marker
1040 @end smallexample
1041
1042 Most of these have directly corresponding ``set'' functions, like
1043 @code{use-local-map} for @code{current-local-map}, or @code{goto-char}
1044 for @code{point}.  A few, like @code{point-min}, expand to longer
1045 sequences of code when they are @code{setf}'d (@code{(narrow-to-region
1046 x (point-max))} in this case).
1047
1048 @item
1049 A call of the form @code{(substring @var{subplace} @var{n} [@var{m}])},
1050 where @var{subplace} is itself a valid generalized variable whose
1051 current value is a string, and where the value stored is also a
1052 string.  The new string is spliced into the specified part of the
1053 destination string.  For example:
1054
1055 @example
1056 (setq a (list "hello" "world"))
1057      @result{} ("hello" "world")
1058 (cadr a)
1059      @result{} "world"
1060 (substring (cadr a) 2 4)
1061      @result{} "rl"
1062 (setf (substring (cadr a) 2 4) "o")
1063      @result{} "o"
1064 (cadr a)
1065      @result{} "wood"
1066 a
1067      @result{} ("hello" "wood")
1068 @end example
1069
1070 The generalized variable @code{buffer-substring}, listed above,
1071 also works in this way by replacing a portion of the current buffer.
1072
1073 @item
1074 A call of the form @code{(apply '@var{func} @dots{})} or
1075 @code{(apply (function @var{func}) @dots{})}, where @var{func}
1076 is a @code{setf}-able function whose store function is ``suitable''
1077 in the sense described in Steele's book; since none of the standard
1078 Emacs place functions are suitable in this sense, this feature is
1079 only interesting when used with places you define yourself with
1080 @code{define-setf-method} or the long form of @code{defsetf}.
1081
1082 @item
1083 A macro call, in which case the macro is expanded and @code{setf}
1084 is applied to the resulting form.
1085
1086 @item
1087 Any form for which a @code{defsetf} or @code{define-setf-method}
1088 has been made.
1089 @end itemize
1090
1091 Using any forms other than these in the @var{place} argument to
1092 @code{setf} will signal an error.
1093
1094 The @code{setf} macro takes care to evaluate all subforms in
1095 the proper left-to-right order; for example,
1096
1097 @example
1098 (setf (aref vec (incf i)) i)
1099 @end example
1100
1101 @noindent
1102 looks like it will evaluate @code{(incf i)} exactly once, before the
1103 following access to @code{i}; the @code{setf} expander will insert
1104 temporary variables as necessary to ensure that it does in fact work
1105 this way no matter what setf-method is defined for @code{aref}.
1106 (In this case, @code{aset} would be used and no such steps would
1107 be necessary since @code{aset} takes its arguments in a convenient
1108 order.)
1109
1110 However, if the @var{place} form is a macro which explicitly
1111 evaluates its arguments in an unusual order, this unusual order
1112 will be preserved.  Adapting an example from Steele, given
1113
1114 @example
1115 (defmacro wrong-order (x y) (list 'aref y x))
1116 @end example
1117
1118 @noindent
1119 the form @code{(setf (wrong-order @var{a} @var{b}) 17)} will
1120 evaluate @var{b} first, then @var{a}, just as in an actual call
1121 to @code{wrong-order}.
1122 @end defspec
1123
1124 @node Modify Macros, Customizing Setf, Basic Setf, Generalized Variables
1125 @subsection Modify Macros
1126
1127 @noindent
1128 This package defines a number of other macros besides @code{setf}
1129 that operate on generalized variables.  Many are interesting and
1130 useful even when the @var{place} is just a variable name.
1131
1132 @defspec psetf [place form]@dots{}
1133 This macro is to @code{setf} what @code{psetq} is to @code{setq}:
1134 When several @var{place}s and @var{form}s are involved, the
1135 assignments take place in parallel rather than sequentially.
1136 Specifically, all subforms are evaluated from left to right, then
1137 all the assignments are done (in an undefined order).
1138 @end defspec
1139
1140 @defspec incf place &optional x
1141 This macro increments the number stored in @var{place} by one, or
1142 by @var{x} if specified.  The incremented value is returned.  For
1143 example, @code{(incf i)} is equivalent to @code{(setq i (1+ i))}, and
1144 @code{(incf (car x) 2)} is equivalent to @code{(setcar x (+ (car x) 2))}.
1145
1146 Once again, care is taken to preserve the ``apparent'' order of
1147 evaluation.  For example,
1148
1149 @example
1150 (incf (aref vec (incf i)))
1151 @end example
1152
1153 @noindent
1154 appears to increment @code{i} once, then increment the element of
1155 @code{vec} addressed by @code{i}; this is indeed exactly what it
1156 does, which means the above form is @emph{not} equivalent to the
1157 ``obvious'' expansion,
1158
1159 @example
1160 (setf (aref vec (incf i)) (1+ (aref vec (incf i))))   ; Wrong!
1161 @end example
1162
1163 @noindent
1164 but rather to something more like
1165
1166 @example
1167 (let ((temp (incf i)))
1168   (setf (aref vec temp) (1+ (aref vec temp))))
1169 @end example
1170
1171 @noindent
1172 Again, all of this is taken care of automatically by @code{incf} and
1173 the other generalized-variable macros.
1174
1175 As a more Emacs-specific example of @code{incf}, the expression
1176 @code{(incf (point) @var{n})} is essentially equivalent to
1177 @code{(forward-char @var{n})}.
1178 @end defspec
1179
1180 @defspec decf place &optional x
1181 This macro decrements the number stored in @var{place} by one, or
1182 by @var{x} if specified.
1183 @end defspec
1184
1185 @defspec pop place
1186 This macro removes and returns the first element of the list stored
1187 in @var{place}.  It is analogous to @code{(prog1 (car @var{place})
1188 (setf @var{place} (cdr @var{place})))}, except that it takes care
1189 to evaluate all subforms only once.
1190 @end defspec
1191
1192 @defspec push x place
1193 This macro inserts @var{x} at the front of the list stored in
1194 @var{place}.  It is analogous to @code{(setf @var{place} (cons
1195 @var{x} @var{place}))}, except