cl.texi 199 KB
Newer Older
Glenn Morris's avatar
Glenn Morris committed
1
\input texinfo    @c -*-texinfo-*-
2
@setfilename ../../info/cl
Glenn Morris's avatar
Glenn Morris committed
3
@settitle Common Lisp Extensions
4
@include emacsver.texi
Glenn Morris's avatar
Glenn Morris committed
5 6 7 8

@copying
This file documents the GNU Emacs Common Lisp emulation package.

9
Copyright @copyright{} 1993, 2001-2012 Free Software Foundation, Inc.
Glenn Morris's avatar
Glenn Morris committed
10 11 12

@quotation
Permission is granted to copy, distribute and/or modify this document
13
under the terms of the GNU Free Documentation License, Version 1.3 or
Glenn Morris's avatar
Glenn Morris committed
14
any later version published by the Free Software Foundation; with no
15 16 17
Invariant Sections, with the Front-Cover texts being ``A GNU Manual'',
and with the Back-Cover Texts as in (a) below.  A copy of the license
is included in the section entitled ``GNU Free Documentation License''.
Glenn Morris's avatar
Glenn Morris committed
18

19 20 21
(a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
modify this GNU manual.  Buying copies from the FSF supports it in
developing GNU and promoting software freedom.''
Glenn Morris's avatar
Glenn Morris committed
22 23 24
@end quotation
@end copying

25
@dircategory Emacs lisp libraries
Glenn Morris's avatar
Glenn Morris committed
26
@direntry
Glenn Morris's avatar
Glenn Morris committed
27
* CL: (cl).                     Partial Common Lisp support for Emacs Lisp.
Glenn Morris's avatar
Glenn Morris committed
28 29 30 31 32 33 34 35 36 37
@end direntry

@finalout

@titlepage
@sp 6
@center @titlefont{Common Lisp Extensions}
@sp 4
@center For GNU Emacs Lisp
@sp 1
38
@center as distributed with Emacs @value{EMACSVER}
Glenn Morris's avatar
Glenn Morris committed
39 40 41 42 43 44 45 46
@sp 5
@center Dave Gillespie
@center daveg@@synaptics.com
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage

47 48 49
@contents

@ifnottex
50 51 52
@node Top
@top GNU Emacs Common Lisp Emulation

53 54 55
@insertcopying
@end ifnottex

Glenn Morris's avatar
Glenn Morris committed
56
@menu
57 58 59 60 61
* Overview::             Basics, usage, organization, naming conventions.
* Program Structure::    Arglists, @code{cl-eval-when}.
* Predicates::           Type predicates and equality predicates.
* Control Structure::    Assignment, conditionals, blocks, looping.
* Macros::               Destructuring, compiler macros.
62
* Declarations::         @code{cl-proclaim}, @code{cl-declare}, etc.
63
* Symbols::              Property lists, creating symbols.
64 65
* Numbers::              Predicates, functions, random numbers.
* Sequences::            Mapping, functions, searching, sorting.
66
* Lists::                Functions, substitution, sets, associations.
67
* Structures::           @code{cl-defstruct}.
68
* Assertions::           Assertions and type checking.
Glenn Morris's avatar
Glenn Morris committed
69

70 71 72 73 74
Appendices
* Efficiency Concerns::            Hints and techniques.
* Common Lisp Compatibility::      All known differences with Steele.
* Porting Common Lisp::            Hints for porting Common Lisp code.
* Obsolete Features::              Obsolete features.
Glenn Morris's avatar
Glenn Morris committed
75
* GNU Free Documentation License:: The license for this documentation.
76 77 78 79

Indexes
* Function Index::                 An entry for each documented function.
* Variable Index::                 An entry for each documented variable.
Glenn Morris's avatar
Glenn Morris committed
80 81
@end menu

82
@node Overview
Glenn Morris's avatar
Glenn Morris committed
83 84 85
@chapter Overview

@noindent
86 87 88 89 90
This document describes a set of Emacs Lisp facilities borrowed from
Common Lisp.  All the facilities are described here in detail.  While
this document does not assume any prior knowledge of Common Lisp, it
does assume a basic familiarity with Emacs Lisp.

Glenn Morris's avatar
Glenn Morris committed
91 92 93 94 95 96 97
Common Lisp is a huge language, and Common Lisp systems tend to be
massive and extremely complex.  Emacs Lisp, by contrast, is rather
minimalist in the choice of Lisp features it offers the programmer.
As Emacs Lisp programmers have grown in number, and the applications
they write have grown more ambitious, it has become clear that Emacs
Lisp could benefit from many of the conveniences of Common Lisp.

98
The @dfn{CL} package adds a number of Common Lisp functions and
Glenn Morris's avatar
Glenn Morris committed
99
control structures to Emacs Lisp.  While not a 100% complete
100
implementation of Common Lisp, it adds enough functionality
Glenn Morris's avatar
Glenn Morris committed
101 102 103 104 105 106 107 108 109
to make Emacs Lisp programming significantly more convenient.

Some Common Lisp features have been omitted from this package
for various reasons:

@itemize @bullet
@item
Some features are too complex or bulky relative to their benefit
to Emacs Lisp programmers.  CLOS and Common Lisp streams are fine
110 111
examples of this group.  (The separate package EIEIO implements
a subset of CLOS functionality.  @xref{Top, , Introduction, eieio, EIEIO}.)
Glenn Morris's avatar
Glenn Morris committed
112 113 114 115

@item
Other features cannot be implemented without modification to the
Emacs Lisp interpreter itself, such as multiple return values,
116
case-insensitive symbols, and complex numbers.
117
This package generally makes no attempt to emulate these features.
Glenn Morris's avatar
Glenn Morris committed
118 119 120

@end itemize

Glenn Morris's avatar
Glenn Morris committed
121 122 123 124 125 126
This package was originally written by Dave Gillespie,
@file{daveg@@synaptics.com}, as a total rewrite of an earlier 1986
@file{cl.el} package by Cesar Quiroz.  Care has been taken to ensure
that each function is defined efficiently, concisely, and with minimal
impact on the rest of the Emacs environment.  Stefan Monnier added the
file @file{cl-lib.el} and rationalized the namespace for Emacs 24.3.
Glenn Morris's avatar
Glenn Morris committed
127 128

@menu
129
* Usage::                How to use this package.
Glenn Morris's avatar
Glenn Morris committed
130
* Organization::         The package's component files.
131
* Naming Conventions::   Notes on function names.
Glenn Morris's avatar
Glenn Morris committed
132 133
@end menu

134
@node Usage
Glenn Morris's avatar
Glenn Morris committed
135 136 137
@section Usage

@noindent
138
This package is distributed with Emacs, so there is no need
139
to install any additional files in order to start using it.  Lisp code
140
that uses features from this package should simply include at
141
the beginning:
Glenn Morris's avatar
Glenn Morris committed
142 143

@example
144
(require 'cl-lib)
Glenn Morris's avatar
Glenn Morris committed
145 146 147
@end example

@noindent
148
You may wish to add such a statement to your init file, if you
149
make frequent use of features from this package.
Glenn Morris's avatar
Glenn Morris committed
150

151
@node Organization
Glenn Morris's avatar
Glenn Morris committed
152 153 154
@section Organization

@noindent
155
The Common Lisp package is organized into four main files:
Glenn Morris's avatar
Glenn Morris committed
156 157

@table @file
158 159 160
@item cl-lib.el
This is the main file, which contains basic functions
and information about the package.  This file is relatively compact.
Glenn Morris's avatar
Glenn Morris committed
161 162 163 164

@item cl-extra.el
This file contains the larger, more complex or unusual functions.
It is kept separate so that packages which only want to use Common
165
Lisp fundamentals like the @code{cl-incf} function won't need to pay
Glenn Morris's avatar
Glenn Morris committed
166 167 168 169
the overhead of loading the more advanced functions.

@item cl-seq.el
This file contains most of the advanced functions for operating
170
on sequences or lists, such as @code{cl-delete-if} and @code{cl-assoc}.
Glenn Morris's avatar
Glenn Morris committed
171 172

@item cl-macs.el
173 174 175 176 177 178
This file contains the features that are macros instead of functions.
Macros expand when the caller is compiled, not when it is run, so the
macros generally only need to be present when the byte-compiler is
running (or when the macros are used in uncompiled code).  Most of the
macros of this package are isolated in @file{cl-macs.el} so that they
won't take up memory unless you are compiling.
Glenn Morris's avatar
Glenn Morris committed
179 180
@end table

181
The file @file{cl-lib.el} includes all necessary @code{autoload}
Glenn Morris's avatar
Glenn Morris committed
182
commands for the functions and macros in the other three files.
183
All you have to do is @code{(require 'cl-lib)}, and @file{cl-lib.el}
Glenn Morris's avatar
Glenn Morris committed
184 185 186
will take care of pulling in the other files when they are
needed.

187
There is another file, @file{cl.el}, which was the main entry point to
188
this package prior to Emacs 24.3.  Nowadays, it is replaced by
189 190 191 192 193
@file{cl-lib.el}.  The two provide the same features (in most cases),
but use different function names (in fact, @file{cl.el} mainly just
defines aliases to the @file{cl-lib.el} definitions).  Where
@file{cl-lib.el} defines a function called, for example,
@code{cl-incf}, @file{cl.el} uses the same name but without the
194
@samp{cl-} prefix, e.g.@: @code{incf} in this example.  There are a few
195 196 197
exceptions to this.  First, functions such as @code{cl-defun} where
the unprefixed version was already used for a standard Emacs Lisp
function.  In such cases, the @file{cl.el} version adds a @samp{*}
198
suffix, e.g.@: @code{defun*}.  Second, there are some obsolete features
199 200 201 202 203
that are only implemented in @file{cl.el}, not in @file{cl-lib.el},
because they are replaced by other standard Emacs Lisp features.
Finally, in a very few cases the old @file{cl.el} versions do not
behave in exactly the same way as the @file{cl-lib.el} versions.
@xref{Obsolete Features}.
Glenn Morris's avatar
Glenn Morris committed
204 205
@c There is also cl-mapc, which was called cl-mapc even before cl-lib.el.
@c But not autoloaded, so maybe not much used?
206 207 208 209 210 211 212

Since the old @file{cl.el} does not use a clean namespace, Emacs has a
policy that packages distributed with Emacs must not load @code{cl} at
run time.  (It is ok for them to load @code{cl} at @emph{compile}
time, with @code{eval-when-compile}, and use the macros it provides.)
There is no such restriction on the use of @code{cl-lib}.  New code
should use @code{cl-lib} rather than @code{cl}.
213 214

There is one more file, @file{cl-compat.el}, which defines some
215
routines from the older Quiroz @file{cl.el} package that are not otherwise
216 217
present in the new package.  This file is obsolete and should not be
used in new code.
Glenn Morris's avatar
Glenn Morris committed
218

219
@node Naming Conventions
Glenn Morris's avatar
Glenn Morris committed
220 221 222 223
@section Naming Conventions

@noindent
Except where noted, all functions defined by this package have the
224 225
same calling conventions as their Common Lisp counterparts, and
names that are those of Common Lisp plus a @samp{cl-} prefix.
Glenn Morris's avatar
Glenn Morris committed
226 227

Internal function and variable names in the package are prefixed
228
by @code{cl--}.  Here is a complete list of functions prefixed by
229
@code{cl-} that were @emph{not} taken from Common Lisp:
Glenn Morris's avatar
Glenn Morris committed
230 231

@example
232
cl-callf           cl-callf2          cl-defsubst
233
cl-letf            cl-letf*
Glenn Morris's avatar
Glenn Morris committed
234 235
@end example

236 237
@c This is not uninteresting I suppose, but is of zero practical relevance
@c to the user, and seems like a hostage to changing implementation details.
238
The following simple functions and macros are defined in @file{cl-lib.el};
Glenn Morris's avatar
Glenn Morris committed
239 240 241
they do not cause other components like @file{cl-extra} to be loaded.

@example
242
cl-evenp           cl-oddp            cl-minusp
243
cl-plusp           cl-endp            cl-subst
244 245 246 247 248
cl-copy-list       cl-list*           cl-ldiff
cl-rest            cl-decf [1]        cl-incf [1]
cl-acons           cl-adjoin [2]      cl-pairlis
cl-pushnew [1,2]   cl-declaim         cl-proclaim
cl-caaar@dots{}cl-cddddr                  cl-first@dots{}cl-tenth
249
cl-mapcar [3]
Glenn Morris's avatar
Glenn Morris committed
250 251 252
@end example

@noindent
253
[1] Only when @var{place} is a plain variable name.
Glenn Morris's avatar
Glenn Morris committed
254 255

@noindent
256
[2] Only if @code{:test} is @code{eq}, @code{equal}, or unspecified,
Glenn Morris's avatar
Glenn Morris committed
257 258 259
and @code{:key} is not used.

@noindent
260
[3] Only for one sequence argument or two list arguments.
Glenn Morris's avatar
Glenn Morris committed
261

262
@node Program Structure
Glenn Morris's avatar
Glenn Morris committed
263 264 265
@chapter Program Structure

@noindent
266
This section describes features of this package that have to
Glenn Morris's avatar
Glenn Morris committed
267
do with programs as a whole: advanced argument lists for functions,
268
and the @code{cl-eval-when} construct.
Glenn Morris's avatar
Glenn Morris committed
269 270

@menu
271 272
* Argument Lists::       @code{&key}, @code{&aux}, @code{cl-defun}, @code{cl-defmacro}.
* Time of Evaluation::   The @code{cl-eval-when} construct.
Glenn Morris's avatar
Glenn Morris committed
273 274
@end menu

275
@node Argument Lists
Glenn Morris's avatar
Glenn Morris committed
276 277 278 279 280 281 282 283 284 285 286 287 288 289
@section Argument Lists

@noindent
Emacs Lisp's notation for argument lists of functions is a subset of
the Common Lisp notation.  As well as the familiar @code{&optional}
and @code{&rest} markers, Common Lisp allows you to specify default
values for optional arguments, and it provides the additional markers
@code{&key} and @code{&aux}.

Since argument parsing is built-in to Emacs, there is no way for
this package to implement Common Lisp argument lists seamlessly.
Instead, this package defines alternates for several Lisp forms
which you must use if you need Common Lisp argument lists.

290
@defmac cl-defun name arglist body@dots{}
Glenn Morris's avatar
Glenn Morris committed
291 292 293 294
This form is identical to the regular @code{defun} form, except
that @var{arglist} is allowed to be a full Common Lisp argument
list.  Also, the function body is enclosed in an implicit block
called @var{name}; @pxref{Blocks and Exits}.
295
@end defmac
Glenn Morris's avatar
Glenn Morris committed
296

297
@defmac cl-defsubst name arglist body@dots{}
298
This is just like @code{cl-defun}, except that the function that
Glenn Morris's avatar
Glenn Morris committed
299 300 301
is defined is automatically proclaimed @code{inline}, i.e.,
calls to it may be expanded into in-line code by the byte compiler.
This is analogous to the @code{defsubst} form;
302
@code{cl-defsubst} uses a different method (compiler macros) which
303
works in all versions of Emacs, and also generates somewhat more
304 305
@c For some examples,
@c see http://lists.gnu.org/archive/html/emacs-devel/2012-11/msg00009.html
306
efficient inline expansions.  In particular, @code{cl-defsubst}
Glenn Morris's avatar
Glenn Morris committed
307 308
arranges for the processing of keyword arguments, default values,
etc., to be done at compile-time whenever possible.
309
@end defmac
Glenn Morris's avatar
Glenn Morris committed
310

311
@defmac cl-defmacro name arglist body@dots{}
Glenn Morris's avatar
Glenn Morris committed
312 313 314
This is identical to the regular @code{defmacro} form,
except that @var{arglist} is allowed to be a full Common Lisp
argument list.  The @code{&environment} keyword is supported as
Glenn Morris's avatar
Glenn Morris committed
315 316
described in Steele's book @cite{Common Lisp, the Language}.
The @code{&whole} keyword is supported only
Glenn Morris's avatar
Glenn Morris committed
317 318 319 320
within destructured lists (see below); top-level @code{&whole}
cannot be implemented with the current Emacs Lisp interpreter.
The macro expander body is enclosed in an implicit block called
@var{name}.
321
@end defmac
Glenn Morris's avatar
Glenn Morris committed
322

323
@defmac cl-function symbol-or-lambda
Glenn Morris's avatar
Glenn Morris committed
324 325 326
This is identical to the regular @code{function} form,
except that if the argument is a @code{lambda} form then that
form may use a full Common Lisp argument list.
327
@end defmac
Glenn Morris's avatar
Glenn Morris committed
328

329
Also, all forms (such as @code{cl-flet} and @code{cl-labels}) defined
Glenn Morris's avatar
Glenn Morris committed
330 331 332
in this package that include @var{arglist}s in their syntax allow
full Common Lisp argument lists.

333
Note that it is @emph{not} necessary to use @code{cl-defun} in
334
order to have access to most CL features in your function.
335
These features are always present; @code{cl-defun}'s only
Glenn Morris's avatar
Glenn Morris committed
336 337 338 339 340 341
difference from @code{defun} is its more flexible argument
lists and its implicit block.

The full form of a Common Lisp argument list is

@example
342 343
(@var{var}@dots{}
 &optional (@var{var} @var{initform} @var{svar})@dots{}
Glenn Morris's avatar
Glenn Morris committed
344
 &rest @var{var}
345 346
 &key ((@var{keyword} @var{var}) @var{initform} @var{svar})@dots{}
 &aux (@var{var} @var{initform})@dots{})
Glenn Morris's avatar
Glenn Morris committed
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
@end example

Each of the five argument list sections is optional.  The @var{svar},
@var{initform}, and @var{keyword} parts are optional; if they are
omitted, then @samp{(@var{var})} may be written simply @samp{@var{var}}.

The first section consists of zero or more @dfn{required} arguments.
These arguments must always be specified in a call to the function;
there is no difference between Emacs Lisp and Common Lisp as far as
required arguments are concerned.

The second section consists of @dfn{optional} arguments.  These
arguments may be specified in the function call; if they are not,
@var{initform} specifies the default value used for the argument.
(No @var{initform} means to use @code{nil} as the default.)  The
@var{initform} is evaluated with the bindings for the preceding
arguments already established; @code{(a &optional (b (1+ a)))}
matches one or two arguments, with the second argument defaulting
to one plus the first argument.  If the @var{svar} is specified,
it is an auxiliary variable which is bound to @code{t} if the optional
argument was specified, or to @code{nil} if the argument was omitted.
If you don't use an @var{svar}, then there will be no way for your
function to tell whether it was called with no argument, or with
the default value passed explicitly as an argument.

The third section consists of a single @dfn{rest} argument.  If
more arguments were passed to the function than are accounted for
by the required and optional arguments, those extra arguments are
collected into a list and bound to the ``rest'' argument variable.
Common Lisp's @code{&rest} is equivalent to that of Emacs Lisp.
Common Lisp accepts @code{&body} as a synonym for @code{&rest} in
macro contexts; this package accepts it all the time.

The fourth section consists of @dfn{keyword} arguments.  These
are optional arguments which are specified by name rather than
positionally in the argument list.  For example,

@example
385
(cl-defun foo (a &optional b &key c d (e 17)))
Glenn Morris's avatar
Glenn Morris committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
@end example

@noindent
defines a function which may be called with one, two, or more
arguments.  The first two arguments are bound to @code{a} and
@code{b} in the usual way.  The remaining arguments must be
pairs of the form @code{:c}, @code{:d}, or @code{:e} followed
by the value to be bound to the corresponding argument variable.
(Symbols whose names begin with a colon are called @dfn{keywords},
and they are self-quoting in the same way as @code{nil} and
@code{t}.)

For example, the call @code{(foo 1 2 :d 3 :c 4)} sets the five
arguments to 1, 2, 4, 3, and 17, respectively.  If the same keyword
appears more than once in the function call, the first occurrence
takes precedence over the later ones.  Note that it is not possible
to specify keyword arguments without specifying the optional
argument @code{b} as well, since @code{(foo 1 :c 2)} would bind
@code{b} to the keyword @code{:c}, then signal an error because
@code{2} is not a valid keyword.

407 408 409 410
You can also explicitly specify the keyword argument; it need not be
simply the variable name prefixed with a colon.  For example,

@example
411
(cl-defun bar (&key (a 1) ((baz b) 4)))
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
@end example

@noindent

specifies a keyword @code{:a} that sets the variable @code{a} with
default value 1, as well as a keyword @code{baz} that sets the
variable @code{b} with default value 4.  In this case, because
@code{baz} is not self-quoting, you must quote it explicitly in the
function call, like this:

@example
(bar :a 10 'baz 42)
@end example

Ordinarily, it is an error to pass an unrecognized keyword to
Glenn Morris's avatar
Glenn Morris committed
427 428 429 430 431 432 433 434 435
a function, e.g., @code{(foo 1 2 :c 3 :goober 4)}.  You can ask
Lisp to ignore unrecognized keywords, either by adding the
marker @code{&allow-other-keys} after the keyword section
of the argument list, or by specifying an @code{:allow-other-keys}
argument in the call whose value is non-@code{nil}.  If the
function uses both @code{&rest} and @code{&key} at the same time,
the ``rest'' argument is bound to the keyword list as it appears
in the call.  For example:

436
@example
437 438
(cl-defun find-thing (thing &rest rest &key need &allow-other-keys)
  (or (apply 'cl-member thing thing-list :allow-other-keys t rest)
Glenn Morris's avatar
Glenn Morris committed
439
      (if need (error "Thing not found"))))
440
@end example
Glenn Morris's avatar
Glenn Morris committed
441 442 443 444

@noindent
This function takes a @code{:need} keyword argument, but also
accepts other keyword arguments which are passed on to the
445 446
@code{cl-member} function.  @code{allow-other-keys} is used to
keep both @code{find-thing} and @code{cl-member} from complaining
Glenn Morris's avatar
Glenn Morris committed
447 448 449 450 451 452 453 454 455 456
about each others' keywords in the arguments.

The fifth section of the argument list consists of @dfn{auxiliary
variables}.  These are not really arguments at all, but simply
variables which are bound to @code{nil} or to the specified
@var{initforms} during execution of the function.  There is no
difference between the following two functions, except for a
matter of stylistic taste:

@example
457
(cl-defun foo (a b &aux (c (+ a b)) d)
Glenn Morris's avatar
Glenn Morris committed
458 459
  @var{body})

460
(cl-defun foo (a b)
Glenn Morris's avatar
Glenn Morris committed
461 462 463 464 465 466
  (let ((c (+ a b)) d)
    @var{body}))
@end example

Argument lists support @dfn{destructuring}.  In Common Lisp,
destructuring is only allowed with @code{defmacro}; this package
467
allows it with @code{cl-defun} and other argument lists as well.
Glenn Morris's avatar
Glenn Morris committed
468
In destructuring, any argument variable (@var{var} in the above
Glenn Morris's avatar
Glenn Morris committed
469
example) can be replaced by a list of variables, or more generally,
Glenn Morris's avatar
Glenn Morris committed
470 471 472 473 474
a recursive argument list.  The corresponding argument value must
be a list whose elements match this recursive argument list.
For example:

@example
475
(cl-defmacro dolist ((var listform &optional resultform)
Glenn Morris's avatar
Glenn Morris committed
476
                   &rest body)
477
  @dots{})
Glenn Morris's avatar
Glenn Morris committed
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
@end example

This says that the first argument of @code{dolist} must be a list
of two or three items; if there are other arguments as well as this
list, they are stored in @code{body}.  All features allowed in
regular argument lists are allowed in these recursive argument lists.
In addition, the clause @samp{&whole @var{var}} is allowed at the
front of a recursive argument list.  It binds @var{var} to the
whole list being matched; thus @code{(&whole all a b)} matches
a list of two things, with @code{a} bound to the first thing,
@code{b} bound to the second thing, and @code{all} bound to the
list itself.  (Common Lisp allows @code{&whole} in top-level
@code{defmacro} argument lists as well, but Emacs Lisp does not
support this usage.)

One last feature of destructuring is that the argument list may be
dotted, so that the argument list @code{(a b . c)} is functionally
equivalent to @code{(a b &rest c)}.

If the optimization quality @code{safety} is set to 0
(@pxref{Declarations}), error checking for wrong number of
arguments and invalid keyword arguments is disabled.  By default,
argument lists are rigorously checked.

502
@node Time of Evaluation
Glenn Morris's avatar
Glenn Morris committed
503 504 505 506 507 508 509 510 511 512 513 514 515
@section Time of Evaluation

@noindent
Normally, the byte-compiler does not actually execute the forms in
a file it compiles.  For example, if a file contains @code{(setq foo t)},
the act of compiling it will not actually set @code{foo} to @code{t}.
This is true even if the @code{setq} was a top-level form (i.e., not
enclosed in a @code{defun} or other form).  Sometimes, though, you
would like to have certain top-level forms evaluated at compile-time.
For example, the compiler effectively evaluates @code{defmacro} forms
at compile-time so that later parts of the file can refer to the
macros that are defined.

516
@defmac cl-eval-when (situations@dots{}) forms@dots{}
Glenn Morris's avatar
Glenn Morris committed
517 518 519 520 521 522
This form controls when the body @var{forms} are evaluated.
The @var{situations} list may contain any set of the symbols
@code{compile}, @code{load}, and @code{eval} (or their long-winded
ANSI equivalents, @code{:compile-toplevel}, @code{:load-toplevel},
and @code{:execute}).

523
The @code{cl-eval-when} form is handled differently depending on
Glenn Morris's avatar
Glenn Morris committed
524 525 526 527 528 529
whether or not it is being compiled as a top-level form.
Specifically, it gets special treatment if it is being compiled
by a command such as @code{byte-compile-file} which compiles files
or buffers of code, and it appears either literally at the
top level of the file or inside a top-level @code{progn}.

530
For compiled top-level @code{cl-eval-when}s, the body @var{forms} are
Glenn Morris's avatar
Glenn Morris committed
531 532 533 534 535 536 537
executed at compile-time if @code{compile} is in the @var{situations}
list, and the @var{forms} are written out to the file (to be executed
at load-time) if @code{load} is in the @var{situations} list.

For non-compiled-top-level forms, only the @code{eval} situation is
relevant.  (This includes forms executed by the interpreter, forms
compiled with @code{byte-compile} rather than @code{byte-compile-file},
538
and non-top-level forms.)  The @code{cl-eval-when} acts like a
Glenn Morris's avatar
Glenn Morris committed
539 540 541
@code{progn} if @code{eval} is specified, and like @code{nil}
(ignoring the body @var{forms}) if not.

542
The rules become more subtle when @code{cl-eval-when}s are nested;
Glenn Morris's avatar
Glenn Morris committed
543 544 545 546 547 548 549
consult Steele (second edition) for the gruesome details (and
some gruesome examples).

Some simple examples:

@example
;; Top-level forms in foo.el:
550 551 552 553 554 555 556
(cl-eval-when (compile)           (setq foo1 'bar))
(cl-eval-when (load)              (setq foo2 'bar))
(cl-eval-when (compile load)      (setq foo3 'bar))
(cl-eval-when (eval)              (setq foo4 'bar))
(cl-eval-when (eval compile)      (setq foo5 'bar))
(cl-eval-when (eval load)         (setq foo6 'bar))
(cl-eval-when (eval compile load) (setq foo7 'bar))
Glenn Morris's avatar
Glenn Morris committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
@end example

When @file{foo.el} is compiled, these variables will be set during
the compilation itself:

@example
foo1  foo3  foo5  foo7      ; `compile'
@end example

When @file{foo.elc} is loaded, these variables will be set:

@example
foo2  foo3  foo6  foo7      ; `load'
@end example

And if @file{foo.el} is loaded uncompiled, these variables will
be set:

@example
foo4  foo5  foo6  foo7      ; `eval'
@end example

579
If these seven @code{cl-eval-when}s had been, say, inside a @code{defun},
Glenn Morris's avatar
Glenn Morris committed
580 581 582
then the first three would have been equivalent to @code{nil} and the
last four would have been equivalent to the corresponding @code{setq}s.

583
Note that @code{(cl-eval-when (load eval) @dots{})} is equivalent
Glenn Morris's avatar
Glenn Morris committed
584 585
to @code{(progn @dots{})} in all contexts.  The compiler treats
certain top-level forms, like @code{defmacro} (sort-of) and
Glenn Morris's avatar
Glenn Morris committed
586
@code{require}, as if they were wrapped in @code{(cl-eval-when
Glenn Morris's avatar
Glenn Morris committed
587
(compile load eval) @dots{})}.
588
@end defmac
Glenn Morris's avatar
Glenn Morris committed
589

590
Emacs includes two special forms related to @code{cl-eval-when}.
Glenn Morris's avatar
Glenn Morris committed
591
@xref{Eval During Compile,,,elisp,GNU Emacs Lisp Reference Manual}.
Glenn Morris's avatar
Glenn Morris committed
592
One of these, @code{eval-when-compile}, is not quite equivalent to
Glenn Morris's avatar
Glenn Morris committed
593
any @code{cl-eval-when} construct and is described below.
Glenn Morris's avatar
Glenn Morris committed
594 595

The other form, @code{(eval-and-compile @dots{})}, is exactly
Glenn Morris's avatar
Glenn Morris committed
596
equivalent to @samp{(cl-eval-when (compile load eval) @dots{})}.
Glenn Morris's avatar
Glenn Morris committed
597

598
@defmac eval-when-compile forms@dots{}
Glenn Morris's avatar
Glenn Morris committed
599 600 601 602 603 604 605 606
The @var{forms} are evaluated at compile-time; at execution time,
this form acts like a quoted constant of the resulting value.  Used
at top-level, @code{eval-when-compile} is just like @samp{eval-when
(compile eval)}.  In other contexts, @code{eval-when-compile}
allows code to be evaluated once at compile-time for efficiency
or other reasons.

This form is similar to the @samp{#.} syntax of true Common Lisp.
607
@end defmac
Glenn Morris's avatar
Glenn Morris committed
608

609
@defmac cl-load-time-value form
Glenn Morris's avatar
Glenn Morris committed
610 611 612 613 614 615 616
The @var{form} is evaluated at load-time; at execution time,
this form acts like a quoted constant of the resulting value.

Early Common Lisp had a @samp{#,} syntax that was similar to
this, but ANSI Common Lisp replaced it with @code{load-time-value}
and gave it more well-defined semantics.

617
In a compiled file, @code{cl-load-time-value} arranges for @var{form}
Glenn Morris's avatar
Glenn Morris committed
618 619 620 621
to be evaluated when the @file{.elc} file is loaded and then used
as if it were a quoted constant.  In code compiled by
@code{byte-compile} rather than @code{byte-compile-file}, the
effect is identical to @code{eval-when-compile}.  In uncompiled
622
code, both @code{eval-when-compile} and @code{cl-load-time-value}
Glenn Morris's avatar
Glenn Morris committed
623 624 625 626 627 628 629 630 631 632
act exactly like @code{progn}.

@example
(defun report ()
  (insert "This function was executed on: "
          (current-time-string)
          ", compiled on: "
          (eval-when-compile (current-time-string))
          ;; or '#.(current-time-string) in real Common Lisp
          ", and loaded on: "
633
          (cl-load-time-value (current-time-string))))
Glenn Morris's avatar
Glenn Morris committed
634 635 636 637 638 639 640 641 642 643 644 645
@end example

@noindent
Byte-compiled, the above defun will result in the following code
(or its compiled equivalent, of course) in the @file{.elc} file:

@example
(setq --temp-- (current-time-string))
(defun report ()
  (insert "This function was executed on: "
          (current-time-string)
          ", compiled on: "
646
          '"Wed Oct 31 16:32:28 2012"
Glenn Morris's avatar
Glenn Morris committed
647 648 649
          ", and loaded on: "
          --temp--))
@end example
650
@end defmac
Glenn Morris's avatar
Glenn Morris committed
651

652
@node Predicates
Glenn Morris's avatar
Glenn Morris committed
653 654 655 656 657 658 659
@chapter Predicates

@noindent
This section describes functions for testing whether various
facts are true or false.

@menu
660 661
* Type Predicates::      @code{cl-typep}, @code{cl-deftype}, and @code{cl-coerce}.
* Equality Predicates::  @code{cl-equalp}.
Glenn Morris's avatar
Glenn Morris committed
662 663
@end menu

664
@node Type Predicates
Glenn Morris's avatar
Glenn Morris committed
665 666
@section Type Predicates

667
@defun cl-typep object type
Glenn Morris's avatar
Glenn Morris committed
668 669
Check if @var{object} is of type @var{type}, where @var{type} is a
(quoted) type name of the sort used by Common Lisp.  For example,
670
@code{(cl-typep foo 'integer)} is equivalent to @code{(integerp foo)}.
Glenn Morris's avatar
Glenn Morris committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684
@end defun

The @var{type} argument to the above function is either a symbol
or a list beginning with a symbol.

@itemize @bullet
@item
If the type name is a symbol, Emacs appends @samp{-p} to the
symbol name to form the name of a predicate function for testing
the type.  (Built-in predicates whose names end in @samp{p} rather
than @samp{-p} are used when appropriate.)

@item
The type symbol @code{t} stands for the union of all types.
685
@code{(cl-typep @var{object} t)} is always true.  Likewise, the
Glenn Morris's avatar
Glenn Morris committed
686
type symbol @code{nil} stands for nothing at all, and
687
@code{(cl-typep @var{object} nil)} is always false.
Glenn Morris's avatar
Glenn Morris committed
688 689 690

@item
The type symbol @code{null} represents the symbol @code{nil}.
691
Thus @code{(cl-typep @var{object} 'null)} is equivalent to
Glenn Morris's avatar
Glenn Morris committed
692 693 694 695
@code{(null @var{object})}.

@item
The type symbol @code{atom} represents all objects that are not cons
696
cells. Thus @code{(cl-typep @var{object} 'atom)} is equivalent to
Glenn Morris's avatar
Glenn Morris committed
697 698 699 700 701 702 703 704 705 706
@code{(atom @var{object})}.

@item
The type symbol @code{real} is a synonym for @code{number}, and
@code{fixnum} is a synonym for @code{integer}.

@item
The type symbols @code{character} and @code{string-char} match
integers in the range from 0 to 255.

707 708
@c No longer relevant, so covered by first item above (float -> floatp).
@ignore
Glenn Morris's avatar
Glenn Morris committed
709
@item
710
The type symbol @code{float} uses the @code{cl-floatp-safe} predicate
Glenn Morris's avatar
Glenn Morris committed
711 712
defined by this package rather than @code{floatp}, so it will work
correctly even in Emacs versions without floating-point support.
713
@end ignore
Glenn Morris's avatar
Glenn Morris committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

@item
The type list @code{(integer @var{low} @var{high})} represents all
integers between @var{low} and @var{high}, inclusive.  Either bound
may be a list of a single integer to specify an exclusive limit,
or a @code{*} to specify no limit.  The type @code{(integer * *)}
is thus equivalent to @code{integer}.

@item
Likewise, lists beginning with @code{float}, @code{real}, or
@code{number} represent numbers of that type falling in a particular
range.

@item
Lists beginning with @code{and}, @code{or}, and @code{not} form
combinations of types.  For example, @code{(or integer (float 0 *))}
represents all objects that are integers or non-negative floats.

@item
733
Lists beginning with @code{member} or @code{cl-member} represent
Glenn Morris's avatar
Glenn Morris committed
734 735 736 737 738 739 740 741 742 743 744
objects @code{eql} to any of the following values.  For example,
@code{(member 1 2 3 4)} is equivalent to @code{(integer 1 4)},
and @code{(member nil)} is equivalent to @code{null}.

@item
Lists of the form @code{(satisfies @var{predicate})} represent
all objects for which @var{predicate} returns true when called
with that object as an argument.
@end itemize

The following function and macro (not technically predicates) are
745
related to @code{cl-typep}.
Glenn Morris's avatar
Glenn Morris committed
746

747
@defun cl-coerce object type
Glenn Morris's avatar
Glenn Morris committed
748 749
This function attempts to convert @var{object} to the specified
@var{type}.  If @var{object} is already of that type as determined by
Glenn Morris's avatar
Glenn Morris committed
750
@code{cl-typep}, it is simply returned.  Otherwise, certain types of
Glenn Morris's avatar
Glenn Morris committed
751 752 753 754 755 756
conversions will be made:  If @var{type} is any sequence type
(@code{string}, @code{list}, etc.) then @var{object} will be
converted to that type if possible.  If @var{type} is
@code{character}, then strings of length one and symbols with
one-character names can be coerced.  If @var{type} is @code{float},
then integers can be coerced in versions of Emacs that support
757
floats.  In all other circumstances, @code{cl-coerce} signals an
Glenn Morris's avatar
Glenn Morris committed
758 759 760
error.
@end defun

761
@defmac cl-deftype name arglist forms@dots{}
Glenn Morris's avatar
Glenn Morris committed
762 763 764 765 766
This macro defines a new type called @var{name}.  It is similar
to @code{defmacro} in many ways; when @var{name} is encountered
as a type name, the body @var{forms} are evaluated and should
return a type specifier that is equivalent to the type.  The
@var{arglist} is a Common Lisp argument list of the sort accepted
767
by @code{cl-defmacro}.  The type specifier @samp{(@var{name} @var{args}@dots{})}
Glenn Morris's avatar
Glenn Morris committed
768 769 770
is expanded by calling the expander with those arguments; the type
symbol @samp{@var{name}} is expanded by calling the expander with
no arguments.  The @var{arglist} is processed the same as for
771
@code{cl-defmacro} except that optional arguments without explicit
Glenn Morris's avatar
Glenn Morris committed
772 773 774 775
defaults use @code{*} instead of @code{nil} as the ``default''
default.  Some examples:

@example
776 777 778
(cl-deftype null () '(satisfies null))    ; predefined
(cl-deftype list () '(or null cons))      ; predefined
(cl-deftype unsigned-byte (&optional bits)
Glenn Morris's avatar
Glenn Morris committed
779 780 781 782 783 784 785 786 787 788
  (list 'integer 0 (if (eq bits '*) bits (1- (lsh 1 bits)))))
(unsigned-byte 8)  @equiv{}  (integer 0 255)
(unsigned-byte)  @equiv{}  (integer 0 *)
unsigned-byte  @equiv{}  (integer 0 *)
@end example

@noindent
The last example shows how the Common Lisp @code{unsigned-byte}
type specifier could be implemented if desired; this package does
not implement @code{unsigned-byte} by default.
789
@end defmac
Glenn Morris's avatar
Glenn Morris committed
790

Glenn Morris's avatar
Glenn Morris committed
791 792
The @code{cl-typecase} (@pxref{Conditionals}) and @code{cl-check-type}
(@pxref{Assertions}) macros also use type names.  The @code{cl-map},
793
@code{cl-concatenate}, and @code{cl-merge} functions take type-name
Glenn Morris's avatar
Glenn Morris committed
794 795
arguments to specify the type of sequence to return.  @xref{Sequences}.

796
@node Equality Predicates
Glenn Morris's avatar
Glenn Morris committed
797 798 799
@section Equality Predicates

@noindent
800
This package defines the Common Lisp predicate @code{cl-equalp}.
Glenn Morris's avatar
Glenn Morris committed
801

802
@defun cl-equalp a b
Glenn Morris's avatar
Glenn Morris committed
803 804
This function is a more flexible version of @code{equal}.  In
particular, it compares strings case-insensitively, and it compares
805
numbers without regard to type (so that @code{(cl-equalp 3 3.0)} is
Glenn Morris's avatar
Glenn Morris committed
806 807 808 809 810 811 812 813
true).  Vectors and conses are compared recursively.  All other
objects are compared as if by @code{equal}.

This function differs from Common Lisp @code{equalp} in several
respects.  First, Common Lisp's @code{equalp} also compares
@emph{characters} case-insensitively, which would be impractical
in this package since Emacs does not distinguish between integers
and characters.  In keeping with the idea that strings are less
814
vector-like in Emacs Lisp, this package's @code{cl-equalp} also will
Glenn Morris's avatar
Glenn Morris committed
815 816 817 818 819 820
not compare strings against vectors of integers.
@end defun

Also note that the Common Lisp functions @code{member} and @code{assoc}
use @code{eql} to compare elements, whereas Emacs Lisp follows the
MacLisp tradition and uses @code{equal} for these two functions.
821 822
In Emacs, use @code{memq} (or @code{cl-member}) and @code{assq} (or
@code{cl-assoc}) to get functions which use @code{eql} for comparisons.
Glenn Morris's avatar
Glenn Morris committed
823

824
@node Control Structure
Glenn Morris's avatar
Glenn Morris committed
825 826 827 828
@chapter Control Structure

@noindent
The features described in the following sections implement
829 830
various advanced control structures, including extensions to the
standard @code{setf} facility, and a number of looping and conditional
Glenn Morris's avatar
Glenn Morris committed
831 832 833
constructs.

@menu
834
* Assignment::             The @code{cl-psetq} form.
835
* Generalized Variables::  Extensions to generalized variables.
836
* Variable Bindings::      @code{cl-progv}, @code{cl-flet}, @code{cl-macrolet}.
837 838 839
* Conditionals::           @code{cl-case}, @code{cl-typecase}.
* Blocks and Exits::       @code{cl-block}, @code{cl-return}, @code{cl-return-from}.
* Iteration::              @code{cl-do}, @code{cl-dotimes}, @code{cl-dolist}, @code{cl-do-symbols}.
840
* Loop Facility::          The Common Lisp @code{loop} macro.
Glenn Morris's avatar
Glenn Morris committed
841
* Multiple Values::        @code{cl-values}, @code{cl-multiple-value-bind}, etc.
Glenn Morris's avatar
Glenn Morris committed
842 843
@end menu

844
@node Assignment
Glenn Morris's avatar
Glenn Morris committed
845 846 847
@section Assignment

@noindent
848
The @code{cl-psetq} form is just like @code{setq}, except that multiple
Glenn Morris's avatar
Glenn Morris committed
849 850
assignments are done in parallel rather than sequentially.

851
@defmac cl-psetq [symbol form]@dots{}
Glenn Morris's avatar
Glenn Morris committed
852 853 854 855 856 857 858 859 860 861 862 863 864 865
This special form (actually a macro) is used to assign to several
variables simultaneously.  Given only one @var{symbol} and @var{form},
it has the same effect as @code{setq}.  Given several @var{symbol}
and @var{form} pairs, it evaluates all the @var{form}s in advance
and then stores the corresponding variables afterwards.

@example
(setq x 2 y 3)
(setq x (+ x y)  y (* x y))
x
     @result{} 5
y                     ; @r{@code{y} was computed after @code{x} was set.}
     @result{} 15
(setq x 2 y 3)
866
(cl-psetq x (+ x y)  y (* x y))
Glenn Morris's avatar
Glenn Morris committed
867 868 869 870 871 872
x
     @result{} 5
y                     ; @r{@code{y} was computed before @code{x} was set.}
     @result{} 6
@end example

873 874
The simplest use of @code{cl-psetq} is @code{(cl-psetq x y y x)}, which
exchanges the values of two variables.  (The @code{cl-rotatef} form
Glenn Morris's avatar
Glenn Morris committed
875 876 877
provides an even more convenient way to swap two variables;
@pxref{Modify Macros}.)

878
@code{cl-psetq} always returns @code{nil}.
879
@end defmac
Glenn Morris's avatar
Glenn Morris committed
880

881
@node Generalized Variables
Glenn Morris's avatar
Glenn Morris committed
882 883
@section Generalized Variables

884 885
A @dfn{generalized variable} or @dfn{place form} is one of the many
places in Lisp memory where values can be stored.  The simplest place
886
form is a regular Lisp variable.  But the @sc{car}s and @sc{cdr}s of lists,
887 888 889 890 891
elements of arrays, properties of symbols, and many other locations
are also places where Lisp values are stored.  For basic information,
@pxref{Generalized Variables,,,elisp,GNU Emacs Lisp Reference Manual}.
This package provides several additional features related to
generalized variables.
Glenn Morris's avatar
Glenn Morris committed
892 893

@menu
894
* Setf Extensions::    Additional @code{setf} places.
895
* Modify Macros::      @code{cl-incf}, @code{cl-rotatef}, @code{cl-letf}, @code{cl-callf}, etc.
Glenn Morris's avatar
Glenn Morris committed
896 897
@end menu

898 899
@node Setf Extensions
@subsection Setf Extensions
Glenn Morris's avatar
Glenn Morris committed
900

901 902
Several standard (e.g.@: @code{car}) and Emacs-specific
(e.g.@: @code{window-point}) Lisp functions are @code{setf}-able by default.
903
This package defines @code{setf} handlers for several additional functions:
Glenn Morris's avatar
Glenn Morris committed
904

905
@itemize
Glenn Morris's avatar
Glenn Morris committed
906
@item
907 908 909 910 911
Functions from this package:
@example
cl-rest        cl-subseq      cl-get         cl-getf
cl-caaar@dots{}cl-cddddr          cl-first@dots{}cl-tenth
@end example
Glenn Morris's avatar
Glenn Morris committed
912

913 914 915 916
@noindent
Note that for @code{cl-getf} (as for @code{nthcdr}), the list argument
of the function must itself be a valid @var{place} form.

Glenn Morris's avatar
Glenn Morris committed
917
@item
918
General Emacs Lisp functions:
919
@example
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
buffer-file-name                   getenv
buffer-modified-p                  global-key-binding
buffer-name                        local-key-binding
buffer-string                      mark
buffer-substring                   mark-marker
current-buffer                     marker-position
current-case-table                 mouse-position
current-column                     point
current-global-map                 point-marker
current-input-mode                 point-max
current-local-map                  point-min
current-window-configuration       read-mouse-position
default-file-modes                 screen-height
documentation-property             screen-width
face-background                    selected-window
face-background-pixmap             selected-screen
face-font                          selected-frame
face-foreground                    standard-case-table
face-underline-p                   syntax-table
file-modes                         visited-file-modtime
frame-height                       window-height
frame-parameters                   window-width
frame-visible-p                    x-get-secondary-selection
frame-width                        x-get-selection
get-register
945
@end example
Glenn Morris's avatar
Glenn Morris committed
946 947 948 949

Most of these have directly corresponding ``set'' functions, like
@code{use-local-map} for @code{current-local-map}, or @code{goto-char}
for @code{point}.  A few, like @code{point-min}, expand to longer
950 951
sequences of code when they are used with @code{setf}
(@code{(narrow-to-region x (point-max))} in this case).
Glenn Morris's avatar
Glenn Morris committed
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977

@item
A call of the form @code{(substring @var{subplace} @var{n} [@var{m}])},
where @var{subplace} is itself a valid generalized variable whose
current value is a string, and where the value stored is also a
string.  The new string is spliced into the specified part of the
destination string.  For example:

@example
(setq a (list "hello" "world"))
     @result{} ("hello" "world")
(cadr a)
     @result{} "world"
(substring (cadr a) 2 4)
     @result{} "rl"
(setf (substring (cadr a) 2 4) "o")
     @result{} "o"
(cadr a)
     @result{} "wood"
a
     @result{} ("hello" "wood")
@end example

The generalized variable @code{buffer-substring}, listed above,
also works in this way by replacing a portion of the current buffer.

978 979
@c FIXME? Also `eq'? (see cl-lib.el)

980 981
@c Currently commented out in cl.el.
@ignore
Glenn Morris's avatar
Glenn Morris committed
982 983 984 985 986 987 988 989
@item
A call of the form @code{(apply '@var{func} @dots{})} or
@code{(apply (function @var{func}) @dots{})}, where @var{func}
is a @code{setf}-able function whose store function is ``suitable''
in the sense described in Steele's book; since none of the standard
Emacs place functions are suitable in this sense, this feature is
only interesting when used with places you define yourself with
@code{define-setf-method} or the long form of @code{defsetf}.
990
@xref{Obsolete Setf Customization}.
991
@end ignore
Glenn Morris's avatar
Glenn Morris committed
992 993