cl.texi 210 KB
Newer Older
Dave Love's avatar
Dave Love committed
1 2 3 4
\input texinfo    @c -*-texinfo-*-
@setfilename ../info/cl
@settitle Common Lisp Extensions

Karl Berry's avatar
Karl Berry committed
Dave Love's avatar
Dave Love committed
6 7
This file documents the GNU Emacs Common Lisp emulation package.

Karl Berry's avatar
Karl Berry committed
Copyright (C) 1993, 2002 Free Software Foundation, Inc.
Dave Love's avatar
Dave Love committed

Karl Berry's avatar
Karl Berry committed
Dave Love's avatar
Dave Love committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1 or
any later version published by the Free Software Foundation; with no
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'' in the Emacs manual.

(a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
this GNU Manual, like GNU software.  Copies published by the Free
Software Foundation raise funds for GNU development.''

This document is part of a collection distributed under the GNU Free
Documentation License.  If you want to distribute this document
separately from the collection, you can do so by adding a copy of the
license to the document, as described in section 6 of the license.
Karl Berry's avatar
Karl Berry committed
27 28 29 30 31 32 33 34 35
@end quotation
@end copying

@dircategory Emacs
* CL: (cl).		Partial Common Lisp support for Emacs Lisp.
@end direntry

Dave Love's avatar
Dave Love committed
36 37 38 39 40 41 42 43 44 45 46 47 48

@sp 6
@center @titlefont{Common Lisp Extensions}
@sp 4
@center For GNU Emacs Lisp
@sp 1
@center Version 2.02
@sp 5
@center Dave Gillespie
@vskip 0pt plus 1filll
Karl Berry's avatar
Karl Berry committed
Dave Love's avatar
Dave Love committed
50 51
@end titlepage

@node Top, Overview, (dir), (dir)
Dave Love's avatar
Dave Love committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
@chapter Common Lisp Extensions

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.

* Overview::             Installation, usage, etc.
* Program Structure::    Arglists, `eval-when', `defalias'
* Predicates::           `typep', `eql', and `equalp'
* Control Structure::    `setf', `do', `loop', etc.
* Macros::               Destructuring, `define-compiler-macro'
* Declarations::         `proclaim', `declare', etc.
* Symbols::              Property lists, `gensym'
* Numbers::              Predicates, functions, random numbers
* Sequences::            Mapping, functions, searching, sorting
* Lists::                `cadr', `sublis', `member*', `assoc*', etc.
* Structures::           `defstruct'
* Assertions::           `check-type', `assert', `ignore-errors'.

* Efficiency Concerns::         Hints and techniques
* Common Lisp Compatibility::   All known differences with Steele
* Old CL Compatibility::        All known differences with old cl.el
* Porting Common Lisp::         Hints for porting Common Lisp code

* Function Index::
* Variable Index::
@end menu

@node Overview, Program Structure, Top, Top
@chapter Overview
@end ifinfo
@section Overview
@end iftex

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.

The @dfn{CL} package adds a number of Common Lisp functions and
control structures to Emacs Lisp.  While not a 100% complete
implementation of Common Lisp, @dfn{CL} adds enough functionality
to make Emacs Lisp programming significantly more convenient.

105 106 107 108 109 110 111 112 113 114
@strong{Please note:} the @dfn{CL} functions are not standard parts of
the Emacs Lisp name space, so it is legitimate for users to define
them with other, conflicting meanings.  To avoid conflicting with
those user activities, we have a policy that packages installed in
Emacs must not load @dfn{CL} at run time.  (It is ok for them to load
@dfn{CL} at compile time only, with @code{eval-when-compile}, and use
the macros it provides.)  If you are writing packages that you plan to
distribute and invite widespread use for, you might want to observe
the same rule.

Dave Love's avatar
Dave Love committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
Some Common Lisp features have been omitted from this package
for various reasons:

@itemize @bullet
Some features are too complex or bulky relative to their benefit
to Emacs Lisp programmers.  CLOS and Common Lisp streams are fine
examples of this group.

Other features cannot be implemented without modification to the
Emacs Lisp interpreter itself, such as multiple return values,
lexical scoping, case-insensitive symbols, and complex numbers.
The @dfn{CL} package generally makes no attempt to emulate these

Some features conflict with existing things in Emacs Lisp.  For
example, Emacs' @code{assoc} function is incompatible with the
Common Lisp @code{assoc}.  In such cases, this package usually
adds the suffix @samp{*} to the function name of the Common
Lisp version of the function (e.g., @code{assoc*}).
@end itemize

The package described here was written by Dave Gillespie,
@file{}.  It is a total rewrite of the original
1986 @file{cl.el} package by Cesar Quiroz.  Most features of the
the Quiroz package have been retained; any incompatibilities are
noted in the descriptions below.  Care has been taken in this
version to ensure that each function is defined efficiently,
concisely, and with minimal impact on the rest of the Emacs

* Usage::                How to use the CL package
* Organization::         The package's five component files
* Installation::         Compiling and installing CL
* Naming Conventions::   Notes on CL function names
@end menu

@node Usage, Organization, Overview, Overview
@section Usage

Lisp code that uses features from the @dfn{CL} package should
include at the beginning:

(require 'cl)
@end example

If you want to ensure that the new (Gillespie) version of @dfn{CL}
is the one that is present, add an additional @code{(require 'cl-19)}

(require 'cl)
(require 'cl-19)
@end example

The second call will fail (with ``@file{cl-19.el} not found'') if
the old @file{cl.el} package was in use.

It is safe to arrange to load @dfn{CL} at all times, e.g.,
in your @file{.emacs} file.  But it's a good idea, for portability,
to @code{(require 'cl)} in your code even if you do this.

@node Organization, Installation, Usage, Overview
@section Organization

The Common Lisp package is organized into four files:

@table @file
@item cl.el
This is the ``main'' file, which contains basic functions
and information about the package.  This file is relatively
compact---about 700 lines.

@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
Lisp fundamentals like the @code{cadr} function won't need to pay
the overhead of loading the more advanced functions.

@item cl-seq.el
This file contains most of the advanced functions for operating
on sequences or lists, such as @code{delete-if} and @code{assoc*}.

@item cl-macs.el
This file contains the features of the packages which 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 such as a @file{.emacs} file).  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.
@end table

The file @file{cl.el} includes all necessary @code{autoload}
commands for the functions and macros in the other three files.
All you have to do is @code{(require 'cl)}, and @file{cl.el}
will take care of pulling in the other files when they are

There is another file, @file{cl-compat.el}, which defines some
routines from the older @file{cl.el} package that are no longer
present in the new package.  This includes internal routines
like @code{setelt} and @code{zip-lists}, deprecated features
like @code{defkeyword}, and an emulation of the old-style
multiple-values feature.  @xref{Old CL Compatibility}.

@node Installation, Naming Conventions, Organization, Overview
@section Installation

Installation of the @dfn{CL} package is simple:  Just put the
byte-compiled files @file{cl.elc}, @file{cl-extra.elc},
@file{cl-seq.elc}, @file{cl-macs.elc}, and @file{cl-compat.elc}
into a directory on your @code{load-path}.

There are no special requirements to compile this package:
The files do not have to be loaded before they are compiled,
nor do they need to be compiled in any particular order.

You may choose to put the files into your main @file{lisp/}
directory, replacing the original @file{cl.el} file there.  Or,
you could put them into a directory that comes before @file{lisp/}
on your @code{load-path} so that the old @file{cl.el} is
effectively hidden.

Also, format the @file{cl.texinfo} file and put the resulting
Info files in the @file{info/} directory or another suitable place.

You may instead wish to leave this package's components all in
their own directory, and then add this directory to your
@code{load-path} and @code{Info-directory-list}.
Dave Love's avatar
Dave Love committed
254 255 256
Add the directory to the front of the list so the old @dfn{CL}
package and its documentation are hidden.

@node Naming Conventions,  , Installation, Overview
Dave Love's avatar
Dave Love committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
@section Naming Conventions

Except where noted, all functions defined by this package have the
same names and calling conventions as their Common Lisp counterparts.

Following is a complete list of functions whose names were changed
from Common Lisp, usually to avoid conflicts with Emacs.  In each
case, a @samp{*} has been appended to the Common Lisp name to obtain
the Emacs name:

defun*        defsubst*     defmacro*     function*
member*       assoc*        rassoc*       get*
remove*       delete*       mapcar*       sort*
floor*        ceiling*      truncate*     round*
Dave Love's avatar
Dave Love committed
mod*          rem*          random*
Dave Love's avatar
Dave Love committed
275 276 277 278 279 280 281
@end example

Internal function and variable names in the package are prefixed
by @code{cl-}.  Here is a complete list of functions @emph{not}
prefixed by @code{cl-} which were not taken from Common Lisp:

floatp-safe   lexical-let   lexical-let*
Dave Love's avatar
Dave Love committed
callf         callf2        letf          letf*
Dave Love's avatar
Dave Love committed
285 286 287 288 289 290
@end example

The following simple functions and macros are defined in @file{cl.el};
they do not cause other components like @file{cl-extra} to be loaded.

eql           floatp-safe   endp
Dave Love's avatar
Dave Love committed
evenp         oddp          plusp         minusp
Dave Love's avatar
Dave Love committed
caaar .. cddddr
Dave Love's avatar
Dave Love committed
list*         ldiff         rest          first .. tenth
copy-list     subst         mapcar* [2]
Dave Love's avatar
Dave Love committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
adjoin [3]    acons         pairlis       pop [4]
push [4]      pushnew [3,4] incf [4]      decf [4]
proclaim      declaim
@end example

[2] Only for one sequence argument or two list arguments.

[3] Only if @code{:test} is @code{eq}, @code{equal}, or unspecified,
and @code{:key} is not used.

[4] Only when @var{place} is a plain variable name.

@end iftex

@node Program Structure, Predicates, Overview, Top
@chapter Program Structure

This section describes features of the @dfn{CL} package which have to
do with programs as a whole: advanced argument lists for functions,
and the @code{eval-when} construct.

* Argument Lists::       `&key', `&aux', `defun*', `defmacro*'.
* Time of Evaluation::   The `eval-when' construct.
@end menu

@end iftex

@node Argument Lists, Time of Evaluation, Program Structure, Program Structure
@section Argument Lists

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.

@defspec defun* name arglist body...
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}.
@end defspec

@defspec defsubst* name arglist body...
This is just like @code{defun*}, except that the function that
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;
Dave Love's avatar
Dave Love committed
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 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
@code{defsubst*} uses a different method (compiler macros) which
works in all version of Emacs, and also generates somewhat more
efficient inline expansions.  In particular, @code{defsubst*}
arranges for the processing of keyword arguments, default values,
etc., to be done at compile-time whenever possible.
@end defspec

@defspec defmacro* name arglist body...
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
described in Steele.  The @code{&whole} keyword is supported only
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
@end defspec

@defspec function* symbol-or-lambda
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.
@end defspec

Also, all forms (such as @code{defsetf} and @code{flet}) defined
in this package that include @var{arglist}s in their syntax allow
full Common Lisp argument lists.

Note that it is @emph{not} necessary to use @code{defun*} in
order to have access to most @dfn{CL} features in your function.
These features are always present; @code{defun*}'s only
difference from @code{defun} is its more flexible argument
lists and its implicit block.

The full form of a Common Lisp argument list is

 &optional (@var{var} @var{initform} @var{svar})...
 &rest @var{var}
 &key ((@var{keyword} @var{var}) @var{initform} @var{svar})...
 &aux (@var{var} @var{initform})...)
@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,

(defun* foo (a &optional b &key c d (e 17)))
@end example

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

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.

If a @var{keyword} symbol is explicitly specified in the argument
list as shown in the above diagram, then that keyword will be
used instead of just the variable name prefixed with a colon.
You can specify a @var{keyword} symbol which does not begin with
a colon at all, but such symbols will not be self-quoting; you
will have to quote them explicitly with an apostrophe in the
function call.

Ordinarily it is an error to pass an unrecognized keyword to
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:

(defun* find-thing (thing &rest rest &key need &allow-other-keys)
  (or (apply 'member* thing thing-list :allow-other-keys t rest)
      (if need (error "Thing not found"))))
@end smallexample

This function takes a @code{:need} keyword argument, but also
accepts other keyword arguments which are passed on to the
@code{member*} function.  @code{allow-other-keys} is used to
keep both @code{find-thing} and @code{member*} from complaining
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:

(defun* foo (a b &aux (c (+ a b)) d)

(defun* foo (a b)
  (let ((c (+ a b)) d)
@end example

Argument lists support @dfn{destructuring}.  In Common Lisp,
destructuring is only allowed with @code{defmacro}; this package
allows it with @code{defun*} and other argument lists as well.
In destructuring, any argument variable (@var{var} in the above
diagram) can be replaced by a list of variables, or more generally,
a recursive argument list.  The corresponding argument value must
be a list whose elements match this recursive argument list.
For example:

(defmacro* dolist ((var listform &optional resultform)
                   &rest body)
@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.

@node Time of Evaluation,  , Argument Lists, Program Structure
Dave Love's avatar
Dave Love committed
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
@section Time of Evaluation

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.

@defspec eval-when (situations...) forms...
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}).

The @code{eval-when} form is handled differently depending on
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}.

For compiled top-level @code{eval-when}s, the body @var{forms} are
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},
and non-top-level forms.)  The @code{eval-when} acts like a
@code{progn} if @code{eval} is specified, and like @code{nil}
(ignoring the body @var{forms}) if not.

The rules become more subtle when @code{eval-when}s are nested;
consult Steele (second edition) for the gruesome details (and
some gruesome examples).

Some simple examples:

;; Top-level forms in foo.el:
(eval-when (compile)           (setq foo1 'bar))
(eval-when (load)              (setq foo2 'bar))
(eval-when (compile load)      (setq foo3 'bar))
(eval-when (eval)              (setq foo4 'bar))
(eval-when (eval compile)      (setq foo5 'bar))
(eval-when (eval load)         (setq foo6 'bar))
(eval-when (eval compile load) (setq foo7 'bar))
@end example

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

foo1  foo3  foo5  foo7      ; `compile'
@end example

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

foo2  foo3  foo6  foo7      ; `load'
@end example

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

foo4  foo5  foo6  foo7      ; `eval'
@end example

If these seven @code{eval-when}s had been, say, inside a @code{defun},
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.

Note that @code{(eval-when (load eval) @dots{})} is equivalent
to @code{(progn @dots{})} in all contexts.  The compiler treats
certain top-level forms, like @code{defmacro} (sort-of) and
@code{require}, as if they were wrapped in @code{(eval-when
(compile load eval) @dots{})}.
@end defspec

Emacs includes two special forms related to @code{eval-when}.
Dave Love's avatar
Dave Love committed
One of these, @code{eval-when-compile}, is not quite equivalent to
any @code{eval-when} construct and is described below.
Dave Love's avatar
Dave Love committed
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834

The other form, @code{(eval-and-compile @dots{})}, is exactly
equivalent to @samp{(eval-when (compile load eval) @dots{})} and
so is not itself defined by this package.

@defspec eval-when-compile forms...
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.
@end defspec

@defspec load-time-value form
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.

In a compiled file, @code{load-time-value} arranges for @var{form}
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
code, both @code{eval-when-compile} and @code{load-time-value}
act exactly like @code{progn}.

(defun report ()
  (insert "This function was executed on: "
          ", compiled on: "
          (eval-when-compile (current-time-string))
          ;; or '#.(current-time-string) in real Common Lisp
          ", and loaded on: "
          (load-time-value (current-time-string))))
@end example

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

(setq --temp-- (current-time-string))
(defun report ()
  (insert "This function was executed on: "
          ", compiled on: "
          '"Wed Jun 23 18:33:43 1993"
          ", and loaded on: "
@end example
@end defspec

@node Predicates, Control Structure, Program Structure, Top
@chapter Predicates

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

* Type Predicates::      `typep', `deftype', and `coerce'
* Equality Predicates::  `eql' and `equalp'
@end menu

@node Type Predicates, Equality Predicates, Predicates, Predicates
@section Type Predicates

The @dfn{CL} package defines a version of the Common Lisp @code{typep}

@defun typep object type
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,
@code{(typep foo 'integer)} is equivalent to @code{(integerp foo)}.
@end defun

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

@itemize @bullet
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.)

The type symbol @code{t} stands for the union of all types.
@code{(typep @var{object} t)} is always true.  Likewise, the
type symbol @code{nil} stands for nothing at all, and
@code{(typep @var{object} nil)} is always false.

The type symbol @code{null} represents the symbol @code{nil}.
Thus @code{(typep @var{object} 'null)} is equivalent to
@code{(null @var{object})}.

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

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

The type symbol @code{float} uses the @code{floatp-safe} predicate
defined by this package rather than @code{floatp}, so it will work
correctly even in Emacs versions without floating-point support.

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}.

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

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.

Lists beginning with @code{member} or @code{member*} represent
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}.

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
related to @code{typep}.

@defun coerce object type
This function attempts to convert @var{object} to the specified
@var{type}.  If @var{object} is already of that type as determined by
@code{typep}, it is simply returned.  Otherwise, certain types of
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
floats.  In all other circumstances, @code{coerce} signals an
@end defun

@defspec deftype name arglist forms...
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
by @code{defmacro*}.  The type specifier @samp{(@var{name} @var{args}...)}
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
@code{defmacro*} except that optional arguments without explicit
defaults use @code{*} instead of @code{nil} as the ``default''
default.  Some examples:

(deftype null () '(satisfies null))    ; predefined
(deftype list () '(or null cons))      ; predefined
(deftype unsigned-byte (&optional bits)
  (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

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.
@end defspec

The @code{typecase} and @code{check-type} macros also use type
names.  @xref{Conditionals}.  @xref{Assertions}.  The @code{map},
@code{concatenate}, and @code{merge} functions take type-name
arguments to specify the type of sequence to return.  @xref{Sequences}.

@node Equality Predicates,  , Type Predicates, Predicates
Dave Love's avatar
Dave Love committed
836 837 838 839 840 841 842 843 844 845 846
@section Equality Predicates

This package defines two Common Lisp predicates, @code{eql} and

@defun eql a b
This function is almost the same as @code{eq}, except that if @var{a}
and @var{b} are numbers of the same type, it compares them for numeric
equality (as if by @code{equal} instead of @code{eq}).  This makes a
difference only for versions of Emacs that are compiled with
floating-point support.  Emacs floats are allocated
Dave Love's avatar
Dave Love committed
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
objects just like cons cells, which means that @code{(eq 3.0 3.0)}
will not necessarily be true---if the two @code{3.0}s were allocated
separately, the pointers will be different even though the numbers are
the same.  But @code{(eql 3.0 3.0)} will always be true.

The types of the arguments must match, so @code{(eql 3 3.0)} is
still false.

Note that Emacs integers are ``direct'' rather than allocated, which
basically means @code{(eq 3 3)} will always be true.  Thus @code{eq}
and @code{eql} behave differently only if floating-point numbers are
involved, and are indistinguishable on Emacs versions that don't
support floats.

There is a slight inconsistency with Common Lisp in the treatment of
positive and negative zeros.  Some machines, notably those with IEEE
standard arithmetic, represent @code{+0} and @code{-0} as distinct
values.  Normally this doesn't matter because the standard specifies
that @code{(= 0.0 -0.0)} should always be true, and this is indeed
what Emacs Lisp and Common Lisp do.  But the Common Lisp standard
states that @code{(eql 0.0 -0.0)} and @code{(equal 0.0 -0.0)} should
be false on IEEE-like machines; Emacs Lisp does not do this, and in
fact the only known way to distinguish between the two zeros in Emacs
Lisp is to @code{format} them and check for a minus sign.
@end defun

@defun equalp a b
This function is a more flexible version of @code{equal}.  In
particular, it compares strings case-insensitively, and it compares
numbers without regard to type (so that @code{(equalp 3 3.0)} is
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
vector-like in Emacs Lisp, this package's @code{equalp} also will
not compare strings against vectors of integers.
Dave Love's avatar
Dave Love committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
@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.
In Emacs, use @code{member*} and @code{assoc*} to get functions
which use @code{eql} for comparisons.

@node Control Structure, Macros, Predicates, Top
@chapter Control Structure

The features described in the following sections implement
various advanced control structures, including the powerful
@code{setf} facility and a number of looping and conditional

* Assignment::             The `psetq' form
* Generalized Variables::  `setf', `incf', `push', etc.
* Variable Bindings::      `progv', `lexical-let', `flet', `macrolet'
* Conditionals::           `case', `typecase'
* Blocks and Exits::       `block', `return', `return-from'
* Iteration::              `do', `dotimes', `dolist', `do-symbols'
Dave Love's avatar
Dave Love committed
912 913 914 915 916 917 918 919 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 945 946 947 948 949 950 951 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 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
* Loop Facility::          The Common Lisp `loop' macro
* Multiple Values::        `values', `multiple-value-bind', etc.
@end menu

@node Assignment, Generalized Variables, Control Structure, Control Structure
@section Assignment

The @code{psetq} form is just like @code{setq}, except that multiple
assignments are done in parallel rather than sequentially.

@defspec psetq [symbol form]@dots{}
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.

(setq x 2 y 3)
(setq x (+ x y)  y (* x y))
     @result{} 5
y                     ; @r{@code{y} was computed after @code{x} was set.}
     @result{} 15
(setq x 2 y 3)
(psetq x (+ x y)  y (* x y))
     @result{} 5
y                     ; @r{@code{y} was computed before @code{x} was set.}
     @result{} 6
@end example

The simplest use of @code{psetq} is @code{(psetq x y y x)}, which
exchanges the values of two variables.  (The @code{rotatef} form
provides an even more convenient way to swap two variables;
@pxref{Modify Macros}.)

@code{psetq} always returns @code{nil}.
@end defspec

@node Generalized Variables, Variable Bindings, Assignment, Control Structure
@section Generalized Variables

A ``generalized variable'' or ``place form'' is one of the many places
in Lisp memory where values can be stored.  The simplest place form is
a regular Lisp variable.  But the cars and cdrs of lists, elements
of arrays, properties of symbols, and many other locations are also
places where Lisp values are stored.

The @code{setf} form is like @code{setq}, except that it accepts
arbitrary place forms on the left side rather than just
symbols.  For example, @code{(setf (car a) b)} sets the car of
@code{a} to @code{b}, doing the same operation as @code{(setcar a b)}
but without having to remember two separate functions for setting
and accessing every type of place.

Generalized variables are analogous to ``lvalues'' in the C
language, where @samp{x = a[i]} gets an element from an array
and @samp{a[i] = x} stores an element using the same notation.
Just as certain forms like @code{a[i]} can be lvalues in C, there
is a set of forms that can be generalized variables in Lisp.

* Basic Setf::         `setf' and place forms
* Modify Macros::      `incf', `push', `rotatef', `letf', `callf', etc.
* Customizing Setf::   `define-modify-macro', `defsetf', `define-setf-method'
@end menu

@node Basic Setf, Modify Macros, Generalized Variables, Generalized Variables
@subsection Basic Setf

The @code{setf} macro is the most basic way to operate on generalized

@defspec setf [place form]@dots{}
This macro evaluates @var{form} and stores it in @var{place}, which
must be a valid generalized variable form.  If there are several
@var{place} and @var{form} pairs, the assignments are done sequentially
just as with @code{setq}.  @code{setf} returns the value of the last

The following Lisp forms will work as generalized variables, and
so may legally appear in the @var{place} argument of @code{setf}:

@itemize @bullet
A symbol naming a variable.  In other words, @code{(setf x y)} is
exactly equivalent to @code{(setq x y)}, and @code{setq} itself is
strictly speaking redundant now that @code{setf} exists.  Many
programmers continue to prefer @code{setq} for setting simple
variables, though, purely for stylistic or historical reasons.
The macro @code{(setf x y)} actually expands to @code{(setq x y)},
so there is no performance penalty for using it in compiled code.

A call to any of the following Lisp functions:

car                 cdr                 caar .. cddddr
nth                 rest                first .. tenth
aref                elt                 nthcdr
symbol-function     symbol-value        symbol-plist
get                 get*                getf
gethash             subseq
@end smallexample

Note that for @code{nthcdr} and @code{getf}, the list argument
of the function must itself be a valid @var{place} form.  For
example, @code{(setf (nthcdr 0 foo) 7)} will set @code{foo} itself
to 7.  Note that @code{push} and @code{pop} on an @code{nthcdr}
place can be used to insert or delete at any position in a list.
The use of @code{nthcdr} as a @var{place} form is an extension
to standard Common Lisp.

The following Emacs-specific functions are also @code{setf}-able.

buffer-file-name                  marker-position          
buffer-modified-p                 match-data               
buffer-name                       mouse-position           
buffer-string                     overlay-end              
buffer-substring                  overlay-get              
current-buffer                    overlay-start            
current-case-table                point                    
current-column                    point-marker             
current-global-map                point-max                
current-input-mode                point-min                
current-local-map                 process-buffer           
current-window-configuration      process-filter           
default-file-modes                process-sentinel         
default-value                     read-mouse-position      
documentation-property            screen-height            
extent-data                       screen-menubar           
extent-end-position               screen-width             
extent-start-position             selected-window          
face-background                   selected-screen          
face-background-pixmap            selected-frame           
face-font                         standard-case-table      
face-foreground                   syntax-table             
face-underline-p                  window-buffer            
file-modes                        window-dedicated-p       
frame-height                      window-display-table     
frame-parameters                  window-height            
frame-visible-p                   window-hscroll           
frame-width                       window-point             
get-register                      window-start             
getenv                            window-width             
global-key-binding                x-get-cut-buffer         
keymap-parent                     x-get-cutbuffer          
local-key-binding                 x-get-secondary-selection
mark                              x-get-selection          
@end smallexample

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
sequences of code when they are @code{setf}'d (@code{(narrow-to-region
x (point-max))} in this case).

A call of the form @code{(substring @var{subplace} @var{n} [@var{m}])},
where @var{subplace} is itself a legal 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:

(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"
     @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.

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}.

A macro call, in which case the macro is expanded and @code{setf}
is applied to the resulting form.

Any form for which a @code{defsetf} or @code{define-setf-method}
has been made.
@end itemize

Using any forms other than these in the @var{place} argument to
@code{setf} will signal an error.

The @code{setf} macro takes care to evaluate all subforms in
the proper left-to-right order; for example,

(setf (aref vec (incf i)) i)
@end example

looks like it will evaluate @code{(incf i)} exactly once, before the
following access to @code{i}; the @code{setf} expander will insert
temporary variables as necessary to ensure that it does in fact work
this way no matter what setf-method is defined for @code{aref}.
(In this case, @code{aset} would be used and no such steps would
be necessary since @code{aset} takes its arguments in a convenient

However, if the @var{place} form is a macro which explicitly
evaluates its arguments in an unusual order, this unusual order
will be preserved.  Adapting an example from Steele, given

(defmacro wrong-order (x y) (list 'aref y x))
@end example

the form @code{(setf (wrong-order @var{a} @var{b}) 17)} will
evaluate @var{b} first, then @var{a}, just as in an actual call
to @code{wrong-order}.
@end defspec

@node Modify Macros, Customizing Setf, Basic Setf, Generalized Variables
@subsection Modify Macros

This package defines a number of other macros besides @code{setf}
that operate on generalized variables.  Many are interesting and
useful even when the @var{place} is just a variable name.

@defspec psetf [place form]@dots{}
This macro is to @code{setf} what @code{psetq} is to @code{setq}:
When several @var{place}s and @var{form}s are involved, the
assignments take place in parallel rather than sequentially.
Specifically, all subforms are evaluated from left to right, then
all the assignments are done (in an undefined order).
@end defspec

@defspec incf place &optional x
This macro increments the number stored in @var{place} by one, or
by @var{x} if specified.  The incremented value is returned.  For
example, @code{(incf i)} is equivalent to @code{(setq i (1+ i))}, and
@code{(incf (car x) 2)} is equivalent to @code{(setcar x (+ (car x) 2))}.

Once again, care is taken to preserve the ``apparent'' order of
evaluation.  For example,

(incf (aref vec (incf i)))
@end example

appears to increment @code{i} once, then increment the element of
@code{vec} addressed by @code{i}; this is indeed exactly what it
does, which means the above form is @emph{not} equivalent to the
``obvious'' expansion,

(setf (aref vec (incf i)) (1+ (aref vec (incf i))))   ; Wrong!
@end example

but rather to something more like

(let ((temp (incf i)))
  (setf (aref vec temp) (1+ (aref vec temp))))
@end example

Again, all of this is taken care of automatically by @code{incf} and
the other generalized-variable macros.

As a more Emacs-specific example of @code{incf}, the expression
@code{(incf (point) @var{n})} is essentially equivalent to
@code{(forward-char @var{n})}.
@end defspec

@defspec decf place &optional x
This macro decrements the number stored in @var{place} by one, or
by @var{x} if specified.
@end defspec

@defspec pop place
This macro removes and returns the first element of the list stored
in @var{place}.  It is analogous to @code{(prog1 (car @var{place})
(setf @var{place} (cdr @var{place})))}, except that it takes care
to evaluate all subforms only once.
@end defspec

@defspec push x place
This macro inserts @var{x} at the front of the list stored in
@var{place}.  It is analogous to @code{(setf @var{place} (cons
@var{x} @var{place}))}, except for evaluation of the subforms.
@end defspec

@defspec pushnew x place @t{&key :test :test-not :key}
This macro inserts @var{x} at the front of the list stored in
@var{place}, but only if @var{x} was not @code{eql} to any
existing element of the list.  The optional keyword arguments
are interpreted in the same way as for @code{adjoin}.
@xref{Lists as Sets}.
@end defspec

@defspec shiftf place@dots{} newvalue
This macro shifts the @var{place}s left by one, shifting in the
value of @var{newvalue} (which may be any Lisp expression, not just
a generalized variable), and returning the value shifted out of
the first @var{place}.  Thus, @code{(shiftf @var{a} @var{b} @var{c}
@var{d})} is equivalent to

  (psetf @var{a} @var{b}
         @var{b} @var{c}
         @var{c} @var{d}))
@end example

except that the subforms of @var{a}, @var{b}, and @var{c} are actually
evaluated only once each and in the apparent order.
@end defspec

@defspec rotatef place@dots{}
This macro rotates the @var{place}s left by one in circular fashion.
Thus, @code{(rotatef @var{a} @var{b} @var{c} @var{d})} is equivalent to

(psetf @var{a} @var{b}
       @var{b} @var{c}
       @var{c} @var{d}
       @var{d} @var{a})
@end example

except for the evaluation of subforms.  @code{rotatef} always
returns @code{nil}.  Note that @code{(rotatef @var{a} @var{b})}
conveniently exchanges @var{a} and @var{b}.
@end defspec

The following macros were invented for this package; they have no
analogues in Common Lisp.

@defspec letf (bindings@dots{}) forms@dots{}
This macro is analogous to @code{let}, but for generalized variables
rather than just symbols.  Each @var{binding} should be of the form
@code{(@var{place} @var{value})}; the original contents of the
@var{place}s are saved, the @var{value}s are stored in them, and
then the body @var{form}s are executed.  Afterwards, the @var{places}
are set back to their original saved contents.  This cleanup happens
even if the @var{form}s exit irregularly due to a @code{throw} or an

For example,

(letf (((point) (point-min))
       (a 17))
@end example

moves ``point'' in the current buffer to the beginning of the buffer,
and also binds @code{a} to 17 (as if by a normal @code{let}, since
@code{a} is just a regular variable).  After the body exits, @code{a}
is set back to its original value and point is moved back to its
original position.

Note that @code{letf} on @code{(point)} is not quite like a
@code{save-excursion}, as the latter effectively saves a marker
which tracks insertions and deletions in the buffer.  Actually,
a @code{letf} of @code{(point-marker)} is much closer to this
behavior.  (@code{point} and @code{point-marker} are equivalent
as @code{setf} places; each will accept either an integer or a
marker as the stored value.)

Since generalized variables look like lists, @code{let}'s shorthand
of using @samp{foo} for @samp{(foo nil)} as a @var{binding} would
be ambiguous in @code{letf} and is not allowed.

However, a @var{binding} specifier may be a one-element list
@samp{(@var{place})}, which is similar to @samp{(@var{place}
@var{place})}.  In other words, the @var{place} is not disturbed
on entry to the body, and the only effect of the @code{letf} is
to restore the original value of @var{place} afterwards.  (The
redundant access-and-store suggested by the @code{(@var{place}
@var{place})} example does not actually occur.)

In most cases, the @var{place} must have a well-defined value on
entry to the @code{letf} form.  The only exceptions are plain
variables and calls to @code{symbol-value} and @code{symbol-function}.
If the symbol is not bound on entry, it is simply made unbound by
@code{makunbound} or @code{fmakunbound} on exit.
@end defspec

@defspec letf* (bindings@dots{}) forms@dots{}
This macro is to @code{letf} what @code{let*} is to @code{let}:
It does the bindings in sequential rather than parallel order.
@end defspec

@defspec callf @var{function} @var{place} @var{args}@dots{}
This is the ``generic'' modify macro.  It calls @var{function},
which should be an unquoted function name, macro name, or lambda.
It passes @var{place} and @var{args} as arguments, and assigns the
result back to @var{place}.  For example, @code{(incf @var{place}
@var{n})} is the same as @code{(callf + @var{place} @var{n})}.
Some more examples:

(callf abs my-number)
(callf concat (buffer-name) "<" (int-to-string n) ">")
(callf union happy-people (list joe bob) :test 'same-person)
@end example

@xref{Customizing Setf}, for @code{define-modify-macro}, a way
to create even more concise notations for modify macros.  Note
again that @code{callf} is an extension to standard Common Lisp.
@end defspec

@defspec callf2 @var{function} @var{arg1} @var{place} @var{args}@dots{}
This macro is like @code{callf}, except that @var{place} is
the @emph{second} argument of @var{function} rather than the
first.  For example, @code{(push @var{x} @var{place})} is
equivalent to @code{(callf2 cons @var{x} @var{place})}.
@end defspec

The @code{callf} and @code{callf2} macros serve as building
blocks for other macros like @code{incf}, @code{pushnew}, and
@code{define-modify-macro}.  The @code{letf} and @code{letf*}
macros are used in the processing of symbol macros;
@pxref{Macro Bindings}.

@node Customizing Setf,  , Modify Macros, Generalized Variables
Dave Love's avatar
Dave Love committed
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
@subsection Customizing Setf

Common Lisp defines three macros, @code{define-modify-macro},
@code{defsetf}, and @code{define-setf-method}, that allow the
user to extend generalized variables in various ways.

@defspec define-modify-macro name arglist function [doc-string]
This macro defines a ``read-modify-write'' macro similar to
@code{incf} and @code{decf}.  The macro @var{name} is defined
to take a @var{place} argument followed by additional arguments
described by @var{arglist}.  The call

(@var{name} @var{place} @var{args}...)
@end example

will be expanded to

(callf @var{func} @var{place} @var{args}...)
@end example

which in turn is roughly equivalent to

(setf @var{place} (@var{func} @var{place} @var{args}...))
@end example

For example:

(define-modify-macro incf (&optional (n 1)) +)
(define-modify-macro concatf (&rest args) concat)
@end example

Note that @code{&key} is not allowed in @var{arglist}, but
@code{&rest} is sufficient to pass keywords on to the function.

Most of the modify macros defined by Common Lisp do not exactly
follow the pattern of @code{define-modify-macro}.  For example,
@code{push} takes its arguments in the wrong order, and @code{pop}
is completely irregular.  You can define these macros ``by hand''
using @code{get-setf-method}, or consult the source file
@file{cl-macs.el} to see how to use the internal @code{setf}
building blocks.
@end defspec

@defspec defsetf access-fn update-fn
This is the simpler of two @code{defsetf} forms.  Where
@var{access-fn} is the name of a function which accesses a place,
this declares @var{update-fn} to be the corresponding store
function.  From now on,

(setf (@var{access-fn} @var{arg1} @var{arg2} @var{arg3}) @var{value})
@end example

will be expanded to

(@var{update-fn} @var{arg1} @var{arg2} @var{arg3} @var{value})
@end example

The @var{update-fn} is required to be either a true function, or
a macro which evaluates its arguments in a function-like way.  Also,
the @var{update-fn} is expected to return @var{value} as its result.
Otherwise, the above expansion would not obey the rules for the way
@code{setf} is supposed to behave.

As a special (non-Common-Lisp) extension, a third argument of @code{t}
to @code{defsetf} says that the @code{update-fn}'s return value is
not suitable, so that the above @code{setf} should be expanded to
something more like

(let ((temp @var{value}))
  (@var{update-fn} @var{arg1} @var{arg2} @var{arg3} temp)
@end example

Some examples of the use of @code{defsetf}, drawn from the standard
suite of setf methods, are:

(defsetf car setcar)
(defsetf symbol-value set)
(defsetf buffer-name rename-buffer t)
@end example
@end defspec

@defspec defsetf access-fn arglist (store-var) forms@dots{}
This is the second, more complex, form of @code{defsetf}.  It is
rather like @code{defmacro} except for the additional @var{store-var}
argument.  The @var{forms} should return a Lisp form which stores
the value of @var{store-var} into the generalized variable formed
by a call to @var{access-fn} with arguments described by @var{arglist}.
The @var{forms} may begin with a string which documents the @code{setf}
method (analogous to the doc string that appears at the front of a

For example, the simple form of @code{defsetf} is shorthand for

(defsetf @var{access-fn} (&rest args) (store)
  (append '(@var{update-fn}) args (list store)))
@end example

The Lisp form that is returned can access the arguments from
@var{arglist} and @var{store-var} in an unrestricted fashion;
macros like @code{setf} and @code{incf} which invoke this
setf-method will insert temporary variables as needed to make
sure the apparent order of evaluation is preserved.

Another example drawn from the standard package:

(defsetf nth (n x) (store)
  (list 'setcar (list 'nthcdr n x) store))
@end example
@end defspec

@defspec define-setf-method access-fn arglist forms@dots{}
This is the most general way to create new place forms.  When
a @code{setf} to @var{access-fn} with arguments described by
@var{arglist} is expanded, the @var{forms} are evaluated and
must return a list of five items:

A list of @dfn{temporary variables}.

A list of @dfn{value forms} corresponding to the temporary variables
above.  The temporary variables will be bound to these value forms
as the first step of any operation on the generalized variable.

A list of exactly one @dfn{store variable} (generally obtained
from a call to @code{gensym}).

A Lisp form which stores the contents of the store variable into
the generalized variable, assuming the temporaries have been
bound as described above.

A Lisp form which accesses the contents of the generalized variable,
assuming the temporaries have been bound.
@end enumerate

This is exactly like the Common Lisp macro of the same name,
except that the method returns a list of five values rather
than the five values themselves, since Emacs Lisp does not
support Common Lisp's notion of multiple return values.

Once again, the @var{forms} may begin with a documentation string.

A setf-method should be maximally conservative with regard to
temporary variables.  In the setf-methods generated by
@code{defsetf}, the second return value is simply the list of
arguments in the place form, and the first return value is a
list of a corresponding number of temporary variables generated
by @code{gensym}.  Macros like @code{setf} and @code{incf} which
use this setf-method will optimize away most temporaries that
turn out to be unnecessary, so there is little reason for the
setf-method itself to optimize.
@end defspec

@defun get-setf-method place &optional env
This function returns the setf-method for @var{place}, by
invoking the definition previously recorded by @code{defsetf}
or @code{define-setf-method}.  The result is a list of five
values as described above.  You can use this function to build
your own @code{incf}-like modify macros.  (Actually, it is
better to use the internal functions @code{cl-setf-do-modify}
and @code{cl-setf-do-store}, which are a bit easier to use and
which also do a number of optimizations; consult the source
code for the @code{incf} function for a simple example.)

The argument @var{env} specifies the ``environment'' to be
passed on to @code{macroexpand} if @code{get-setf-method} should
need to expand a macro in @var{place}.  It should come from
an @code{&environment} argument to the macro or setf-method
that called @code{get-setf-method}.

See also the source code for the setf-methods for @code{apply}
and @code{substring}, each of which works by calling
@code{get-setf-method} on a simpler case, then massaging
the result in various ways.
@end defun

Modern Common Lisp defines a second, independent way to specify
the @code{setf} behavior of a function, namely ``@code{setf}
functions'' whose names are lists @code{(setf @var{name})}
rather than symbols.  For example, @code{(defun (setf foo) @dots{})}
defines the function that is used when @code{setf} is applied to
@code{foo}.  This package does not currently support @code{setf}
functions.  In particular, it is a compile-time error to use
@code{setf} on a form which has not already been @code{defsetf}'d
or otherwise declared; in newer Common Lisps, this would not be
an error since the function @code{(setf @var{func})} might be
defined later.

@end iftex

@node Variable Bindings, Conditionals, Generalized Variables, Control Structure
@section Variable Bindings

These Lisp forms make bindings to variables and function names,
analogous to Lisp's built-in @code{let} form.

@xref{Modify Macros}, for the @code{letf} and @code{letf*} forms which
are also related to variable bindings.

* Dynamic Bindings::     The `progv' form
* Lexical Bindings::     `lexical-let' and lexical closures
* Function Bindings::    `flet' and `labels'
* Macro Bindings::       `macrolet' and `symbol-macrolet'
@end menu

@node Dynamic Bindings, Lexical Bindings, Variable Bindings, Variable Bindings
@subsection Dynamic Bindings

The standard @code{let} form binds variables whose names are known
at compile-time.  The @code{progv} form provides an easy way to
bind variables whose names are computed at run-time.

@defspec progv symbols values forms@dots{}
This form establishes @code{let}-style variable bindings on a
set of variables computed at run-time.  The expressions
@var{symbols} and @var{values} are evaluated, and must return lists
of symbols and values, respectively.  The symbols are bound to the
corresponding values for the duration of the body @var{form}s.
If @var{values} is shorter than @var{symbols}, the last few symbols
are made unbound (as if by @code{makunbound}) inside the body.
If @var{symbols} is shorter than @var{values}, the excess values
are ignored.
@end defspec

@node Lexical Bindings, Function Bindings, Dynamic Bindings, Variable Bindings
@subsection Lexical Bindings

The @dfn{CL} package defines the following macro which
more closely follows the Common Lisp @code{let} form:

@defspec lexical-let (bindings@dots{}) forms@dots{}
This form is exactly like @code{let} except that the bindings it
establishes are purely lexical.  Lexical bindings are similar to
local variables in a language like C:  Only the code physically
within the body of the @code{lexical-let} (after macro expansion)
may refer to the bound variables.

(setq a 5)
(defun foo (b) (+ a b))
(let ((a 2)) (foo a))
     @result{} 4
(lexical-let ((a 2)) (foo a))
     @result{} 7
@end example

In this example, a regular @code{let} binding of @code{a} actually
makes a temporary change to the global variable @code{a}, so @code{foo}
is able to see the binding of @code{a} to 2.  But @code{lexical-let}
actually creates a distinct local variable @code{a} for use within its
body, without any effect on the global variable of the same name.

The most important use of lexical bindings is to create @dfn{closures}.
A closure is a function object that refers to an outside lexical
variable.  For example:

(defun make-adder (n)
  (lexical-let ((n n))
    (function (lambda (m) (+ n m)))))
(setq add17 (make-adder 17))
(funcall add17 4)
     @result{} 21
@end example

The call @code{(make-adder 17)} returns a function object which adds
17 to its argument.  If @code{let} had been used instead of
@code{lexical-let}, the function object would have referred to the
global @code{n}, which would have been bound to 17 only during the
call to @code{make-adder} itself.

(defun make-counter ()
  (lexical-let ((n 0))
    (function* (lambda (&optional (m 1)) (incf n m)))))
(setq count-1 (make-counter))
(funcall count-1 3)
     @result{} 3
(funcall count-1 14)
     @result{} 17
(setq count-2 (make-counter))
(funcall count-2 5)
     @result{} 5
(funcall count-1 2)
     @result{} 19
(funcall count-2)
     @result{} 6
@end example

Here we see that each call to @code{make-counter} creates a distinct
local variable @code{n}, which serves as a private counter for the
function object that is returned.

Closed-over lexical variables persist until the last reference to
them goes away, just like all other Lisp objects.  For example,
@code{count-2} refers to a function object which refers to an
instance of the variable @code{n}; this is the only reference
to that variable, so after @code{(setq count-2 nil)} the garbage
collector would be able to delete this instance of @code{n}.
Of course, if a @code{lexical-let} does not actually create any
closures, then the lexical variables are free as soon as the
@code{lexical-let} returns.

Many closures are used only during the extent of the bindings they
refer to; these are known as ``downward funargs'' in Lisp parlance.
When a closure is used in this way, regular Emacs Lisp dynamic
bindings suffice and will be more efficient than @code{lexical-let}

(defun add-to-list (x list)
  (mapcar (lambda (y) (+ x y))) list)
Dave Love's avatar
Dave Love committed
1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
(add-to-list 7 '(1 2 5))
     @result{} (8 9 12)
@end example

Since this lambda is only used while @code{x} is still bound,
it is not necessary to make a true closure out of it.

You can use @code{defun} or @code{flet} inside a @code{lexical-let}
to create a named closure.  If several closures are created in the
body of a single @code{lexical-let}, they all close over the same
instance of the lexical variable.

The @code{lexical-let} form is an extension to Common Lisp.  In
true Common Lisp, all bindings are lexical unless declared otherwise.
@end defspec

@defspec lexical-let* (bindings@dots{}) forms@dots{}
This form is just like @code{lexical-let}, except that the bindings
are made sequentially in the manner of @code{let*}.
@end defspec

@node Function Bindings, Macro Bindings, Lexical Bindings, Variable Bindings
@subsection Function Bindings

These forms make @code{let}-like bindings to functions instead
of variables.

@defspec flet (bindings@dots{}) forms@dots{}
This form establishes @code{let}-style bindings on the function
cells of symbols rather than on the value cells.  Each @var{binding}
must be a list of the form @samp{(@var{name} @var{arglist}
@var{forms}@dots{})}, which defines a function exactly as if
it were a @code{defun*} form.  The function @var{name} is defined
accordingly for the duration of the body of the @code{flet}; then
the old function definition, or lack thereof, is restored.

While @code{flet} in Common Lisp establishes a lexical binding of
@var{name}, Emacs Lisp @code{flet} makes a dynamic binding.  The
result is that @code{flet} affects indirect calls to a function as
well as calls directly inside the @code{flet} form itself.

You can use @code{flet} to disable or modify the behavior of a
function in a temporary fashion.  This will even work on Emacs
primitives, although note that some calls to primitive functions
internal to Emacs are made without going through the symbol's
function cell, and so will not be affected by @code{flet}.  For

(flet ((message (&rest args) (push args saved-msgs)))
@end example

This code attempts to replace the built-in function @code{message}
with a function that simply saves the messages in a list rather
than displaying them.  The original definition of @code{message}
will be restored after @code{do-something} exits.  This code will
work fine on messages generated by other Lisp code, but messages
generated directly inside Emacs will not be caught since they make
direct C-language calls to the message routines rather than going
through the Lisp @code{message} function.

Functions defined by @code{flet} may use the full Common Lisp
argument notation supported by @code{defun*}; also, the function
body is enclosed in an implicit block as if by @code{defun*}.
@xref{Program Structure}.
@end defspec

@defspec labels (bindings@dots{}) forms@dots{}
The @code{labels} form is like @code{flet}, except that it
makes lexical bindings of the function names rather than
dynamic bindings.  (In true Common Lisp, both @code{flet} and
@code{labels} make lexical bindings of slightly different sorts;
since Emacs Lisp is dynamically bound by default, it seemed
more appropriate for @code{flet} also to use dynamic binding.
The @code{labels} form, with its lexical binding, is fully
compatible with Common Lisp.)

Lexical scoping means that all references to the named
functions must appear physically within the body of the
@code{labels} form.  References may appear both in the body
@var{forms} of @code{labels} itself, and in the bodies of
the functions themselves.  Thus, @code{labels} can define
local recursive functions, or mutually-recursive sets of

A ``reference'' to a function name is either a call to that
function, or a use of its name quoted by @code{quote} or
@code{function} to be passed on to, say, @code{mapcar}.
@end defspec

@node Macro Bindings,  , Function Bindings, Variable Bindings
Dave Love's avatar
Dave Love committed
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
@subsection Macro Bindings

These forms create local macros and ``symbol macros.''

@defspec macrolet (bindings@dots{}) forms@dots{}
This form is analogous to @code{flet}, but for macros instead of
functions.  Each @var{binding} is a list of the same form as the
arguments to @code{defmacro*} (i.e., a macro name, argument list,
and macro-expander forms).  The macro is defined accordingly for
use within the body of the @code{macrolet}.

Because of the nature of macros, @code{macrolet} is lexically
scoped even in Emacs Lisp:  The @code{macrolet} binding will
affect only calls that appear physically within the body
@var{forms}, possibly after expansion of other macros in the
@end defspec

@defspec symbol-macrolet (bindings@dots{}) forms@dots{}
This form creates @dfn{symbol macros}, which are macros that look
like variable references rather than function calls.  Each
@var{binding} is a list @samp{(@var{var} @var{expansion})};
any reference to @var{var} within the body @var{forms} is
replaced by @var{expansion}.

(setq bar '(5 . 9))
(symbol-macrolet ((foo (car bar)))
  (incf foo))
     @result{} (6 . 9)
@end example

A @code{setq} of a symbol macro is treated the same as a @code{setf}.
I.e., @code{(setq foo 4)} in the above would be equivalent to
@code{(setf foo 4)}, which in turn expands to @code{(setf (car bar) 4)}.

Likewise, a @code{let} or @code{let*} binding a symbol macro is
treated like a @code{letf} or @code{letf*}.  This differs from true
Common Lisp, where the rules of lexical scoping cause a @code{let}
binding to shadow a @code{symbol-macrolet} binding.  In this package,
only @code{lexical-let} and @code{lexical-let*} will shadow a symbol

There is no analogue of @code{defmacro} for symbol macros; all symbol
macros are local.  A typical use of @code{symbol-macrolet} is in the
expansion of another macro:

(defmacro* my-dolist ((x list) &rest body)
  (let ((var (gensym)))
    (list 'loop 'for var 'on list 'do
          (list* 'symbol-macrolet (list (list x (list 'car var)))

(setq mylist '(1 2 3 4))
(my-dolist (x mylist) (incf x))
     @result{} (2 3 4 5)
@end example

In this example, the @code{my-dolist} macro is similar to @code{dolist}
(@pxref{Iteration}) except that the variable @code{x} becomes a true
Dave Love's avatar
Dave Love committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
reference onto the elements of the list.  The @code{my-dolist} call
shown here expands to

(loop for G1234 on mylist do
      (symbol-macrolet ((x (car G1234)))
        (incf x)))
@end example

which in turn expands to

(loop for G1234 on mylist do (incf (car G1234)))
@end example

@xref{Loop Facility}, for a description of the @code{loop} macro.
This package defines a nonstandard @code{in-ref} loop clause that
works much like @code{my-dolist}.
@end defspec

@node Conditionals, Blocks and Exits, Variable Bindings, Control Structure
@section Conditionals

These conditional forms augment Emacs Lisp's simple @code{if},
@code{and}, @code{or}, and @code{cond} forms.

@defspec case keyform clause@dots{}
This macro evaluates @var{keyform}, then compares it with the key
values listed in the various @var{clause}s.  Whichever clause matches
the key is executed; comparison is done by @code{eql}.  If no clause
matches, the @code{case} form returns @code{nil}.  The clauses are
of the form

(@var{keylist} @var{body-forms}@dots{})
@end example

where @var{keylist} is a list of key values.  If there is exactly
one value, and it is not a cons cell or the symbol @code{nil} or
@code{t}, then it can be used by itself as a @var{keylist} without
being enclosed in a list.  All key values in the @code{case} form
must be distinct.  The final clauses may use @code{t} in place of
a @var{keylist} to indicate a default clause that should be taken
if none of the other clauses match.  (The symbol @code{otherwise}
is also recognized in place of @code{t}.  To make a clause that
matches the actual symbol @code{t}, @code{nil}, or @code{otherwise},
enclose the symbol in a list.)

For example, this expression reads a keystroke, then does one of
four things depending on whether it is an @samp{a}, a @samp{b},
a @key{RET} or @kbd{C-j}, or anything else.

(case (read-char)
  (?a (do-a-thing))
  (?b (do-b-thing))
  ((?\r ?\n) (do-ret-thing))
  (t (do-other-thing)))
@end example
@end defspec

@defspec ecase keyform clause@dots{}
This macro is just like @code{case}, except that if the key does
not match any of the clauses, an error is signaled rather than
simply returning @code{nil}.
@end defspec

@defspec typecase keyform clause@dots{}
This macro is a version of @code{case} that checks for types
rather than values.  Each @var{clause} is of the form
@samp{(@var{type} @var{body}...)}.  @xref{Type Predicates},
for a description of type specifiers.  For example,

(typecase x
  (integer (munch-integer x))
  (float (munch-float x))
  (string (munch-integer (string-to-int x)))
  (t (munch-anything x)))
@end example

The type specifier @code{t} matches any type of object; the word
@code{otherwise} is also allowed.  To make one clause match any of
several types, use an @code{(or ...)} type specifier.
@end defspec

@defspec etypecase keyform clause@dots{}
This macro is just like @code{typecase}, except that if the key does
not match any of the clauses, an error is signaled rather than
simply returning @code{nil}.
@end defspec

@node Blocks and Exits, Iteration, Conditionals, Control Structure
@section Blocks and Exits

Common Lisp @dfn{blocks} provide a non-local exit mechanism very
similar to @code{catch} and @code{throw}, but lexically rather than
dynamically scoped.  This package actually implements @code{block}
in terms of @code{catch}; however, the lexical scoping allows the
optimizing byte-compiler to omit the costly @code{catch} step if the
body of the block does not actually @code{return-from} the block.

@defspec block name forms@dots{}
The @var{forms} are evaluated as if by a @code{progn}.  However,
if any of the @var{forms} execute @code{(return-from @var{name})},
they will jump out and return directly from the @code{block} form.
The @code{block} returns the result of the last @var{form} unless
a @code{return-from} occurs.

The @code{block}/@code{return-from} mechanism is quite similar to
the @code{catch}/@code{throw} mechanism.  The main differences are
that block @var{name}s are unevaluated symbols, rather than forms
(such as quoted symbols) which evaluate to a tag at run-time; and
also that blocks are lexically scoped whereas @code{catch}/@code{throw}
are dynamically scoped.  This means that functions called from the
body of a @code{catch} can also @code{throw} to the @code{catch},
but the @code{return-from} referring to a block name must appear
physically within the @var{forms} that make up the body of the block.
They may not appear within other called functions, although they may
appear within macro expansions or @code{lambda}s in the body.  Block
names and @code{catch} names form independent name-spaces.

In true Common Lisp, @code{defun} and @code{defmacro} surround
the function or expander bodies with implicit blocks with the
same name as the function or macro.  This does not occur in Emacs
Lisp, but this package provides @code{defun*} and @code{defmacro*}
forms which do create the implicit block.

The Common Lisp looping constructs defined by this package,
such as @code{loop} and @code{dolist}, also create implicit blocks
Dave Love's avatar
Dave Love committed
1999 2000 2001 2002 2003
just as in Common Lisp.

Because they are implemented in terms of Emacs Lisp @code{catch}
and @code{throw}, blocks have the same overhead as actual
@code{catch} constructs (roughly two function calls).  However,
2004 2005
the optimizing byte compiler will optimize away the @code{catch} 
if the block does
Dave Love's avatar
Dave Love committed
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
not in fact contain any @code{return} or @code{return-from} calls
that jump to it.  This means that @code{do} loops and @code{defun*}
functions which don't use @code{return} don't pay the overhead to
support it.
@end defspec

@defspec return-from name [result]
This macro returns from the block named @var{name}, which must be
an (unevaluated) symbol.  If a @var{result} form is specified, it
is evaluated to produce the result returned from the @code{block}.
Otherwise, @code{nil} is returned.
@end defspec

@defspec return [result]
This macro is exactly like @code{(return-from nil @var{result})}.
Common Lisp loops like @code{do} and @code{dolist} implicitly enclose
Dave Love's avatar
Dave Love committed
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
themselves in @code{nil} blocks.
@end defspec

@node Iteration, Loop Facility, Blocks and Exits, Control Structure
@section Iteration

The macros described here provide more sophisticated, high-level
looping constructs to complement Emacs Lisp's basic @code{while}

@defspec loop forms@dots{}
The @dfn{CL} package supports both the simple, old-style meaning of
@code{loop} and the extremely powerful and flexible feature known as
the @dfn{Loop Facility} or @dfn{Loop Macro}.  This more advanced
facility is discussed in the following section; @pxref{Loop Facility}.
The simple form of @code{loop} is described here.

If @code{loop} is followed by zero or more Lisp expressions,
then @code{(loop @var{exprs}@dots{})} simply creates an infinite
loop executing the expressions over and over.  The loop is
enclosed in an implicit @code{nil} block.  Thus,

(loop (foo)  (if (no-more) (return 72))  (bar))
@end example

is exactly equivalent to

(block nil (while t (foo)  (if (no-more) (return 72))  (bar)))
@end example

If any of the expressions are plain symbols, the loop is instead
interpreted as a Loop Macro specification as described later.
(This is not a restriction in practice, since a plain symbol
in the above notation would simply access and throw away the
value of a variable.)
@end defspec

@defspec do (spec@dots{}) (end-test [result@dots{}]) forms@dots{}
This macro creates a general iterative loop.  Each @var{spec} is
of the form

(@var{var} [@var{init} [@var{step}]])
@end example

The loop works as follows:  First, each @var{var} is bound to the
associated @var{init} value as if by a @code{let} form.  Then, in
each iteration of the loop, the @var{end-test} is evaluated; if
true, the loop is finished.  Otherwise, the body @var{forms} are
evaluated, then each @var{var} is set to the associated @var{step}
expression (as if by a @code{psetq} form) and the next iteration
begins.  Once the @var{end-test} becomes true, the @var{result}
forms are evaluated (with the @var{var}s still bound to their
values) to produce the result returned by @code{do}.

The entire @code{do} loop is enclosed in an implicit @code{nil}
block, so that you can use @code{(return)} to break out of the
loop at any time.

If there are no @var{result} forms, the loop returns @code{nil}.
If a given @var{var} has no @var{step} form, it is bound to its
@var{init} value but not otherwise modified during the @code{do}
loop (unless the code explicitly modifies it); this case is just
a shorthand for putting a @code{(let ((@var{var} @var{init})) @dots{})}
around the loop.  If @var{init} is also omitted it defaults to
@code{nil}, and in this case a plain @samp{@var{var}} can be used
in place of @samp{(@var{var})}, again following the analogy with

This example (from Steele) illustrates a loop which applies the
function @code{f} to successive pairs of values from the lists
@code{foo} and @code{bar}; it is equivalent to the call
@code{(mapcar* 'f foo bar)}.  Note that this loop has no body
@var{forms} at all, performing all its work as side effects of
the rest of the loop.

(do ((x foo (cdr x))
     (y bar (cdr y))
     (z nil (cons (f (car x) (car y)) z)))
  ((or (null x) (null y))
   (nreverse z)))
@end example
@end defspec

@defspec do* (spec@dots{}) (end-test [result@dots{}]) forms@dots{}
This is to @code{do} what @code{let*} is to @code{let}.  In
particular, the initial values are bound as if by @code{let*}
rather than @code{let}, and the steps are assigned as if by
@code{setq} rather than @code{psetq}.

Here is another way to write the above loop:

(do* ((xp foo (cdr xp))
      (yp bar (cdr yp))
      (x (car xp) (car xp))
      (y (car yp) (car yp))
  ((or (null xp) (null yp))
   (nreverse z))
  (push (f x y) z))
@end example
@end defspec

2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
@defspec dolist (var list [result]) forms@dots{}
This is a more specialized loop which iterates across the elements
of a list.  @var{list} should evaluate to a list; the body @var{forms}
are executed with @var{var} bound to each element of the list in
turn.  Finally, the @var{result} form (or @code{nil}) is evaluated
with @var{var} bound to @code{nil} to produce the result returned by
the loop.  Unlike with Emacs's built in @code{dolist}, the loop is
surrounded by an implicit @code{nil} block.
@end defspec

@defspec dotimes (var count [result]) forms@dots{}
This is a more specialized loop which iterates a specified number
of times.  The body is executed with @var{var} bound to the integers
from zero (inclusive) to @var{count} (exclusive), in turn.  Then
the @code{result} form is evaluated with @var{var} bound to the total
number of iterations that were done (i.e., @code{(max 0 @var{count})})
to get the return value for the loop form.  Unlike with Emacs's built in
@code{dolist}, the loop is surrounded by an implicit @code{nil} block.
@end defspec

Dave Love's avatar
Dave Love committed
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493