The features described in the following sections implement
various advanced control structures, including the powerful
setf facility and a number of looping and conditional
psetq form is just like
setq, except that multiple
assignments are done in parallel rather than sequentially.
setq. Given several symbol and form pairs, it evaluates all the forms in advance and then stores the corresponding variables afterwards.
(setq x 2 y 3) (setq x (+ x y) y (* x y)) x => 5 y ;
ywas computed after
xwas set. => 15 (setq x 2 y 3) (psetq x (+ x y) y (* x y)) x => 5 y ;
ywas computed before
xwas set. => 6
The simplest use of
(psetq x y y x), which
exchanges the values of two variables. (The
provides an even more convenient way to swap two variables;
see section Modify Macros.)
psetq always returns
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.
setf form is like
setq, except that it accepts
arbitrary place forms on the left side rather than just
symbols. For example,
(setf (car a) b) sets the car of
b, doing the same operation as
(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 `x = a[i]' gets an element from an array
and `a[i] = x' stores an element using the same notation.
Just as certain forms like
a[i] can be lvalues in C, there
is a set of forms that can be generalized variables in Lisp.
setf macro is the most basic way to operate on generalized
setfreturns the value of the last form.
The following Lisp forms will work as generalized variables, and
so may legally appear in the place argument of
(setf x y)is exactly equivalent to
(setq x y), and
setqitself is strictly speaking redundant now that
setfexists. Many programmers continue to prefer
setqfor setting simple variables, though, purely for stylistic or historical reasons. The macro
(setf x y)actually expands to
(setq x y), so there is no performance penalty for using it in compiled code.
car cdr caar .. cddddr nth rest first .. tenth aref elt nthcdr symbol-function symbol-value symbol-plist get get* getf gethash subseqNote that for
getf, the list argument of the function must itself be a valid place form. For example,
(setf (nthcdr 0 foo) 7)will set
fooitself to 7. Note that
nthcdrplace can be used to insert or delete at any position in a list. The use of
nthcdras a place form is an extension to standard Common Lisp.
setf-able. (Some of these are defined only in Emacs 19 or only in Lucid Emacs.)
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 mark-markerMost of these have directly corresponding "set" functions, like
point. A few, like
point-min, expand to longer sequences of code when they are
(narrow-to-region x (point-max))in this case).
(substring subplace n [m]), where 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")) => ("hello" "world") (cadr a) => "world" (substring (cadr a) 2 4) => "rl" (setf (substring (cadr a) 2 4) "o") => "o" (cadr a) => "wood" a => ("hello" "wood")The generalized variable
buffer-substring, listed above, also works in this way by replacing a portion of the current buffer.
(apply 'func ...)or
(apply (function func) ...), where func is a
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
define-setf-methodor the long form of
setfis applied to the resulting form.
define-setf-methodhas been made.
Using any forms other than these in the place argument to
setf will signal an error.
setf macro takes care to evaluate all subforms in
the proper left-to-right order; for example,
(setf (aref vec (incf i)) i)
looks like it will evaluate
(incf i) exactly once, before the
following access to
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
(In this case,
aset would be used and no such steps would
be necessary since
aset takes its arguments in a convenient
However, if the 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))
(setf (wrong-order a b) 17) will
evaluate b first, then a, just as in an actual call
This package defines a number of other macros besides
that operate on generalized variables. Many are interesting and
useful even when the place is just a variable name.
setq: When several places and forms 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).
(incf i)is equivalent to
(setq i (1+ i)), and
(incf (car x) 2)is equivalent to
(setcar x (+ (car x) 2)).
Once again, care is taken to preserve the "apparent" order of evaluation. For example,
(incf (aref vec (incf i)))
appears to increment
i once, then increment the element of
vec addressed by
i; this is indeed exactly what it
does, which means the above form is not equivalent to the
(setf (aref vec (incf i)) (1+ (aref vec (incf i)))) ; Wrong!
but rather to something more like
(let ((temp (incf i))) (setf (aref vec temp) (1+ (aref vec temp))))
Again, all of this is taken care of automatically by
the other generalized-variable macros.
As a more Emacs-specific example of
incf, the expression
(incf (point) n) is essentially equivalent to
(prog1 (car place) (setf place (cdr place))), except that it takes care to evaluate all subforms only once.
(setf place (cons x place)), except for evaluation of the subforms.
eqlto any existing element of the list. The optional keyword arguments are interpreted in the same way as for
adjoin. See section Lists as Sets.
(shiftf a b c d)is equivalent to
(prog1 a (psetf a b b c c d))
except that the subforms of a, b, and c are actually evaluated only once each and in the apparent order.
(rotatef a b c d)is equivalent to
(psetf a b b c c d d a)
except for the evaluation of subforms.
nil. Note that
(rotatef a b)
conveniently exchanges a and b.
The following macros were invented for this package; they have no analogues in Common Lisp.
let, but for generalized variables rather than just symbols. Each binding should be of the form
(place value); the original contents of the places are saved, the values are stored in them, and then the body forms are executed. Afterwards, the places are set back to their original saved contents. This cleanup happens even if the forms exit irregularly due to a
throwor an error.
(letf (((point) (point-min)) (a 17)) ...)
moves "point" in the current buffer to the beginning of the buffer,
and also binds
a to 17 (as if by a normal
a is just a regular variable). After the body exits,
is set back to its original value and point is moved back to its
(point) is not quite like a
save-excursion, as the latter effectively saves a marker
which tracks insertions and deletions in the buffer. Actually,
(point-marker) is much closer to this
point-marker are equivalent
setf places; each will accept either an integer or a
marker as the stored value.)
Since generalized variables look like lists,
of using `foo' for `(foo nil)' as a binding would
be ambiguous in
letf and is not allowed.
However, a binding specifier may be a one-element list
`(place)', which is similar to `(place
place)'. In other words, the place is not disturbed
on entry to the body, and the only effect of the
to restore the original value of place afterwards. (The
redundant access-and-store suggested by the
place) example does not actually occur.)
In most cases, the place must have a well-defined value on
entry to the
letf form. The only exceptions are plain
variables and calls to
If the symbol is not bound on entry, it is simply made unbound by
fmakunbound on exit.
let: It does the bindings in sequential rather than parallel order.
(incf place n)is the same as
(callf + place 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)
See section Customizing Setf, for
define-modify-macro, a way
to create even more concise notations for modify macros. Note
callf is an extension to standard Common Lisp.
callf, except that place is the second argument of function rather than the first. For example,
(push x place)is equivalent to
(callf2 cons x place).
callf2 macros serve as building
blocks for other macros like
macros are used in the processing of symbol macros;
see section Macro Bindings.
Common Lisp defines three macros,
define-setf-method, that allow the
user to extend generalized variables in various ways.
decf. The macro name is defined to take a place argument followed by additional arguments described by arglist. The call
(name place args...)
will be expanded to
(callf func place args...)
which in turn is roughly equivalent to
(setf place (func place args...))
(define-modify-macro incf (&optional (n 1)) +) (define-modify-macro concatf (&rest args) concat)
&key is not allowed in arglist, but
&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
define-modify-macro. For example,
push takes its arguments in the wrong order, and
is completely irregular. You can define these macros "by hand"
get-setf-method, or consult the source file
`cl-macs.el' to see how to use the internal
defsetfforms. Where access-fn is the name of a function which accesses a place, this declares update-fn to be the corresponding store function. From now on,
(setf (access-fn arg1 arg2 arg3) value)
will be expanded to
(update-fn arg1 arg2 arg3 value)
The update-fn is required to be either a true function, or
a macro which evaluates its arguments in a function-like way. Also,
the update-fn is expected to return value as its result.
Otherwise, the above expansion would not obey the rules for the way
setf is supposed to behave.
As a special (non-Common-Lisp) extension, a third argument of
defsetf says that the
update-fn's return value is
not suitable, so that the above
setf should be expanded to
something more like
(let ((temp value)) (update-fn arg1 arg2 arg3 temp) temp)
Some examples of the use of
defsetf, drawn from the standard
suite of setf methods, are:
(defsetf car setcar) (defsetf symbol-value set) (defsetf buffer-name rename-buffer t)
defsetf. It is rather like
defmacroexcept for the additional store-var argument. The forms should return a Lisp form which stores the value of store-var into the generalized variable formed by a call to access-fn with arguments described by arglist. The forms may begin with a string which documents the
setfmethod (analogous to the doc string that appears at the front of a function).
For example, the simple form of
defsetf is shorthand for
(defsetf access-fn (&rest args) (store) (append '(update-fn) args (list store)))
The Lisp form that is returned can access the arguments from
arglist and store-var in an unrestricted fashion;
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))
setfto access-fn with arguments described by arglist is expanded, the forms are evaluated and must return a list of five items:
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 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
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
gensym. Macros like
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.
define-setf-method. The result is a list of five values as described above. You can use this function to build your own
incf-like modify macros. (Actually, it is better to use the internal functions
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
incffunction for a simple example.)
The argument env specifies the "environment" to be
passed on to
need to expand a macro in place. It should come from
&environment argument to the macro or setf-method
See also the source code for the setf-methods for
substring, each of which works by calling
get-setf-method on a simpler case, then massaging
the result in various ways.
Modern Common Lisp defines a second, independent way to specify
setf behavior of a function, namely "
functions" whose names are lists
rather than symbols. For example,
(defun (setf foo) ...)
defines the function that is used when
setf is applied to
foo. This package does not currently support
functions. In particular, it is a compile-time error to use
setf on a form which has not already been
or otherwise declared; in newer Common Lisps, this would not be
an error since the function
(setf func) might be
These Lisp forms make bindings to variables and function names,
analogous to Lisp's built-in
See section Modify Macros, for the
letf* forms which
are also related to variable bindings.
let form binds variables whose names are known
at compile-time. The
progv form provides an easy way to
bind variables whose names are computed at run-time.
let-style variable bindings on a set of variables computed at run-time. The expressions symbols and 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 forms. If values is shorter than symbols, the last few symbols are made unbound (as if by
makunbound) inside the body. If symbols is shorter than values, the excess values are ignored.
The CL package defines the following macro which
more closely follows the Common Lisp
letexcept 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
lexical-let(after macro expansion) may refer to the bound variables.
(setq a 5) (defun foo (b) (+ a b)) (let ((a 2)) (foo a)) => 4 (lexical-let ((a 2)) (foo a)) => 7
In this example, a regular
let binding of
makes a temporary change to the global variable
is able to see the binding of
a to 2. But
actually creates a distinct local variable
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 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) => 21
(make-adder 17) returns a function object which adds
17 to its argument. If
let had been used instead of
lexical-let, the function object would have referred to the
n, which would have been bound to 17 only during the
(defun make-counter () (lexical-let ((n 0)) (function* (lambda (&optional (m 1)) (incf n m))))) (setq count-1 (make-counter)) (funcall count-1 3) => 3 (funcall count-1 14) => 17 (setq count-2 (make-counter)) (funcall count-2 5) => 5 (funcall count-1 2) => 19 (funcall count-2) => 6
Here we see that each call to
make-counter creates a distinct
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,
count-2 refers to a function object which refers to an
instance of the variable
n; this is the only reference
to that variable, so after
(setq count-2 nil) the garbage
collector would be able to delete this instance of
Of course, if a
lexical-let does not actually create any
closures, then the lexical variables are free as soon as the
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
(defun add-to-list (x list) (mapcar (function (lambda (y) (+ x y))) list)) (add-to-list 7 '(1 2 5)) => (8 9 12)
Since this lambda is only used while
x is still bound,
it is not necessary to make a true closure out of it.
You can use
flet inside a
to create a named closure. If several closures are created in the
body of a single
lexical-let, they all close over the same
instance of the lexical variable.
lexical-let form is an extension to Common Lisp. In
true Common Lisp, all bindings are lexical unless declared otherwise.
lexical-let, except that the bindings are made sequentially in the manner of
These forms make
let-like bindings to functions instead
let-style bindings on the function cells of symbols rather than on the value cells. Each binding must be a list of the form `(name arglist forms...)', which defines a function exactly as if it were a
defun*form. The function name is defined accordingly for the duration of the body of the
flet; then the old function definition, or lack thereof, is restored.
flet in Common Lisp establishes a lexical binding of
name, Emacs Lisp
flet makes a dynamic binding. The
result is that
flet affects indirect calls to a function as
well as calls directly inside the
flet form itself.
You can use
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
(flet ((message (&rest args) (push args saved-msgs))) (do-something))
This code attempts to replace the built-in function
with a function that simply saves the messages in a list rather
than displaying them. The original definition of
will be restored after
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
Functions defined by
flet may use the full Common Lisp
argument notation supported by
defun*; also, the function
body is enclosed in an implicit block as if by
See section Program Structure.
labelsform is like
flet, except that it makes lexical bindings of the function names rather than dynamic bindings. (In true Common Lisp, both
labelsmake lexical bindings of slightly different sorts; since Emacs Lisp is dynamically bound by default, it seemed more appropriate for
fletalso to use dynamic binding. The
labelsform, 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
labels form. References may appear both in the body
labels itself, and in the bodies of
the functions themselves. Thus,
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
function to be passed on to, say,
These forms create local macros and "symbol macros."
flet, but for macros instead of functions. Each binding is a list of the same form as the arguments to
defmacro*(i.e., a macro name, argument list, and macro-expander forms). The macro is defined accordingly for use within the body of the
Because of the nature of macros,
macrolet is lexically
scoped even in Emacs Lisp: The
macrolet binding will
affect only calls that appear physically within the body
forms, possibly after expansion of other macros in the
(setq bar '(5 . 9)) (symbol-macrolet ((foo (car bar))) (incf foo)) bar => (6 . 9)
setq of a symbol macro is treated the same as a
(setq foo 4) in the above would be equivalent to
(setf foo 4), which in turn expands to
(setf (car bar) 4).
let* binding a symbol macro is
treated like a
letf*. This differs from true
Common Lisp, where the rules of lexical scoping cause a
binding to shadow a
symbol-macrolet binding. In this package,
lexical-let* will shadow a symbol
There is no analogue of
defmacro for symbol macros; all symbol
macros are local. A typical use of
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))) body)))) (setq mylist '(1 2 3 4)) (my-dolist (x mylist) (incf x)) mylist => (2 3 4 5)
In this example, the
my-dolist macro is similar to
(see section Iteration) except that the variable
x becomes a true
reference onto the elements of the list. The
shown here expands to
(loop for G1234 on mylist do (symbol-macrolet ((x (car G1234))) (incf x)))
which in turn expands to
(loop for G1234 on mylist do (incf (car G1234)))
See section Loop Facility, for a description of the
This package defines a nonstandard
in-ref loop clause that
works much like
These conditional forms augment Emacs Lisp's simple
ifwhere there are no "else" forms, and possibly several "then" forms. In particular,
(when test a b c)
is entirely equivalent to
(if test (progn a b c) nil)
ifwhere there are no "then" forms, and possibly several "else" forms:
(unless test a b c)
is entirely equivalent to
(when (not test) a b c)
eql. If no clause matches, the
nil. The clauses are of the form
where keylist is a list of key values. If there is exactly
one value, and it is not a cons cell or the symbol
t, then it can be used by itself as a keylist without
being enclosed in a list. All key values in the
must be distinct. The final clauses may use
t in place of
a keylist to indicate a default clause that should be taken
if none of the other clauses match. (The symbol
is also recognized in place of
t. To make a clause that
matches the actual symbol
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 `a', a `b', a RET or LFD, or anything else.
(case (read-char) (?a (do-a-thing)) (?b (do-b-thing)) ((?\r ?\n) (do-ret-thing)) (t (do-other-thing)))
case, except that if the key does not match any of the clauses, an error is signaled rather than simply returning
casethat checks for types rather than values. Each clause is of the form `(type body...)'. See section 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)))
The type specifier
t matches any type of object; the word
otherwise is also allowed. To make one clause match any of
several types, use an
(or ...) type specifier.
typecase, except that if the key does not match any of the clauses, an error is signaled rather than simply returning
Common Lisp blocks provide a non-local exit mechanism very
throw, but lexically rather than
dynamically scoped. This package actually implements
in terms of
catch; however, the lexical scoping allows the
optimizing byte-compiler to omit the costly
catch step if the
body of the block does not actually
return-from the block.
progn. However, if any of the forms execute
(return-from name), they will jump out and return directly from the
blockreturns the result of the last form unless a
return-from mechanism is quite similar to
throw mechanism. The main differences are
that block names 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
are dynamically scoped. This means that functions called from the
body of a
catch can also
throw to the
return-from referring to a block name must appear
physically within the 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
lambdas in the body. Block
catch names form independent name-spaces.
In true Common Lisp,
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
forms which do create the implicit block.
The Common Lisp looping constructs defined by this package,
dolist, also create implicit blocks
just as in Common Lisp.
Because they are implemented in terms of Emacs Lisp
throw, blocks have the same overhead as actual
catch constructs (roughly two function calls). However,
Zawinski and Furuseth's optimizing byte compiler (standard in
Emacs 19) will optimize away the
catch if the block does
not in fact contain any
that jump to it. This means that
do loops and
functions which don't use
return don't pay the overhead to
(return-from nil result). Common Lisp loops like
dolistimplicitly enclose themselves in
The macros described here provide more sophisticated, high-level
looping constructs to complement Emacs Lisp's basic
loopand the extremely powerful and flexible feature known as the Loop Facility or Loop Macro. This more advanced facility is discussed in the following section; see section Loop Facility. The simple form of
loopis described here.
loop is followed by zero or more Lisp expressions,
(loop exprs...) simply creates an infinite
loop executing the expressions over and over. The loop is
enclosed in an implicit
nil block. Thus,
(loop (foo) (if (no-more) (return 72)) (bar))
is exactly equivalent to
(block nil (while t (foo) (if (no-more) (return 72)) (bar)))
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.)
(var [init [step]])
The loop works as follows: First, each var is bound to the
associated init value as if by a
let form. Then, in
each iteration of the loop, the end-test is evaluated; if
true, the loop is finished. Otherwise, the body forms are
evaluated, then each var is set to the associated step
expression (as if by a
psetq form) and the next iteration
begins. Once the end-test becomes true, the result
forms are evaluated (with the vars still bound to their
values) to produce the result returned by
do loop is enclosed in an implicit
block, so that you can use
(return) to break out of the
loop at any time.
If there are no result forms, the loop returns
If a given var has no step form, it is bound to its
init value but not otherwise modified during the
loop (unless the code explicitly modifies it); this case is just
a shorthand for putting a
(let ((var init)) ...)
around the loop. If init is also omitted it defaults to
nil, and in this case a plain `var' can be used
in place of `(var)', again following the analogy with
This example (from Steele) illustrates a loop which applies the
f to successive pairs of values from the lists
bar; it is equivalent to the call
(mapcar* 'f foo bar). Note that this loop has no body
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)))
let. In particular, the initial values are bound as if by
let, and the steps are assigned as if by
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)) z) ((or (null xp) (null yp)) (nreverse z)) (push (f x y) z))
nil) is evaluated with var bound to
nilto produce the result returned by the loop. The loop is surrounded by an implicit
resultform is evaluated with var bound to the total number of iterations that were done (i.e.,
(max 0 count)) to get the return value for the loop form. The loop is surrounded by an implicit
nil, it loops over all symbols in that obarray. For each symbol, the body forms are evaluated with var bound to that symbol. The symbols are visited in an unspecified order. Afterward the result form, if any, is evaluated (with var bound to
nil) to get the return value. The loop is surrounded by an implicit
do-symbolsexcept that the obarray argument is omitted; it always iterates over the default obarray.
See section Mapping over Sequences, for some more functions for iterating over vectors or lists.
A common complaint with Lisp's traditional looping constructs is
that they are either too simple and limited, such as Common Lisp's
dotimes or Emacs Lisp's
while, or too unreadable and
obscure, like Common Lisp's
To remedy this, recent versions of Common Lisp have added a new
construct called the "Loop Facility" or "
with an easy-to-use but very powerful and expressive syntax.
loop macro essentially creates a mini-language within
Lisp that is specially tailored for describing loops. While this
language is a little strange-looking by the standards of regular Lisp,
it turns out to be very easy to learn and well-suited to its purpose.
loop is a macro, all parsing of the loop language
takes place at byte-compile time; compiled
loops are just
as efficient as the equivalent
while loops written longhand.
do. Clauses are simply strung together in the argument list of
loop, with minimal extra parentheses. The various types of clauses specify initializations, such as the binding of temporary variables, actions to be taken in the loop, stepping actions, and final cleanup.
Common Lisp specifies a certain general order of clauses in a loop:
(loop name-clause var-clauses... action-clauses...)
The name-clause optionally gives a name to the implicit
block that surrounds the loop. By default, the implicit block
nil. The var-clauses specify what
variables should be bound during the loop, and how they should
be modified or iterated throughout the course of the loop. The
action-clauses are things to be done during the loop, such
as computing, collecting, and returning values.
The Emacs version of the
loop macro is less restrictive about
the order of clauses, but things will behave most predictably if
you put the variable-binding clauses
repeat before the action clauses. As in Common Lisp,
finally clauses can go anywhere.
Loops generally return
nil by default, but you can cause
them to return a value by using an accumulation clause like
collect, an end-test clause like
always, or an
return clause to jump out of the implicit block.
(Because the loop body is enclosed in an implicit block, you can
also use regular Lisp
break out of the loop.)
The following sections give some examples of the Loop Macro in
action, and describe the particular loop clauses in great detail.
Consult the second edition of Steele's Common Lisp, the Language,
for additional discussion and examples of the
Before listing the full set of clauses that are allowed, let's
look at a few example loops just to get a feel for the
(loop for buf in (buffer-list) collect (buffer-file-name buf))
This loop iterates over all Emacs buffers, using the list
buffer-list. For each buffer
buffer-file-name and collects the results into
a list, which is then returned from the
The result is a list of the file names of all the buffers in
Emacs' memory. The words
are reserved words in the
(loop repeat 20 do (insert "Yowsa\n"))
This loop inserts the phrase "Yowsa" twenty times in the current buffer.
(loop until (eobp) do (munch-line) (forward-line 1))
This loop calls
munch-line on every line until the end
of the buffer. If point is already at the end of the buffer,
the loop exits immediately.
(loop do (munch-line) until (eobp) do (forward-line 1))
This loop is similar to the above one, except that
is always called at least once.
(loop for x from 1 to 100 for y = (* x x) until (>= y 729) finally return (list x (= y 729)))
This more complicated loop searches for a number
square is 729. For safety's sake it only examines
values up to 100; dropping the phrase `to 100' would
cause the loop to count upwards with no limit. The second
for clause defines
y to be the square of
within the loop; the expression after the
= sign is
reevaluated each time through the loop. The
clause gives a condition for terminating the loop, and the
finally clause says what to do when the loop finishes.
(This particular example was written less concisely than it
could have been, just for the sake of illustration.)
Note that even though this loop contains three clauses (two
fors and an
until) that would have been enough to
define loops all by themselves, it still creates a single loop
rather than some sort of triple-nested loop. You must explicitly
loop constructs if you want nested loops.
Most loops are governed by one or more
for clause simultaneously describes variables to be
bound, how those variables are to be stepped during the loop,
and usually an end condition based on those variables.
as is a synonym for the word
word is followed by a variable name, then a word like
across that describes the kind of iteration desired.
In Common Lisp, the phrase
being the sometimes precedes
the type of iteration; in this package both
the are optional. The word
each is a synonym
the, and the word that follows it may be singular
or plural: `for x being the elements of y' or
`for x being each element of y'. Which form you use
is purely a matter of style.
The variable is bound around the loop as if by
(setq i 'happy) (loop for i from 1 to 10 do (do-something-with i)) i => happy
for var from expr1 to expr2 by expr3
forclause creates a counting loop. Each of the three sub-terms is optional, though there must be at least one term so that the clause is marked as a counting clause. The three expressions are the starting value, the ending value, and the step value, respectively, of the variable. The loop counts upwards by default (expr3 must be positive), from expr1 to expr2 inclusively. If you omit the
fromterm, the loop counts from zero; if you omit the
toterm, the loop counts forever without stopping (unless stopped by some other loop clause, of course); if you omit the
byterm, the loop counts in steps of one. You can replace the word
downfromto indicate the direction of the loop. Likewise, you can replace
downto. For example, `for x from 5 downto 1' executes five times with
xtaking on the integers from 5 down to 1 in turn. Also, you can replace
above, which are like
downtorespectively except that they are exclusive rather than inclusive limits:
(loop for x to 10 collect x) => (0 1 2 3 4 5 6 7 8 9 10) (loop for x below 10 collect x) => (0 1 2 3 4 5 6 7 8 9)The
byvalue is always positive, even for downward-counting loops. Some sort of
fromvalue is required for downward loops; `for x downto 5' is not a legal loop clause all by itself.
for var in list by function
byterm, then function is used to traverse the list instead of
cdr; it must be a function taking one argument. For example:
(loop for x in '(1 2 3 4 5 6) collect (* x x)) => (1 4 9 16 25 36) (loop for x in '(1 2 3 4 5 6) by 'cddr collect (* x x)) => (1 9 25)
for var on list by function
(loop for x on '(1 2 3 4) collect x) => ((1 2 3 4) (2 3 4) (3 4) (4))With
by, there is no real reason that the
onexpression must be a list. For example:
(loop for x on first-animal by 'next-animal collect x)where
(next-animal x)takes an "animal" x and returns the next in the (assumed) sequence of animals, or
nilif x was the last animal in the sequence.
for var in-ref list by function
inclause, but var becomes a
setf-able "reference" onto the elements of the list rather than just a temporary variable. For example,
(loop for x in-ref my-list do (incf x))increments every element of
my-listin place. This clause is an extension to standard Common Lisp.
for var across array
(loop for x across "aeiou" do (use-vowel (char-to-string x)))
for var across-ref array
setf-able reference onto the elements; see
for var being the elements of sequence
across. The clause may be followed by the additional term `using (index var2)' to cause var2 to be bound to the successive indices (starting at 0) of the elements. This clause type is taken from older versions of the
loopmacro, and is not present in modern Common Lisp. The `using (sequence ...)' term of the older macros is not supported.
for var being the elements of-ref sequence
setf-able reference onto the elements; see
for var being the symbols [of obarray]
(loop for sym being the symbols when (fboundp sym) when (string-match "^map" (symbol-name sym)) collect sym)returns a list of all the functions whose names begin with `map'. The Common Lisp words
present-symbolsare also recognized but are equivalent to
symbolsin Emacs Lisp. Due to a minor implementation restriction, it will not work to have more than one
forclause iterating over symbols, hash tables, keymaps, overlays, or intervals in a given
loop. Fortunately, it would rarely if ever be useful to do so. It is legal to mix one of these types of clauses with other clauses like
for ... toor
for var being the hash-keys of hash-table
hash-valuesis the opposite word of the word following
the) to cause var and var2 to be bound to the two parts of each hash table entry.
for var being the key-codes of keymap
usingclause to access both the codes and the bindings together.
for var being the key-seqs of keymap
for var being the overlays [of buffer] ...
extentsis synonymous with
overlays). Under Emacs 18, this clause iterates zero times. If the
ofterm is omitted, the current buffer is used. This clause also accepts optional `from pos' and `to pos' terms, limiting the clause to overlays which overlap the specified region.
for var being the intervals [of buffer] ...
propertyterms, where the latter term restricts the search to just the specified property. The
ofterm may specify either a buffer or a string. This clause is useful only in GNU Emacs 19; in other versions, all buffers and strings consist of a single interval.
for var being the frames
screensis a synonym for
frames. The frames are visited in
next-frameorder starting from
for var being the windows [of frame]
ofterm is not allowed there.)
for var being the buffers
for var = expr1 then expr2
(loop for x on my-list by 'cddr do ...) (loop for x = my-list then (cddr x) while x do ...)Note that this type of
forclause does not imply any sort of terminating condition; the above example combines it with a
whileclause to tell when to end the loop. If you omit the
thenterm, expr1 is used both for the initial setting and for successive settings:
(loop for x = (random) when (> x 0) return x)This loop keeps taking random numbers from the
(random)function until it gets a positive one, which it then returns.
If you include several
for clauses in a row, they are
treated sequentially (as if by
You can instead use the word
and to link the clauses,
in which case they are processed in parallel (as if by
(loop for x below 5 for y = nil then x collect (list x y)) => ((0 nil) (1 1) (2 2) (3 3) (4 4)) (loop for x below 5 and y = nil then x collect (list x y)) => ((0 nil) (1 0) (2 1) (3 2) (4 3))
In the first loop,
y is set based on the value of
that was just set by the previous clause; in the second loop,
y are set simultaneously so
y is set
based on the value of
x left over from the previous time
through the loop.
Another feature of the
loop macro is destructuring,
similar in concept to the destructuring provided by
The var part of any
for clause can be given as a list
of variables instead of a single variable. The values produced
during loop execution must be lists; the values in the lists are
stored in the corresponding variables.
(loop for (x y) in '((2 3) (4 5) (6 7)) collect (+ x y)) => (5 9 13)
In loop destructuring, if there are more values than variables
the trailing values are ignored, and if there are more variables
than values the trailing variables get the value
nil is used as a variable name, the corresponding
values are ignored. Destructuring may be nested, and dotted
lists of variables like
(x . y) are allowed.
for clauses, there are several other loop clauses
that control the way the loop operates. They might be used by
themselves, or in conjunction with one or more
(loop repeat n do ...) (loop for temp to n do ...)are identical except that the second one forces you to choose a name for a variable you aren't actually going to use.
nil. For example, the following two loops are equivalent, except for the implicit
nilblock that surrounds the second one:
(while cond forms...) (loop while cond do forms...)
while, it stops the loop using
return nilso that the
finallyclauses are not executed. If all the conditions were non-
nil, the loop returns
(if (loop for size in size-list always (> size 10)) (some-big-sizes) (no-big-sizes))
always, except that the loop returns
tif any conditions were false, or
nil; in this case, it returns that non-
nilvalue. If all the values were
nil, the loop returns
These clauses cause the loop to accumulate information about the
specified Lisp form. The accumulated result is returned
from the loop unless overridden, say, by a
collectappear elsewhere in this manual. The word
collectingis a synonym for
collect, and likewise for the other accumulation clauses.
maximizeis executed zero times.
Accumulation clauses can be followed by `into var' to
cause the data to be collected into variable var (which is
let-bound during the loop) rather than an
unnamed temporary variable. Also,
into accumulations do
not automatically imply a return value. The loop must use some
explicit mechanism, such as
finally return, to return
the accumulated result.
It is legal for several accumulation clauses of the same type to accumulate into the same place. From Steele:
(loop for name in '(fred sue alice joe june) for kids in '((bob ken) () () (kris sunshine) ()) collect name append kids) => (fred bob ken sue alice joe kris sunshine june)
This section describes the remaining loop clauses.
with var = value
(loop with x = 17 do ...) (let ((x 17)) (loop do ...)) (loop for x = 17 then x do ...)Naturally, the variable var might be used for some purpose in the rest of the loop. For example:
(loop for x in my-list with res = nil do (push x res) finally return res)This loop inserts the elements of
my-listat the front of a new list being accumulated in
res, then returns the list
resat the end of the loop. The effect is similar to that of a
collectclause, but the list gets reversed by virtue of the fact that elements are being pushed onto the front of
resrather than the end. If you omit the
=term, the variable is initialized to
nil. (Thus the `= nil' in the above example is unnecessary.) Bindings made by
withare sequential by default, as if by
let*. Just like
withclauses can be linked with
andto cause the bindings to be made by
if condition clause
unlessclause. Several clauses may be linked by separating them with
and. These clauses may be followed by
elseand a clause or clauses to execute if the condition was false. The whole construct may optionally be followed by the word
end(which may be used to disambiguate an
andin a nested
if). The actual non-
nilvalue of the condition form is available by the name
itin the "then" part. For example:
(setq funny-numbers '(6 13 -1)) => (6 13 -1) (loop for x below 10 if (oddp x) collect x into odds and if (memq x funny-numbers) return (cdr it) end else collect x into evens finally return (vector odds evens)) => [(1 3 5 7 9) (0 2 4 6 8)] (setq funny-numbers '(6 7 13 -1)) => (6 7 13 -1) (loop <same thing again>) => (13 -1)Note the use of
andto put two clauses into the "then" part, one of which is itself an
ifclause. Note also that
end, while normally optional, was necessary here to make it clear that the
elserefers to the outermost
ifclause. In the first case, the loop returns a vector of lists of the odd and even values of x. In the second case, the odd number 7 is one of the
funny-numbersso the loop returns early; the actual returned value is based on the result of the
when condition clause
unless condition clause
unlessclause is just like
ifexcept that the sense of the condition is reversed.
nilto the implicit block surrounding the loop. The name is the symbol to be used as the block name.
initially [do] forms...
withhave been bound to their initial values).
initiallyclauses can appear anywhere; if there are several, they are executed in the order they appear in the loop. The keyword
finally [do] forms...
finallyclauses may appear anywhere in the loop construct, but they are executed (in the specified order) at the beginning or end, respectively, of the loop.
finally return form
return, the loop will simply return
nil.) Variables bound by
intowill still contain their final values when form is executed.
domay be followed by any number of Lisp expressions which are executed as an implicit
prognin the body of the loop. Many of the examples in this section illustrate the use of
finallyclauses, if any, are not executed. Of course,
returnis generally used inside an
unless, as its use in a top-level loop clause would mean the loop would never get to "loop" more than once. The clause `return form' is equivalent to `do (return form)' (or
return-fromif the loop was named). The
returnclause is implemented a bit more efficiently, though.
While there is no high-level way to add user extensions to
setf, say), this package
does offer two properties called
cl-loop-for-handler which are functions to be called when
a given symbol is encountered as a top-level loop clause or
for clause, respectively. Consult the source code in
file `cl-macs.el' for details.
loop macro is compatible with that of Common
Lisp, except that a few features are not implemented:
and data-type specifiers. Naturally, the
for clauses which
iterate over keymaps, overlays, intervals, frames, windows, and
buffers are Emacs-specific extensions.
Common Lisp functions can return zero or more results. Emacs Lisp
functions, by contrast, always return exactly one result. This
package makes no attempt to emulate Common Lisp multiple return
values; Emacs versions of Common Lisp functions that return more
than one value either return just the first value (as in
compiler-macroexpand) or return a list of values (as in
get-setf-method). This package does define placeholders
for the Common Lisp functions that work with multiple values, but
in Emacs Lisp these functions simply operate on lists instead.
values form, for example, is a synonym for
let, and then executes the body forms. If there are more vars than values, the extra vars are bound to
nil. If there are fewer vars than values, the excess values are ignored.
setq. Extra vars or values are treated the same as in
The older Quiroz package attempted a more faithful (but still
imperfect) emulation of Common Lisp multiple values. The old
method "usually" simulated true multiple values quite well,
but under certain circumstances would leave spurious return
values in memory where a later, unrelated
form would see them.
Since a perfect emulation is not feasible in Emacs Lisp, this package opts to keep it as simple and predictable as possible.
Go to the first, previous, next, last section, table of contents.