Move some cl.texi setf extensions to the Obsolete appendix
[bpt/emacs.git] / doc / misc / cl.texi
1 \input texinfo @c -*-texinfo-*-
2 @setfilename ../../info/cl
3 @settitle Common Lisp Extensions
4 @include emacsver.texi
5
6 @copying
7 This file documents the GNU Emacs Common Lisp emulation package.
8
9 Copyright @copyright{} 1993, 2001-2012 Free Software Foundation, Inc.
10
11 @quotation
12 Permission is granted to copy, distribute and/or modify this document
13 under the terms of the GNU Free Documentation License, Version 1.3 or
14 any later version published by the Free Software Foundation; with no
15 Invariant Sections, with the Front-Cover texts being ``A GNU Manual'',
16 and with the Back-Cover Texts as in (a) below. A copy of the license
17 is included in the section entitled ``GNU Free Documentation License''.
18
19 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
20 modify this GNU manual. Buying copies from the FSF supports it in
21 developing GNU and promoting software freedom.''
22 @end quotation
23 @end copying
24
25 @dircategory Emacs lisp libraries
26 @direntry
27 * CL: (cl). Partial Common Lisp support for Emacs Lisp.
28 @end direntry
29
30 @finalout
31
32 @titlepage
33 @sp 6
34 @center @titlefont{Common Lisp Extensions}
35 @sp 4
36 @center For GNU Emacs Lisp
37 @sp 1
38 @center as distributed with Emacs @value{EMACSVER}
39 @sp 5
40 @center Dave Gillespie
41 @center daveg@@synaptics.com
42 @page
43 @vskip 0pt plus 1filll
44 @insertcopying
45 @end titlepage
46
47 @contents
48
49 @ifnottex
50 @node Top
51 @top GNU Emacs Common Lisp Emulation
52
53 @insertcopying
54 @end ifnottex
55
56 @menu
57 * Overview:: Basics, usage, etc.
58 * Program Structure:: Arglists, @code{cl-eval-when}, @code{defalias}.
59 * Predicates:: @code{cl-typep} and @code{cl-equalp}.
60 * Control Structure:: @code{cl-do}, @code{cl-loop}, etc.
61 * Macros:: Destructuring, @code{cl-define-compiler-macro}.
62 * Declarations:: @code{cl-proclaim}, @code{cl-declare}, etc.
63 * Symbols:: Property lists, @code{cl-gensym}.
64 * Numbers:: Predicates, functions, random numbers.
65 * Sequences:: Mapping, functions, searching, sorting.
66 * Lists:: @code{cl-caddr}, @code{cl-sublis}, @code{cl-member}, @code{cl-assoc}, etc.
67 * Structures:: @code{cl-defstruct}.
68 * Assertions:: @code{cl-check-type}, @code{cl-assert}.
69
70 * Efficiency Concerns:: Hints and techniques.
71 * Common Lisp Compatibility:: All known differences with Steele.
72 * Porting Common Lisp:: Hints for porting Common Lisp code.
73 * Obsolete Features:: Obsolete features.
74
75 * GNU Free Documentation License:: The license for this documentation.
76 * Function Index::
77 * Variable Index::
78 @end menu
79
80 @node Overview
81 @chapter Overview
82
83 @noindent
84 This document describes a set of Emacs Lisp facilities borrowed from
85 Common Lisp. All the facilities are described here in detail. While
86 this document does not assume any prior knowledge of Common Lisp, it
87 does assume a basic familiarity with Emacs Lisp.
88
89 Common Lisp is a huge language, and Common Lisp systems tend to be
90 massive and extremely complex. Emacs Lisp, by contrast, is rather
91 minimalist in the choice of Lisp features it offers the programmer.
92 As Emacs Lisp programmers have grown in number, and the applications
93 they write have grown more ambitious, it has become clear that Emacs
94 Lisp could benefit from many of the conveniences of Common Lisp.
95
96 The @code{CL} package adds a number of Common Lisp functions and
97 control structures to Emacs Lisp. While not a 100% complete
98 implementation of Common Lisp, @code{CL} adds enough functionality
99 to make Emacs Lisp programming significantly more convenient.
100
101 Some Common Lisp features have been omitted from this package
102 for various reasons:
103
104 @itemize @bullet
105 @item
106 Some features are too complex or bulky relative to their benefit
107 to Emacs Lisp programmers. CLOS and Common Lisp streams are fine
108 examples of this group.
109
110 @item
111 Other features cannot be implemented without modification to the
112 Emacs Lisp interpreter itself, such as multiple return values,
113 case-insensitive symbols, and complex numbers.
114 The @code{CL} package generally makes no attempt to emulate these
115 features.
116
117 @end itemize
118
119 This package was originally written by Dave Gillespie,
120 @file{daveg@@synaptics.com}, as a total rewrite of an earlier 1986
121 @file{cl.el} package by Cesar Quiroz. Care has been taken to ensure
122 that each function is defined efficiently, concisely, and with minimal
123 impact on the rest of the Emacs environment. Stefan Monnier added the
124 file @file{cl-lib.el} and rationalized the namespace for Emacs 24.3.
125
126 @menu
127 * Usage:: How to use the CL package.
128 * Organization:: The package's component files.
129 * Naming Conventions:: Notes on CL function names.
130 @end menu
131
132 @node Usage
133 @section Usage
134
135 @noindent
136 The @code{CL} package is distributed with Emacs, so there is no need
137 to install any additional files in order to start using it. Lisp code
138 that uses features from the @code{CL} package should simply include at
139 the beginning:
140
141 @example
142 (require 'cl-lib)
143 @end example
144
145 @noindent
146 You may wish to add such a statement to your init file, if you
147 make frequent use of CL features.
148
149 @node Organization
150 @section Organization
151
152 @noindent
153 The Common Lisp package is organized into four main files:
154
155 @table @file
156 @item cl-lib.el
157 This is the main file, which contains basic functions
158 and information about the package. This file is relatively compact.
159
160 @item cl-extra.el
161 This file contains the larger, more complex or unusual functions.
162 It is kept separate so that packages which only want to use Common
163 Lisp fundamentals like the @code{cl-incf} function won't need to pay
164 the overhead of loading the more advanced functions.
165
166 @item cl-seq.el
167 This file contains most of the advanced functions for operating
168 on sequences or lists, such as @code{cl-delete-if} and @code{cl-assoc}.
169
170 @item cl-macs.el
171 This file contains the features that are macros instead of functions.
172 Macros expand when the caller is compiled, not when it is run, so the
173 macros generally only need to be present when the byte-compiler is
174 running (or when the macros are used in uncompiled code). Most of the
175 macros of this package are isolated in @file{cl-macs.el} so that they
176 won't take up memory unless you are compiling.
177 @end table
178
179 The file @file{cl-lib.el} includes all necessary @code{autoload}
180 commands for the functions and macros in the other three files.
181 All you have to do is @code{(require 'cl-lib)}, and @file{cl-lib.el}
182 will take care of pulling in the other files when they are
183 needed.
184
185 There is another file, @file{cl.el}, which was the main entry point to
186 the CL package prior to Emacs 24.3. Nowadays, it is replaced by
187 @file{cl-lib.el}. The two provide the same features (in most cases),
188 but use different function names (in fact, @file{cl.el} mainly just
189 defines aliases to the @file{cl-lib.el} definitions). Where
190 @file{cl-lib.el} defines a function called, for example,
191 @code{cl-incf}, @file{cl.el} uses the same name but without the
192 @samp{cl-} prefix, e.g. @code{incf} in this example. There are a few
193 exceptions to this. First, functions such as @code{cl-defun} where
194 the unprefixed version was already used for a standard Emacs Lisp
195 function. In such cases, the @file{cl.el} version adds a @samp{*}
196 suffix, e.g. @code{defun*}. Second, there are some obsolete features
197 that are only implemented in @file{cl.el}, not in @file{cl-lib.el},
198 because they are replaced by other standard Emacs Lisp features.
199 Finally, in a very few cases the old @file{cl.el} versions do not
200 behave in exactly the same way as the @file{cl-lib.el} versions.
201 @xref{Obsolete Features}.
202
203 Since the old @file{cl.el} does not use a clean namespace, Emacs has a
204 policy that packages distributed with Emacs must not load @code{cl} at
205 run time. (It is ok for them to load @code{cl} at @emph{compile}
206 time, with @code{eval-when-compile}, and use the macros it provides.)
207 There is no such restriction on the use of @code{cl-lib}. New code
208 should use @code{cl-lib} rather than @code{cl}.
209
210 There is one more file, @file{cl-compat.el}, which defines some
211 routines from the older Quiroz CL package that are not otherwise
212 present in the new package. This file is obsolete and should not be
213 used in new code.
214
215 @node Naming Conventions
216 @section Naming Conventions
217
218 @noindent
219 Except where noted, all functions defined by this package have the
220 same calling conventions as their Common Lisp counterparts, and
221 names that are those of Common Lisp plus a @samp{cl-} prefix.
222
223 Internal function and variable names in the package are prefixed
224 by @code{cl--}. Here is a complete list of functions prefixed by
225 @code{cl-} that were not taken from Common Lisp:
226
227 @example
228 cl-callf cl-callf2 cl-defsubst
229 cl-floatp-safe cl-letf cl-letf*
230 @end example
231
232 The following simple functions and macros are defined in @file{cl-lib.el};
233 they do not cause other components like @file{cl-extra} to be loaded.
234
235 @example
236 cl-floatp-safe cl-endp
237 cl-evenp cl-oddp cl-plusp cl-minusp
238 cl-caaar .. cl-cddddr
239 cl-list* cl-ldiff cl-rest cl-first .. cl-tenth
240 cl-copy-list cl-subst cl-mapcar [2]
241 cl-adjoin [3] cl-acons cl-pairlis
242 cl-pushnew [3,4] cl-incf [4] cl-decf [4]
243 cl-proclaim cl-declaim
244 @end example
245
246 @noindent
247 [2] Only for one sequence argument or two list arguments.
248
249 @noindent
250 [3] Only if @code{:test} is @code{eq}, @code{equal}, or unspecified,
251 and @code{:key} is not used.
252
253 @noindent
254 [4] Only when @var{place} is a plain variable name.
255
256 @node Program Structure
257 @chapter Program Structure
258
259 @noindent
260 This section describes features of the @code{CL} package that have to
261 do with programs as a whole: advanced argument lists for functions,
262 and the @code{cl-eval-when} construct.
263
264 @menu
265 * Argument Lists:: @code{&key}, @code{&aux}, @code{cl-defun}, @code{cl-defmacro}.
266 * Time of Evaluation:: The @code{cl-eval-when} construct.
267 @end menu
268
269 @node Argument Lists
270 @section Argument Lists
271
272 @noindent
273 Emacs Lisp's notation for argument lists of functions is a subset of
274 the Common Lisp notation. As well as the familiar @code{&optional}
275 and @code{&rest} markers, Common Lisp allows you to specify default
276 values for optional arguments, and it provides the additional markers
277 @code{&key} and @code{&aux}.
278
279 Since argument parsing is built-in to Emacs, there is no way for
280 this package to implement Common Lisp argument lists seamlessly.
281 Instead, this package defines alternates for several Lisp forms
282 which you must use if you need Common Lisp argument lists.
283
284 @defmac cl-defun name arglist body...
285 This form is identical to the regular @code{defun} form, except
286 that @var{arglist} is allowed to be a full Common Lisp argument
287 list. Also, the function body is enclosed in an implicit block
288 called @var{name}; @pxref{Blocks and Exits}.
289 @end defmac
290
291 @defmac cl-defsubst name arglist body...
292 This is just like @code{cl-defun}, except that the function that
293 is defined is automatically proclaimed @code{inline}, i.e.,
294 calls to it may be expanded into in-line code by the byte compiler.
295 This is analogous to the @code{defsubst} form;
296 @code{cl-defsubst} uses a different method (compiler macros) which
297 works in all versions of Emacs, and also generates somewhat more
298 efficient inline expansions. In particular, @code{cl-defsubst}
299 arranges for the processing of keyword arguments, default values,
300 etc., to be done at compile-time whenever possible.
301 @end defmac
302
303 @defmac cl-defmacro name arglist body...
304 This is identical to the regular @code{defmacro} form,
305 except that @var{arglist} is allowed to be a full Common Lisp
306 argument list. The @code{&environment} keyword is supported as
307 described in Steele. The @code{&whole} keyword is supported only
308 within destructured lists (see below); top-level @code{&whole}
309 cannot be implemented with the current Emacs Lisp interpreter.
310 The macro expander body is enclosed in an implicit block called
311 @var{name}.
312 @end defmac
313
314 @defmac cl-function symbol-or-lambda
315 This is identical to the regular @code{function} form,
316 except that if the argument is a @code{lambda} form then that
317 form may use a full Common Lisp argument list.
318 @end defmac
319
320 Also, all forms (such as @code{cl-flet} and @code{cl-labels}) defined
321 in this package that include @var{arglist}s in their syntax allow
322 full Common Lisp argument lists.
323
324 Note that it is @emph{not} necessary to use @code{cl-defun} in
325 order to have access to most @code{CL} features in your function.
326 These features are always present; @code{cl-defun}'s only
327 difference from @code{defun} is its more flexible argument
328 lists and its implicit block.
329
330 The full form of a Common Lisp argument list is
331
332 @example
333 (@var{var}...
334 &optional (@var{var} @var{initform} @var{svar})...
335 &rest @var{var}
336 &key ((@var{keyword} @var{var}) @var{initform} @var{svar})...
337 &aux (@var{var} @var{initform})...)
338 @end example
339
340 Each of the five argument list sections is optional. The @var{svar},
341 @var{initform}, and @var{keyword} parts are optional; if they are
342 omitted, then @samp{(@var{var})} may be written simply @samp{@var{var}}.
343
344 The first section consists of zero or more @dfn{required} arguments.
345 These arguments must always be specified in a call to the function;
346 there is no difference between Emacs Lisp and Common Lisp as far as
347 required arguments are concerned.
348
349 The second section consists of @dfn{optional} arguments. These
350 arguments may be specified in the function call; if they are not,
351 @var{initform} specifies the default value used for the argument.
352 (No @var{initform} means to use @code{nil} as the default.) The
353 @var{initform} is evaluated with the bindings for the preceding
354 arguments already established; @code{(a &optional (b (1+ a)))}
355 matches one or two arguments, with the second argument defaulting
356 to one plus the first argument. If the @var{svar} is specified,
357 it is an auxiliary variable which is bound to @code{t} if the optional
358 argument was specified, or to @code{nil} if the argument was omitted.
359 If you don't use an @var{svar}, then there will be no way for your
360 function to tell whether it was called with no argument, or with
361 the default value passed explicitly as an argument.
362
363 The third section consists of a single @dfn{rest} argument. If
364 more arguments were passed to the function than are accounted for
365 by the required and optional arguments, those extra arguments are
366 collected into a list and bound to the ``rest'' argument variable.
367 Common Lisp's @code{&rest} is equivalent to that of Emacs Lisp.
368 Common Lisp accepts @code{&body} as a synonym for @code{&rest} in
369 macro contexts; this package accepts it all the time.
370
371 The fourth section consists of @dfn{keyword} arguments. These
372 are optional arguments which are specified by name rather than
373 positionally in the argument list. For example,
374
375 @example
376 (cl-defun foo (a &optional b &key c d (e 17)))
377 @end example
378
379 @noindent
380 defines a function which may be called with one, two, or more
381 arguments. The first two arguments are bound to @code{a} and
382 @code{b} in the usual way. The remaining arguments must be
383 pairs of the form @code{:c}, @code{:d}, or @code{:e} followed
384 by the value to be bound to the corresponding argument variable.
385 (Symbols whose names begin with a colon are called @dfn{keywords},
386 and they are self-quoting in the same way as @code{nil} and
387 @code{t}.)
388
389 For example, the call @code{(foo 1 2 :d 3 :c 4)} sets the five
390 arguments to 1, 2, 4, 3, and 17, respectively. If the same keyword
391 appears more than once in the function call, the first occurrence
392 takes precedence over the later ones. Note that it is not possible
393 to specify keyword arguments without specifying the optional
394 argument @code{b} as well, since @code{(foo 1 :c 2)} would bind
395 @code{b} to the keyword @code{:c}, then signal an error because
396 @code{2} is not a valid keyword.
397
398 You can also explicitly specify the keyword argument; it need not be
399 simply the variable name prefixed with a colon. For example,
400
401 @example
402 (cl-defun bar (&key (a 1) ((baz b) 4)))
403 @end example
404
405 @noindent
406
407 specifies a keyword @code{:a} that sets the variable @code{a} with
408 default value 1, as well as a keyword @code{baz} that sets the
409 variable @code{b} with default value 4. In this case, because
410 @code{baz} is not self-quoting, you must quote it explicitly in the
411 function call, like this:
412
413 @example
414 (bar :a 10 'baz 42)
415 @end example
416
417 Ordinarily, it is an error to pass an unrecognized keyword to
418 a function, e.g., @code{(foo 1 2 :c 3 :goober 4)}. You can ask
419 Lisp to ignore unrecognized keywords, either by adding the
420 marker @code{&allow-other-keys} after the keyword section
421 of the argument list, or by specifying an @code{:allow-other-keys}
422 argument in the call whose value is non-@code{nil}. If the
423 function uses both @code{&rest} and @code{&key} at the same time,
424 the ``rest'' argument is bound to the keyword list as it appears
425 in the call. For example:
426
427 @smallexample
428 (cl-defun find-thing (thing &rest rest &key need &allow-other-keys)
429 (or (apply 'cl-member thing thing-list :allow-other-keys t rest)
430 (if need (error "Thing not found"))))
431 @end smallexample
432
433 @noindent
434 This function takes a @code{:need} keyword argument, but also
435 accepts other keyword arguments which are passed on to the
436 @code{cl-member} function. @code{allow-other-keys} is used to
437 keep both @code{find-thing} and @code{cl-member} from complaining
438 about each others' keywords in the arguments.
439
440 The fifth section of the argument list consists of @dfn{auxiliary
441 variables}. These are not really arguments at all, but simply
442 variables which are bound to @code{nil} or to the specified
443 @var{initforms} during execution of the function. There is no
444 difference between the following two functions, except for a
445 matter of stylistic taste:
446
447 @example
448 (cl-defun foo (a b &aux (c (+ a b)) d)
449 @var{body})
450
451 (cl-defun foo (a b)
452 (let ((c (+ a b)) d)
453 @var{body}))
454 @end example
455
456 Argument lists support @dfn{destructuring}. In Common Lisp,
457 destructuring is only allowed with @code{defmacro}; this package
458 allows it with @code{cl-defun} and other argument lists as well.
459 In destructuring, any argument variable (@var{var} in the above
460 diagram) can be replaced by a list of variables, or more generally,
461 a recursive argument list. The corresponding argument value must
462 be a list whose elements match this recursive argument list.
463 For example:
464
465 @example
466 (cl-defmacro dolist ((var listform &optional resultform)
467 &rest body)
468 ...)
469 @end example
470
471 This says that the first argument of @code{dolist} must be a list
472 of two or three items; if there are other arguments as well as this
473 list, they are stored in @code{body}. All features allowed in
474 regular argument lists are allowed in these recursive argument lists.
475 In addition, the clause @samp{&whole @var{var}} is allowed at the
476 front of a recursive argument list. It binds @var{var} to the
477 whole list being matched; thus @code{(&whole all a b)} matches
478 a list of two things, with @code{a} bound to the first thing,
479 @code{b} bound to the second thing, and @code{all} bound to the
480 list itself. (Common Lisp allows @code{&whole} in top-level
481 @code{defmacro} argument lists as well, but Emacs Lisp does not
482 support this usage.)
483
484 One last feature of destructuring is that the argument list may be
485 dotted, so that the argument list @code{(a b . c)} is functionally
486 equivalent to @code{(a b &rest c)}.
487
488 If the optimization quality @code{safety} is set to 0
489 (@pxref{Declarations}), error checking for wrong number of
490 arguments and invalid keyword arguments is disabled. By default,
491 argument lists are rigorously checked.
492
493 @node Time of Evaluation
494 @section Time of Evaluation
495
496 @noindent
497 Normally, the byte-compiler does not actually execute the forms in
498 a file it compiles. For example, if a file contains @code{(setq foo t)},
499 the act of compiling it will not actually set @code{foo} to @code{t}.
500 This is true even if the @code{setq} was a top-level form (i.e., not
501 enclosed in a @code{defun} or other form). Sometimes, though, you
502 would like to have certain top-level forms evaluated at compile-time.
503 For example, the compiler effectively evaluates @code{defmacro} forms
504 at compile-time so that later parts of the file can refer to the
505 macros that are defined.
506
507 @defmac cl-eval-when (situations...) forms...
508 This form controls when the body @var{forms} are evaluated.
509 The @var{situations} list may contain any set of the symbols
510 @code{compile}, @code{load}, and @code{eval} (or their long-winded
511 ANSI equivalents, @code{:compile-toplevel}, @code{:load-toplevel},
512 and @code{:execute}).
513
514 The @code{cl-eval-when} form is handled differently depending on
515 whether or not it is being compiled as a top-level form.
516 Specifically, it gets special treatment if it is being compiled
517 by a command such as @code{byte-compile-file} which compiles files
518 or buffers of code, and it appears either literally at the
519 top level of the file or inside a top-level @code{progn}.
520
521 For compiled top-level @code{cl-eval-when}s, the body @var{forms} are
522 executed at compile-time if @code{compile} is in the @var{situations}
523 list, and the @var{forms} are written out to the file (to be executed
524 at load-time) if @code{load} is in the @var{situations} list.
525
526 For non-compiled-top-level forms, only the @code{eval} situation is
527 relevant. (This includes forms executed by the interpreter, forms
528 compiled with @code{byte-compile} rather than @code{byte-compile-file},
529 and non-top-level forms.) The @code{cl-eval-when} acts like a
530 @code{progn} if @code{eval} is specified, and like @code{nil}
531 (ignoring the body @var{forms}) if not.
532
533 The rules become more subtle when @code{cl-eval-when}s are nested;
534 consult Steele (second edition) for the gruesome details (and
535 some gruesome examples).
536
537 Some simple examples:
538
539 @example
540 ;; Top-level forms in foo.el:
541 (cl-eval-when (compile) (setq foo1 'bar))
542 (cl-eval-when (load) (setq foo2 'bar))
543 (cl-eval-when (compile load) (setq foo3 'bar))
544 (cl-eval-when (eval) (setq foo4 'bar))
545 (cl-eval-when (eval compile) (setq foo5 'bar))
546 (cl-eval-when (eval load) (setq foo6 'bar))
547 (cl-eval-when (eval compile load) (setq foo7 'bar))
548 @end example
549
550 When @file{foo.el} is compiled, these variables will be set during
551 the compilation itself:
552
553 @example
554 foo1 foo3 foo5 foo7 ; `compile'
555 @end example
556
557 When @file{foo.elc} is loaded, these variables will be set:
558
559 @example
560 foo2 foo3 foo6 foo7 ; `load'
561 @end example
562
563 And if @file{foo.el} is loaded uncompiled, these variables will
564 be set:
565
566 @example
567 foo4 foo5 foo6 foo7 ; `eval'
568 @end example
569
570 If these seven @code{cl-eval-when}s had been, say, inside a @code{defun},
571 then the first three would have been equivalent to @code{nil} and the
572 last four would have been equivalent to the corresponding @code{setq}s.
573
574 Note that @code{(cl-eval-when (load eval) @dots{})} is equivalent
575 to @code{(progn @dots{})} in all contexts. The compiler treats
576 certain top-level forms, like @code{defmacro} (sort-of) and
577 @code{require}, as if they were wrapped in @code{(cl-eval-when
578 (compile load eval) @dots{})}.
579 @end defmac
580
581 Emacs includes two special forms related to @code{cl-eval-when}.
582 One of these, @code{eval-when-compile}, is not quite equivalent to
583 any @code{cl-eval-when} construct and is described below.
584
585 The other form, @code{(eval-and-compile @dots{})}, is exactly
586 equivalent to @samp{(cl-eval-when (compile load eval) @dots{})} and
587 so is not itself defined by this package.
588
589 @defmac eval-when-compile forms...
590 The @var{forms} are evaluated at compile-time; at execution time,
591 this form acts like a quoted constant of the resulting value. Used
592 at top-level, @code{eval-when-compile} is just like @samp{eval-when
593 (compile eval)}. In other contexts, @code{eval-when-compile}
594 allows code to be evaluated once at compile-time for efficiency
595 or other reasons.
596
597 This form is similar to the @samp{#.} syntax of true Common Lisp.
598 @end defmac
599
600 @defmac cl-load-time-value form
601 The @var{form} is evaluated at load-time; at execution time,
602 this form acts like a quoted constant of the resulting value.
603
604 Early Common Lisp had a @samp{#,} syntax that was similar to
605 this, but ANSI Common Lisp replaced it with @code{load-time-value}
606 and gave it more well-defined semantics.
607
608 In a compiled file, @code{cl-load-time-value} arranges for @var{form}
609 to be evaluated when the @file{.elc} file is loaded and then used
610 as if it were a quoted constant. In code compiled by
611 @code{byte-compile} rather than @code{byte-compile-file}, the
612 effect is identical to @code{eval-when-compile}. In uncompiled
613 code, both @code{eval-when-compile} and @code{cl-load-time-value}
614 act exactly like @code{progn}.
615
616 @example
617 (defun report ()
618 (insert "This function was executed on: "
619 (current-time-string)
620 ", compiled on: "
621 (eval-when-compile (current-time-string))
622 ;; or '#.(current-time-string) in real Common Lisp
623 ", and loaded on: "
624 (cl-load-time-value (current-time-string))))
625 @end example
626
627 @noindent
628 Byte-compiled, the above defun will result in the following code
629 (or its compiled equivalent, of course) in the @file{.elc} file:
630
631 @example
632 (setq --temp-- (current-time-string))
633 (defun report ()
634 (insert "This function was executed on: "
635 (current-time-string)
636 ", compiled on: "
637 '"Wed Jun 23 18:33:43 1993"
638 ", and loaded on: "
639 --temp--))
640 @end example
641 @end defmac
642
643 @node Predicates
644 @chapter Predicates
645
646 @noindent
647 This section describes functions for testing whether various
648 facts are true or false.
649
650 @menu
651 * Type Predicates:: @code{cl-typep}, @code{cl-deftype}, and @code{cl-coerce}.
652 * Equality Predicates:: @code{cl-equalp}.
653 @end menu
654
655 @node Type Predicates
656 @section Type Predicates
657
658 @defun cl-typep object type
659 Check if @var{object} is of type @var{type}, where @var{type} is a
660 (quoted) type name of the sort used by Common Lisp. For example,
661 @code{(cl-typep foo 'integer)} is equivalent to @code{(integerp foo)}.
662 @end defun
663
664 The @var{type} argument to the above function is either a symbol
665 or a list beginning with a symbol.
666
667 @itemize @bullet
668 @item
669 If the type name is a symbol, Emacs appends @samp{-p} to the
670 symbol name to form the name of a predicate function for testing
671 the type. (Built-in predicates whose names end in @samp{p} rather
672 than @samp{-p} are used when appropriate.)
673
674 @item
675 The type symbol @code{t} stands for the union of all types.
676 @code{(cl-typep @var{object} t)} is always true. Likewise, the
677 type symbol @code{nil} stands for nothing at all, and
678 @code{(cl-typep @var{object} nil)} is always false.
679
680 @item
681 The type symbol @code{null} represents the symbol @code{nil}.
682 Thus @code{(cl-typep @var{object} 'null)} is equivalent to
683 @code{(null @var{object})}.
684
685 @item
686 The type symbol @code{atom} represents all objects that are not cons
687 cells. Thus @code{(cl-typep @var{object} 'atom)} is equivalent to
688 @code{(atom @var{object})}.
689
690 @item
691 The type symbol @code{real} is a synonym for @code{number}, and
692 @code{fixnum} is a synonym for @code{integer}.
693
694 @item
695 The type symbols @code{character} and @code{string-char} match
696 integers in the range from 0 to 255.
697
698 @item
699 The type symbol @code{float} uses the @code{cl-floatp-safe} predicate
700 defined by this package rather than @code{floatp}, so it will work
701 correctly even in Emacs versions without floating-point support.
702
703 @item
704 The type list @code{(integer @var{low} @var{high})} represents all
705 integers between @var{low} and @var{high}, inclusive. Either bound
706 may be a list of a single integer to specify an exclusive limit,
707 or a @code{*} to specify no limit. The type @code{(integer * *)}
708 is thus equivalent to @code{integer}.
709
710 @item
711 Likewise, lists beginning with @code{float}, @code{real}, or
712 @code{number} represent numbers of that type falling in a particular
713 range.
714
715 @item
716 Lists beginning with @code{and}, @code{or}, and @code{not} form
717 combinations of types. For example, @code{(or integer (float 0 *))}
718 represents all objects that are integers or non-negative floats.
719
720 @item
721 Lists beginning with @code{member} or @code{cl-member} represent
722 objects @code{eql} to any of the following values. For example,
723 @code{(member 1 2 3 4)} is equivalent to @code{(integer 1 4)},
724 and @code{(member nil)} is equivalent to @code{null}.
725
726 @item
727 Lists of the form @code{(satisfies @var{predicate})} represent
728 all objects for which @var{predicate} returns true when called
729 with that object as an argument.
730 @end itemize
731
732 The following function and macro (not technically predicates) are
733 related to @code{cl-typep}.
734
735 @defun cl-coerce object type
736 This function attempts to convert @var{object} to the specified
737 @var{type}. If @var{object} is already of that type as determined by
738 @code{cl-typep}, it is simply returned. Otherwise, certain types of
739 conversions will be made: If @var{type} is any sequence type
740 (@code{string}, @code{list}, etc.) then @var{object} will be
741 converted to that type if possible. If @var{type} is
742 @code{character}, then strings of length one and symbols with
743 one-character names can be coerced. If @var{type} is @code{float},
744 then integers can be coerced in versions of Emacs that support
745 floats. In all other circumstances, @code{cl-coerce} signals an
746 error.
747 @end defun
748
749 @defmac cl-deftype name arglist forms...
750 This macro defines a new type called @var{name}. It is similar
751 to @code{defmacro} in many ways; when @var{name} is encountered
752 as a type name, the body @var{forms} are evaluated and should
753 return a type specifier that is equivalent to the type. The
754 @var{arglist} is a Common Lisp argument list of the sort accepted
755 by @code{cl-defmacro}. The type specifier @samp{(@var{name} @var{args}...)}
756 is expanded by calling the expander with those arguments; the type
757 symbol @samp{@var{name}} is expanded by calling the expander with
758 no arguments. The @var{arglist} is processed the same as for
759 @code{cl-defmacro} except that optional arguments without explicit
760 defaults use @code{*} instead of @code{nil} as the ``default''
761 default. Some examples:
762
763 @example
764 (cl-deftype null () '(satisfies null)) ; predefined
765 (cl-deftype list () '(or null cons)) ; predefined
766 (cl-deftype unsigned-byte (&optional bits)
767 (list 'integer 0 (if (eq bits '*) bits (1- (lsh 1 bits)))))
768 (unsigned-byte 8) @equiv{} (integer 0 255)
769 (unsigned-byte) @equiv{} (integer 0 *)
770 unsigned-byte @equiv{} (integer 0 *)
771 @end example
772
773 @noindent
774 The last example shows how the Common Lisp @code{unsigned-byte}
775 type specifier could be implemented if desired; this package does
776 not implement @code{unsigned-byte} by default.
777 @end defmac
778
779 The @code{cl-typecase} and @code{cl-check-type} macros also use type
780 names. @xref{Conditionals}. @xref{Assertions}. The @code{cl-map},
781 @code{cl-concatenate}, and @code{cl-merge} functions take type-name
782 arguments to specify the type of sequence to return. @xref{Sequences}.
783
784 @node Equality Predicates
785 @section Equality Predicates
786
787 @noindent
788 This package defines the Common Lisp predicate @code{cl-equalp}.
789
790 @defun cl-equalp a b
791 This function is a more flexible version of @code{equal}. In
792 particular, it compares strings case-insensitively, and it compares
793 numbers without regard to type (so that @code{(cl-equalp 3 3.0)} is
794 true). Vectors and conses are compared recursively. All other
795 objects are compared as if by @code{equal}.
796
797 This function differs from Common Lisp @code{equalp} in several
798 respects. First, Common Lisp's @code{equalp} also compares
799 @emph{characters} case-insensitively, which would be impractical
800 in this package since Emacs does not distinguish between integers
801 and characters. In keeping with the idea that strings are less
802 vector-like in Emacs Lisp, this package's @code{cl-equalp} also will
803 not compare strings against vectors of integers.
804 @end defun
805
806 Also note that the Common Lisp functions @code{member} and @code{assoc}
807 use @code{eql} to compare elements, whereas Emacs Lisp follows the
808 MacLisp tradition and uses @code{equal} for these two functions.
809 In Emacs, use @code{memq} (or @code{cl-member}) and @code{assq} (or
810 @code{cl-assoc}) to get functions which use @code{eql} for comparisons.
811
812 @node Control Structure
813 @chapter Control Structure
814
815 @noindent
816 The features described in the following sections implement
817 various advanced control structures, including extensions to the
818 standard @code{setf} facility, and a number of looping and conditional
819 constructs.
820
821 @c FIXME
822 @c flet is not cl-flet.
823 @menu
824 * Assignment:: The @code{cl-psetq} form.
825 * Generalized Variables:: Extensions to generalized variables.
826 * Variable Bindings:: @code{cl-progv}, @code{flet}, @code{cl-macrolet}.
827 * Conditionals:: @code{cl-case}, @code{cl-typecase}.
828 * Blocks and Exits:: @code{cl-block}, @code{cl-return}, @code{cl-return-from}.
829 * Iteration:: @code{cl-do}, @code{cl-dotimes}, @code{cl-dolist}, @code{cl-do-symbols}.
830 * Loop Facility:: The Common Lisp @code{cl-loop} macro.
831 * Multiple Values:: @code{cl-values}, @code{cl-multiple-value-bind}, etc.
832 @end menu
833
834 @node Assignment
835 @section Assignment
836
837 @noindent
838 The @code{cl-psetq} form is just like @code{setq}, except that multiple
839 assignments are done in parallel rather than sequentially.
840
841 @defmac cl-psetq [symbol form]@dots{}
842 This special form (actually a macro) is used to assign to several
843 variables simultaneously. Given only one @var{symbol} and @var{form},
844 it has the same effect as @code{setq}. Given several @var{symbol}
845 and @var{form} pairs, it evaluates all the @var{form}s in advance
846 and then stores the corresponding variables afterwards.
847
848 @example
849 (setq x 2 y 3)
850 (setq x (+ x y) y (* x y))
851 x
852 @result{} 5
853 y ; @r{@code{y} was computed after @code{x} was set.}
854 @result{} 15
855 (setq x 2 y 3)
856 (cl-psetq x (+ x y) y (* x y))
857 x
858 @result{} 5
859 y ; @r{@code{y} was computed before @code{x} was set.}
860 @result{} 6
861 @end example
862
863 The simplest use of @code{cl-psetq} is @code{(cl-psetq x y y x)}, which
864 exchanges the values of two variables. (The @code{cl-rotatef} form
865 provides an even more convenient way to swap two variables;
866 @pxref{Modify Macros}.)
867
868 @code{cl-psetq} always returns @code{nil}.
869 @end defmac
870
871 @node Generalized Variables
872 @section Generalized Variables
873
874 A @dfn{generalized variable} or @dfn{place form} is one of the many
875 places in Lisp memory where values can be stored. The simplest place
876 form is a regular Lisp variable. But the cars and cdrs of lists,
877 elements of arrays, properties of symbols, and many other locations
878 are also places where Lisp values are stored. For basic information,
879 @pxref{Generalized Variables,,,elisp,GNU Emacs Lisp Reference Manual}.
880 This package provides several additional features related to
881 generalized variables.
882
883 @menu
884 * Setf Extensions:: Additional @code{setf} places.
885 * Modify Macros:: @code{cl-incf}, @code{cl-rotatef}, @code{letf}, @code{cl-callf}, etc.
886 @end menu
887
888 @node Setf Extensions
889 @subsection Setf Extensions
890
891 Several standard (e.g. @code{car}) and Emacs-specific
892 (e.g. @code{window-point}) Lisp functions are @code{setf}-able by default.
893 This package defines @code{setf} handlers for several additional functions:
894
895 @itemize
896 @item
897 Functions from @code{CL} itself:
898 @smallexample
899 cl-caaar .. cl-cddddr cl-first .. cl-tenth
900 cl-rest cl-get cl-getf cl-subseq
901 @end smallexample
902
903 @item
904 General Emacs Lisp functions:
905 @smallexample
906 buffer-file-name getenv
907 buffer-modified-p global-key-binding
908 buffer-name local-key-binding
909 buffer-string mark
910 buffer-substring mark-marker
911 current-buffer marker-position
912 current-case-table mouse-position
913 current-column point
914 current-global-map point-marker
915 current-input-mode point-max
916 current-local-map point-min
917 current-window-configuration read-mouse-position
918 default-file-modes screen-height
919 documentation-property screen-width
920 face-background selected-window
921 face-background-pixmap selected-screen
922 face-font selected-frame
923 face-foreground standard-case-table
924 face-underline-p syntax-table
925 file-modes visited-file-modtime
926 frame-height window-height
927 frame-parameters window-width
928 frame-visible-p x-get-secondary-selection
929 frame-width x-get-selection
930 get-register
931 @end smallexample
932
933 Most of these have directly corresponding ``set'' functions, like
934 @code{use-local-map} for @code{current-local-map}, or @code{goto-char}
935 for @code{point}. A few, like @code{point-min}, expand to longer
936 sequences of code when they are used with @code{setf}
937 (@code{(narrow-to-region x (point-max))} in this case).
938
939 @item
940 A call of the form @code{(substring @var{subplace} @var{n} [@var{m}])},
941 where @var{subplace} is itself a valid generalized variable whose
942 current value is a string, and where the value stored is also a
943 string. The new string is spliced into the specified part of the
944 destination string. For example:
945
946 @example
947 (setq a (list "hello" "world"))
948 @result{} ("hello" "world")
949 (cadr a)
950 @result{} "world"
951 (substring (cadr a) 2 4)
952 @result{} "rl"
953 (setf (substring (cadr a) 2 4) "o")
954 @result{} "o"
955 (cadr a)
956 @result{} "wood"
957 a
958 @result{} ("hello" "wood")
959 @end example
960
961 The generalized variable @code{buffer-substring}, listed above,
962 also works in this way by replacing a portion of the current buffer.
963
964 @c FIXME? Also `eq'? (see cl-lib.el)
965
966 @c Currently commented out in cl.el.
967 @ignore
968 @item
969 A call of the form @code{(apply '@var{func} @dots{})} or
970 @code{(apply (function @var{func}) @dots{})}, where @var{func}
971 is a @code{setf}-able function whose store function is ``suitable''
972 in the sense described in Steele's book; since none of the standard
973 Emacs place functions are suitable in this sense, this feature is
974 only interesting when used with places you define yourself with
975 @code{define-setf-method} or the long form of @code{defsetf}.
976 @end ignore
977
978 @item
979 A macro call, in which case the macro is expanded and @code{setf}
980 is applied to the resulting form.
981
982 @item
983 Any form for which a @code{defsetf} or @code{define-setf-method}
984 has been made. @xref{Obsolete Setf Customization}.
985 @end itemize
986
987 @c FIXME should this be in lispref? It seems self-evident.
988 @c Contrast with the cl-incf example later on.
989 @c Here it really only serves as a constrast to wrong-order.
990 The @code{setf} macro takes care to evaluate all subforms in
991 the proper left-to-right order; for example,
992
993 @example
994 (setf (aref vec (cl-incf i)) i)
995 @end example
996
997 @noindent
998 looks like it will evaluate @code{(cl-incf i)} exactly once, before the
999 following access to @code{i}; the @code{setf} expander will insert
1000 temporary variables as necessary to ensure that it does in fact work
1001 this way no matter what setf-method is defined for @code{aref}.
1002 (In this case, @code{aset} would be used and no such steps would
1003 be necessary since @code{aset} takes its arguments in a convenient
1004 order.)
1005
1006 However, if the @var{place} form is a macro which explicitly
1007 evaluates its arguments in an unusual order, this unusual order
1008 will be preserved. Adapting an example from Steele, given
1009
1010 @example
1011 (defmacro wrong-order (x y) (list 'aref y x))
1012 @end example
1013
1014 @noindent
1015 the form @code{(setf (wrong-order @var{a} @var{b}) 17)} will
1016 evaluate @var{b} first, then @var{a}, just as in an actual call
1017 to @code{wrong-order}.
1018
1019 @node Modify Macros
1020 @subsection Modify Macros
1021
1022 @noindent
1023 This package defines a number of macros that operate on generalized
1024 variables. Many are interesting and useful even when the @var{place}
1025 is just a variable name.
1026
1027 @defmac cl-psetf [place form]@dots{}
1028 This macro is to @code{setf} what @code{cl-psetq} is to @code{setq}:
1029 When several @var{place}s and @var{form}s are involved, the
1030 assignments take place in parallel rather than sequentially.
1031 Specifically, all subforms are evaluated from left to right, then
1032 all the assignments are done (in an undefined order).
1033 @end defmac
1034
1035 @defmac cl-incf place &optional x
1036 This macro increments the number stored in @var{place} by one, or
1037 by @var{x} if specified. The incremented value is returned. For
1038 example, @code{(cl-incf i)} is equivalent to @code{(setq i (1+ i))}, and
1039 @code{(cl-incf (car x) 2)} is equivalent to @code{(setcar x (+ (car x) 2))}.
1040
1041 As with @code{setf}, care is taken to preserve the ``apparent'' order
1042 of evaluation. For example,
1043
1044 @example
1045 (cl-incf (aref vec (cl-incf i)))
1046 @end example
1047
1048 @noindent
1049 appears to increment @code{i} once, then increment the element of
1050 @code{vec} addressed by @code{i}; this is indeed exactly what it
1051 does, which means the above form is @emph{not} equivalent to the
1052 ``obvious'' expansion,
1053
1054 @example
1055 (setf (aref vec (cl-incf i))
1056 (1+ (aref vec (cl-incf i)))) ; wrong!
1057 @end example
1058
1059 @noindent
1060 but rather to something more like
1061
1062 @example
1063 (let ((temp (cl-incf i)))
1064 (setf (aref vec temp) (1+ (aref vec temp))))
1065 @end example
1066
1067 @noindent
1068 Again, all of this is taken care of automatically by @code{cl-incf} and
1069 the other generalized-variable macros.
1070
1071 As a more Emacs-specific example of @code{cl-incf}, the expression
1072 @code{(cl-incf (point) @var{n})} is essentially equivalent to
1073 @code{(forward-char @var{n})}.
1074 @end defmac
1075
1076 @defmac cl-decf place &optional x
1077 This macro decrements the number stored in @var{place} by one, or
1078 by @var{x} if specified.
1079 @end defmac
1080
1081 @defmac cl-pushnew x place @t{&key :test :test-not :key}
1082 This macro inserts @var{x} at the front of the list stored in
1083 @var{place}, but only if @var{x} was not @code{eql} to any
1084 existing element of the list. The optional keyword arguments
1085 are interpreted in the same way as for @code{cl-adjoin}.
1086 @xref{Lists as Sets}.
1087 @end defmac
1088
1089 @defmac cl-shiftf place@dots{} newvalue
1090 This macro shifts the @var{place}s left by one, shifting in the
1091 value of @var{newvalue} (which may be any Lisp expression, not just
1092 a generalized variable), and returning the value shifted out of
1093 the first @var{place}. Thus, @code{(cl-shiftf @var{a} @var{b} @var{c}
1094 @var{d})} is equivalent to
1095
1096 @example
1097 (prog1
1098 @var{a}
1099 (cl-psetf @var{a} @var{b}
1100 @var{b} @var{c}
1101 @var{c} @var{d}))
1102 @end example
1103
1104 @noindent
1105 except that the subforms of @var{a}, @var{b}, and @var{c} are actually
1106 evaluated only once each and in the apparent order.
1107 @end defmac
1108
1109 @defmac cl-rotatef place@dots{}
1110 This macro rotates the @var{place}s left by one in circular fashion.
1111 Thus, @code{(cl-rotatef @var{a} @var{b} @var{c} @var{d})} is equivalent to
1112
1113 @example
1114 (cl-psetf @var{a} @var{b}
1115 @var{b} @var{c}
1116 @var{c} @var{d}
1117 @var{d} @var{a})
1118 @end example
1119
1120 @noindent
1121 except for the evaluation of subforms. @code{cl-rotatef} always
1122 returns @code{nil}. Note that @code{(cl-rotatef @var{a} @var{b})}
1123 conveniently exchanges @var{a} and @var{b}.
1124 @end defmac
1125
1126 The following macros were invented for this package; they have no
1127 analogues in Common Lisp.
1128
1129 @defmac letf (bindings@dots{}) forms@dots{}
1130 This macro is analogous to @code{let}, but for generalized variables
1131 rather than just symbols. Each @var{binding} should be of the form
1132 @code{(@var{place} @var{value})}; the original contents of the
1133 @var{place}s are saved, the @var{value}s are stored in them, and
1134 then the body @var{form}s are executed. Afterwards, the @var{places}
1135 are set back to their original saved contents. This cleanup happens
1136 even if the @var{form}s exit irregularly due to a @code{throw} or an
1137 error.
1138
1139 For example,
1140
1141 @example
1142 (letf (((point) (point-min))
1143 (a 17))
1144 ...)
1145 @end example
1146
1147 @noindent
1148 moves ``point'' in the current buffer to the beginning of the buffer,
1149 and also binds @code{a} to 17 (as if by a normal @code{let}, since
1150 @code{a} is just a regular variable). After the body exits, @code{a}
1151 is set back to its original value and point is moved back to its
1152 original position.
1153
1154 Note that @code{letf} on @code{(point)} is not quite like a
1155 @code{save-excursion}, as the latter effectively saves a marker
1156 which tracks insertions and deletions in the buffer. Actually,
1157 a @code{letf} of @code{(point-marker)} is much closer to this
1158 behavior. (@code{point} and @code{point-marker} are equivalent
1159 as @code{setf} places; each will accept either an integer or a
1160 marker as the stored value.)
1161
1162 Since generalized variables look like lists, @code{let}'s shorthand
1163 of using @samp{foo} for @samp{(foo nil)} as a @var{binding} would
1164 be ambiguous in @code{letf} and is not allowed.
1165
1166 However, a @var{binding} specifier may be a one-element list
1167 @samp{(@var{place})}, which is similar to @samp{(@var{place}
1168 @var{place})}. In other words, the @var{place} is not disturbed
1169 on entry to the body, and the only effect of the @code{letf} is
1170 to restore the original value of @var{place} afterwards. (The
1171 redundant access-and-store suggested by the @code{(@var{place}
1172 @var{place})} example does not actually occur.)
1173
1174 In most cases, the @var{place} must have a well-defined value on
1175 entry to the @code{letf} form. The only exceptions are plain
1176 variables and calls to @code{symbol-value} and @code{symbol-function}.
1177 If the symbol is not bound on entry, it is simply made unbound by
1178 @code{makunbound} or @code{fmakunbound} on exit.
1179 @end defmac
1180
1181 @defmac cl-letf* (bindings@dots{}) forms@dots{}
1182 This macro is to @code{letf} what @code{let*} is to @code{let}:
1183 It does the bindings in sequential rather than parallel order.
1184 @end defmac
1185
1186 @defmac cl-callf @var{function} @var{place} @var{args}@dots{}
1187 This is the ``generic'' modify macro. It calls @var{function},
1188 which should be an unquoted function name, macro name, or lambda.
1189 It passes @var{place} and @var{args} as arguments, and assigns the
1190 result back to @var{place}. For example, @code{(cl-incf @var{place}
1191 @var{n})} is the same as @code{(cl-callf + @var{place} @var{n})}.
1192 Some more examples:
1193
1194 @example
1195 (cl-callf abs my-number)
1196 (cl-callf concat (buffer-name) "<" (number-to-string n) ">")
1197 (cl-callf cl-union happy-people (list joe bob) :test 'same-person)
1198 @end example
1199
1200 Note again that @code{cl-callf} is an extension to standard Common Lisp.
1201 @end defmac
1202
1203 @defmac cl-callf2 @var{function} @var{arg1} @var{place} @var{args}@dots{}
1204 This macro is like @code{cl-callf}, except that @var{place} is
1205 the @emph{second} argument of @var{function} rather than the
1206 first. For example, @code{(push @var{x} @var{place})} is
1207 equivalent to @code{(cl-callf2 cons @var{x} @var{place})}.
1208 @end defmac
1209
1210 The @code{cl-callf} and @code{cl-callf2} macros serve as building
1211 blocks for other macros like @code{cl-incf}, @code{cl-pushnew}, and
1212 @code{define-modify-macro}. The @code{letf} and @code{cl-letf*}
1213 macros are used in the processing of symbol macros;
1214 @pxref{Macro Bindings}.
1215
1216
1217 @node Variable Bindings
1218 @section Variable Bindings
1219
1220 @noindent
1221 These Lisp forms make bindings to variables and function names,
1222 analogous to Lisp's built-in @code{let} form.
1223
1224 @xref{Modify Macros}, for the @code{letf} and @code{cl-letf*} forms which
1225 are also related to variable bindings.
1226
1227 @menu
1228 * Dynamic Bindings:: The @code{cl-progv} form.
1229 * Function Bindings:: @code{flet} and @code{labels}.
1230 * Macro Bindings:: @code{cl-macrolet} and @code{cl-symbol-macrolet}.
1231 @end menu
1232
1233 @node Dynamic Bindings
1234 @subsection Dynamic Bindings
1235
1236 @noindent
1237 The standard @code{let} form binds variables whose names are known
1238 at compile-time. The @code{cl-progv} form provides an easy way to
1239 bind variables whose names are computed at run-time.
1240
1241 @defmac cl-progv symbols values forms@dots{}
1242 This form establishes @code{let}-style variable bindings on a
1243 set of variables computed at run-time. The expressions
1244 @var{symbols} and @var{values} are evaluated, and must return lists
1245 of symbols and values, respectively. The symbols are bound to the
1246 corresponding values for the duration of the body @var{form}s.
1247 If @var{values} is shorter than @var{symbols}, the last few symbols
1248 are bound to @code{nil}.
1249 If @var{symbols} is shorter than @var{values}, the excess values
1250 are ignored.
1251 @end defmac
1252
1253 @node Function Bindings
1254 @subsection Function Bindings
1255
1256 @noindent
1257 These forms make @code{let}-like bindings to functions instead
1258 of variables.
1259
1260 @defmac flet (bindings@dots{}) forms@dots{}
1261 This form establishes @code{let}-style bindings on the function
1262 cells of symbols rather than on the value cells. Each @var{binding}
1263 must be a list of the form @samp{(@var{name} @var{arglist}
1264 @var{forms}@dots{})}, which defines a function exactly as if
1265 it were a @code{cl-defun} form. The function @var{name} is defined
1266 accordingly for the duration of the body of the @code{flet}; then
1267 the old function definition, or lack thereof, is restored.
1268
1269 While @code{flet} in Common Lisp establishes a lexical binding of
1270 @var{name}, Emacs Lisp @code{flet} makes a dynamic binding. The
1271 result is that @code{flet} affects indirect calls to a function as
1272 well as calls directly inside the @code{flet} form itself.
1273
1274 You can use @code{flet} to disable or modify the behavior of a
1275 function in a temporary fashion. This will even work on Emacs
1276 primitives, although note that some calls to primitive functions
1277 internal to Emacs are made without going through the symbol's
1278 function cell, and so will not be affected by @code{flet}. For
1279 example,
1280
1281 @example
1282 (flet ((message (&rest args) (push args saved-msgs)))
1283 (do-something))
1284 @end example
1285
1286 This code attempts to replace the built-in function @code{message}
1287 with a function that simply saves the messages in a list rather
1288 than displaying them. The original definition of @code{message}
1289 will be restored after @code{do-something} exits. This code will
1290 work fine on messages generated by other Lisp code, but messages
1291 generated directly inside Emacs will not be caught since they make
1292 direct C-language calls to the message routines rather than going
1293 through the Lisp @code{message} function.
1294
1295 @c Bug#411.
1296 Also note that many primitives (e.g. @code{+}) have special byte-compile
1297 handling. Attempts to redefine such functions using @code{flet} will
1298 fail if byte-compiled. In such cases, use @code{labels} instead.
1299
1300 Functions defined by @code{flet} may use the full Common Lisp
1301 argument notation supported by @code{cl-defun}; also, the function
1302 body is enclosed in an implicit block as if by @code{cl-defun}.
1303 @xref{Program Structure}.
1304 @end defmac
1305
1306 @defmac labels (bindings@dots{}) forms@dots{}
1307 The @code{labels} form is like @code{flet}, except that it
1308 makes lexical bindings of the function names rather than
1309 dynamic bindings. (In true Common Lisp, both @code{flet} and
1310 @code{labels} make lexical bindings of slightly different sorts;
1311 since Emacs Lisp is dynamically bound by default, it seemed
1312 more appropriate for @code{flet} also to use dynamic binding.
1313 The @code{labels} form, with its lexical binding, is fully
1314 compatible with Common Lisp.)
1315
1316 Lexical scoping means that all references to the named
1317 functions must appear physically within the body of the
1318 @code{labels} form. References may appear both in the body
1319 @var{forms} of @code{labels} itself, and in the bodies of
1320 the functions themselves. Thus, @code{labels} can define
1321 local recursive functions, or mutually-recursive sets of
1322 functions.
1323
1324 A ``reference'' to a function name is either a call to that
1325 function, or a use of its name quoted by @code{quote} or
1326 @code{function} to be passed on to, say, @code{mapcar}.
1327 @end defmac
1328
1329 @node Macro Bindings
1330 @subsection Macro Bindings
1331
1332 @noindent
1333 These forms create local macros and ``symbol macros''.
1334
1335 @defmac cl-macrolet (bindings@dots{}) forms@dots{}
1336 This form is analogous to @code{flet}, but for macros instead of
1337 functions. Each @var{binding} is a list of the same form as the
1338 arguments to @code{cl-defmacro} (i.e., a macro name, argument list,
1339 and macro-expander forms). The macro is defined accordingly for
1340 use within the body of the @code{cl-macrolet}.
1341
1342 @c FIXME this should be modified to say ``even when lexical-binding
1343 @c is code{nil}'', but is that true? The doc of cl-macrolet just
1344 @c refers us to cl-flet, which refers to cl-labels, which says that it
1345 @c behaves differently according to whether l-b is true or not.
1346 Because of the nature of macros, @code{cl-macrolet} is lexically
1347 scoped even in Emacs Lisp: The @code{cl-macrolet} binding will
1348 affect only calls that appear physically within the body
1349 @var{forms}, possibly after expansion of other macros in the
1350 body.
1351 @end defmac
1352
1353 @defmac cl-symbol-macrolet (bindings@dots{}) forms@dots{}
1354 This form creates @dfn{symbol macros}, which are macros that look
1355 like variable references rather than function calls. Each
1356 @var{binding} is a list @samp{(@var{var} @var{expansion})};
1357 any reference to @var{var} within the body @var{forms} is
1358 replaced by @var{expansion}.
1359
1360 @example
1361 (setq bar '(5 . 9))
1362 (cl-symbol-macrolet ((foo (car bar)))
1363 (cl-incf foo))
1364 bar
1365 @result{} (6 . 9)
1366 @end example
1367
1368 A @code{setq} of a symbol macro is treated the same as a @code{setf}.
1369 I.e., @code{(setq foo 4)} in the above would be equivalent to
1370 @code{(setf foo 4)}, which in turn expands to @code{(setf (car bar) 4)}.
1371
1372 Likewise, a @code{let} or @code{let*} binding a symbol macro is
1373 treated like a @code{letf} or @code{cl-letf*}. This differs from true
1374 @c FIXME does it work like this in Emacs with lexical-binding = t?
1375 Common Lisp, where the rules of lexical scoping cause a @code{let}
1376 binding to shadow a @code{cl-symbol-macrolet} binding. In this package,
1377 @c FIXME obsolete.
1378 only @code{lexical-let} and @code{lexical-let*} will shadow a symbol
1379 macro.
1380
1381 There is no analogue of @code{defmacro} for symbol macros; all symbol
1382 macros are local. A typical use of @code{cl-symbol-macrolet} is in the
1383 expansion of another macro:
1384
1385 @example
1386 (cl-defmacro my-dolist ((x list) &rest body)
1387 (let ((var (gensym)))
1388 (list 'cl-loop 'for var 'on list 'do
1389 (cl-list* 'cl-symbol-macrolet
1390 (list (list x (list 'car var)))
1391 body))))
1392
1393 (setq mylist '(1 2 3 4))
1394 (my-dolist (x mylist) (cl-incf x))
1395 mylist
1396 @result{} (2 3 4 5)
1397 @end example
1398
1399 @noindent
1400 In this example, the @code{my-dolist} macro is similar to @code{dolist}
1401 (@pxref{Iteration}) except that the variable @code{x} becomes a true
1402 reference onto the elements of the list. The @code{my-dolist} call
1403 shown here expands to
1404
1405 @example
1406 (cl-loop for G1234 on mylist do
1407 (cl-symbol-macrolet ((x (car G1234)))
1408 (cl-incf x)))
1409 @end example
1410
1411 @noindent
1412 which in turn expands to
1413
1414 @example
1415 (cl-loop for G1234 on mylist do (cl-incf (car G1234)))
1416 @end example
1417
1418 @xref{Loop Facility}, for a description of the @code{cl-loop} macro.
1419 This package defines a nonstandard @code{in-ref} loop clause that
1420 works much like @code{my-dolist}.
1421 @end defmac
1422
1423 @node Conditionals
1424 @section Conditionals
1425
1426 @noindent
1427 These conditional forms augment Emacs Lisp's simple @code{if},
1428 @code{and}, @code{or}, and @code{cond} forms.
1429
1430 @defmac cl-case keyform clause@dots{}
1431 This macro evaluates @var{keyform}, then compares it with the key
1432 values listed in the various @var{clause}s. Whichever clause matches
1433 the key is executed; comparison is done by @code{eql}. If no clause
1434 matches, the @code{cl-case} form returns @code{nil}. The clauses are
1435 of the form
1436
1437 @example
1438 (@var{keylist} @var{body-forms}@dots{})
1439 @end example
1440
1441 @noindent
1442 where @var{keylist} is a list of key values. If there is exactly
1443 one value, and it is not a cons cell or the symbol @code{nil} or
1444 @code{t}, then it can be used by itself as a @var{keylist} without
1445 being enclosed in a list. All key values in the @code{cl-case} form
1446 must be distinct. The final clauses may use @code{t} in place of
1447 a @var{keylist} to indicate a default clause that should be taken
1448 if none of the other clauses match. (The symbol @code{otherwise}
1449 is also recognized in place of @code{t}. To make a clause that
1450 matches the actual symbol @code{t}, @code{nil}, or @code{otherwise},
1451 enclose the symbol in a list.)
1452
1453 For example, this expression reads a keystroke, then does one of
1454 four things depending on whether it is an @samp{a}, a @samp{b},
1455 a @key{RET} or @kbd{C-j}, or anything else.
1456
1457 @example
1458 (cl-case (read-char)
1459 (?a (do-a-thing))
1460 (?b (do-b-thing))
1461 ((?\r ?\n) (do-ret-thing))
1462 (t (do-other-thing)))
1463 @end example
1464 @end defmac
1465
1466 @defmac cl-ecase keyform clause@dots{}
1467 This macro is just like @code{cl-case}, except that if the key does
1468 not match any of the clauses, an error is signaled rather than
1469 simply returning @code{nil}.
1470 @end defmac
1471
1472 @defmac cl-typecase keyform clause@dots{}
1473 This macro is a version of @code{cl-case} that checks for types
1474 rather than values. Each @var{clause} is of the form
1475 @samp{(@var{type} @var{body}...)}. @xref{Type Predicates},
1476 for a description of type specifiers. For example,
1477
1478 @example
1479 (cl-typecase x
1480 (integer (munch-integer x))
1481 (float (munch-float x))
1482 (string (munch-integer (string-to-int x)))
1483 (t (munch-anything x)))
1484 @end example
1485
1486 The type specifier @code{t} matches any type of object; the word
1487 @code{otherwise} is also allowed. To make one clause match any of
1488 several types, use an @code{(or ...)} type specifier.
1489 @end defmac
1490
1491 @defmac cl-etypecase keyform clause@dots{}
1492 This macro is just like @code{cl-typecase}, except that if the key does
1493 not match any of the clauses, an error is signaled rather than
1494 simply returning @code{nil}.
1495 @end defmac
1496
1497 @node Blocks and Exits
1498 @section Blocks and Exits
1499
1500 @noindent
1501 Common Lisp @dfn{blocks} provide a non-local exit mechanism very
1502 similar to @code{catch} and @code{throw}, but lexically rather than
1503 dynamically scoped. This package actually implements @code{cl-block}
1504 in terms of @code{catch}; however, the lexical scoping allows the
1505 optimizing byte-compiler to omit the costly @code{catch} step if the
1506 body of the block does not actually @code{cl-return-from} the block.
1507
1508 @defmac cl-block name forms@dots{}
1509 The @var{forms} are evaluated as if by a @code{progn}. However,
1510 if any of the @var{forms} execute @code{(cl-return-from @var{name})},
1511 they will jump out and return directly from the @code{cl-block} form.
1512 The @code{cl-block} returns the result of the last @var{form} unless
1513 a @code{cl-return-from} occurs.
1514
1515 The @code{cl-block}/@code{cl-return-from} mechanism is quite similar to
1516 the @code{catch}/@code{throw} mechanism. The main differences are
1517 that block @var{name}s are unevaluated symbols, rather than forms
1518 (such as quoted symbols) which evaluate to a tag at run-time; and
1519 also that blocks are lexically scoped whereas @code{catch}/@code{throw}
1520 are dynamically scoped. This means that functions called from the
1521 body of a @code{catch} can also @code{throw} to the @code{catch},
1522 but the @code{cl-return-from} referring to a block name must appear
1523 physically within the @var{forms} that make up the body of the block.
1524 They may not appear within other called functions, although they may
1525 appear within macro expansions or @code{lambda}s in the body. Block
1526 names and @code{catch} names form independent name-spaces.
1527
1528 In true Common Lisp, @code{defun} and @code{defmacro} surround
1529 the function or expander bodies with implicit blocks with the
1530 same name as the function or macro. This does not occur in Emacs
1531 Lisp, but this package provides @code{cl-defun} and @code{cl-defmacro}
1532 forms which do create the implicit block.
1533
1534 The Common Lisp looping constructs defined by this package,
1535 such as @code{cl-loop} and @code{cl-dolist}, also create implicit blocks
1536 just as in Common Lisp.
1537
1538 Because they are implemented in terms of Emacs Lisp @code{catch}
1539 and @code{throw}, blocks have the same overhead as actual
1540 @code{catch} constructs (roughly two function calls). However,
1541 the optimizing byte compiler will optimize away the @code{catch}
1542 if the block does
1543 not in fact contain any @code{cl-return} or @code{cl-return-from} calls
1544 that jump to it. This means that @code{cl-do} loops and @code{cl-defun}
1545 functions which don't use @code{cl-return} don't pay the overhead to
1546 support it.
1547 @end defmac
1548
1549 @defmac cl-return-from name [result]
1550 This macro returns from the block named @var{name}, which must be
1551 an (unevaluated) symbol. If a @var{result} form is specified, it
1552 is evaluated to produce the result returned from the @code{block}.
1553 Otherwise, @code{nil} is returned.
1554 @end defmac
1555
1556 @defmac cl-return [result]
1557 This macro is exactly like @code{(cl-return-from nil @var{result})}.
1558 Common Lisp loops like @code{cl-do} and @code{cl-dolist} implicitly enclose
1559 themselves in @code{nil} blocks.
1560 @end defmac
1561
1562 @node Iteration
1563 @section Iteration
1564
1565 @noindent
1566 The macros described here provide more sophisticated, high-level
1567 looping constructs to complement Emacs Lisp's basic @code{while}
1568 loop.
1569
1570 @defmac cl-loop forms@dots{}
1571 The @code{CL} package supports both the simple, old-style meaning of
1572 @code{loop} and the extremely powerful and flexible feature known as
1573 the @dfn{Loop Facility} or @dfn{Loop Macro}. This more advanced
1574 facility is discussed in the following section; @pxref{Loop Facility}.
1575 The simple form of @code{loop} is described here.
1576
1577 If @code{cl-loop} is followed by zero or more Lisp expressions,
1578 then @code{(cl-loop @var{exprs}@dots{})} simply creates an infinite
1579 loop executing the expressions over and over. The loop is
1580 enclosed in an implicit @code{nil} block. Thus,
1581
1582 @example
1583 (cl-loop (foo) (if (no-more) (return 72)) (bar))
1584 @end example
1585
1586 @noindent
1587 is exactly equivalent to
1588
1589 @example
1590 (cl-block nil (while t (foo) (if (no-more) (return 72)) (bar)))
1591 @end example
1592
1593 If any of the expressions are plain symbols, the loop is instead
1594 interpreted as a Loop Macro specification as described later.
1595 (This is not a restriction in practice, since a plain symbol
1596 in the above notation would simply access and throw away the
1597 value of a variable.)
1598 @end defmac
1599
1600 @defmac cl-do (spec@dots{}) (end-test [result@dots{}]) forms@dots{}
1601 This macro creates a general iterative loop. Each @var{spec} is
1602 of the form
1603
1604 @example
1605 (@var{var} [@var{init} [@var{step}]])
1606 @end example
1607
1608 The loop works as follows: First, each @var{var} is bound to the
1609 associated @var{init} value as if by a @code{let} form. Then, in
1610 each iteration of the loop, the @var{end-test} is evaluated; if
1611 true, the loop is finished. Otherwise, the body @var{forms} are
1612 evaluated, then each @var{var} is set to the associated @var{step}
1613 expression (as if by a @code{cl-psetq} form) and the next iteration
1614 begins. Once the @var{end-test} becomes true, the @var{result}
1615 forms are evaluated (with the @var{var}s still bound to their
1616 values) to produce the result returned by @code{cl-do}.
1617
1618 The entire @code{cl-do} loop is enclosed in an implicit @code{nil}
1619 block, so that you can use @code{(cl-return)} to break out of the
1620 loop at any time.
1621
1622 If there are no @var{result} forms, the loop returns @code{nil}.
1623 If a given @var{var} has no @var{step} form, it is bound to its
1624 @var{init} value but not otherwise modified during the @code{cl-do}
1625 loop (unless the code explicitly modifies it); this case is just
1626 a shorthand for putting a @code{(let ((@var{var} @var{init})) @dots{})}
1627 around the loop. If @var{init} is also omitted it defaults to
1628 @code{nil}, and in this case a plain @samp{@var{var}} can be used
1629 in place of @samp{(@var{var})}, again following the analogy with
1630 @code{let}.
1631
1632 This example (from Steele) illustrates a loop which applies the
1633 function @code{f} to successive pairs of values from the lists
1634 @code{foo} and @code{bar}; it is equivalent to the call
1635 @code{(cl-mapcar 'f foo bar)}. Note that this loop has no body
1636 @var{forms} at all, performing all its work as side effects of
1637 the rest of the loop.
1638
1639 @example
1640 (cl-do ((x foo (cdr x))
1641 (y bar (cdr y))
1642 (z nil (cons (f (car x) (car y)) z)))
1643 ((or (null x) (null y))
1644 (nreverse z)))
1645 @end example
1646 @end defmac
1647
1648 @defmac cl-do* (spec@dots{}) (end-test [result@dots{}]) forms@dots{}
1649 This is to @code{cl-do} what @code{let*} is to @code{let}. In
1650 particular, the initial values are bound as if by @code{let*}
1651 rather than @code{let}, and the steps are assigned as if by
1652 @code{setq} rather than @code{cl-psetq}.
1653
1654 Here is another way to write the above loop:
1655
1656 @example
1657 (cl-do* ((xp foo (cdr xp))
1658 (yp bar (cdr yp))
1659 (x (car xp) (car xp))
1660 (y (car yp) (car yp))
1661 z)
1662 ((or (null xp) (null yp))
1663 (nreverse z))
1664 (push (f x y) z))
1665 @end example
1666 @end defmac
1667
1668 @defmac cl-dolist (var list [result]) forms@dots{}
1669 This is a more specialized loop which iterates across the elements
1670 of a list. @var{list} should evaluate to a list; the body @var{forms}
1671 are executed with @var{var} bound to each element of the list in
1672 turn. Finally, the @var{result} form (or @code{nil}) is evaluated
1673 with @var{var} bound to @code{nil} to produce the result returned by
1674 the loop. Unlike with Emacs's built in @code{dolist}, the loop is
1675 surrounded by an implicit @code{nil} block.
1676 @end defmac
1677
1678 @defmac cl-dotimes (var count [result]) forms@dots{}
1679 This is a more specialized loop which iterates a specified number
1680 of times. The body is executed with @var{var} bound to the integers
1681 from zero (inclusive) to @var{count} (exclusive), in turn. Then
1682 the @code{result} form is evaluated with @var{var} bound to the total
1683 number of iterations that were done (i.e., @code{(max 0 @var{count})})
1684 to get the return value for the loop form. Unlike with Emacs's built in
1685 @code{dolist}, the loop is surrounded by an implicit @code{nil} block.
1686 @end defmac
1687
1688 @defmac cl-do-symbols (var [obarray [result]]) forms@dots{}
1689 This loop iterates over all interned symbols. If @var{obarray}
1690 is specified and is not @code{nil}, it loops over all symbols in
1691 that obarray. For each symbol, the body @var{forms} are evaluated
1692 with @var{var} bound to that symbol. The symbols are visited in
1693 an unspecified order. Afterward the @var{result} form, if any,
1694 is evaluated (with @var{var} bound to @code{nil}) to get the return
1695 value. The loop is surrounded by an implicit @code{nil} block.
1696 @end defmac
1697
1698 @defmac cl-do-all-symbols (var [result]) forms@dots{}
1699 This is identical to @code{cl-do-symbols} except that the @var{obarray}
1700 argument is omitted; it always iterates over the default obarray.
1701 @end defmac
1702
1703 @xref{Mapping over Sequences}, for some more functions for
1704 iterating over vectors or lists.
1705
1706 @node Loop Facility
1707 @section Loop Facility
1708
1709 @noindent
1710 A common complaint with Lisp's traditional looping constructs is
1711 that they are either too simple and limited, such as Common Lisp's
1712 @code{dotimes} or Emacs Lisp's @code{while}, or too unreadable and
1713 obscure, like Common Lisp's @code{do} loop.
1714
1715 To remedy this, recent versions of Common Lisp have added a new
1716 construct called the ``Loop Facility'' or ``@code{loop} macro'',
1717 with an easy-to-use but very powerful and expressive syntax.
1718
1719 @menu
1720 * Loop Basics:: @code{cl-loop} macro, basic clause structure.
1721 * Loop Examples:: Working examples of @code{cl-loop} macro.
1722 * For Clauses:: Clauses introduced by @code{for} or @code{as}.
1723 * Iteration Clauses:: @code{repeat}, @code{while}, @code{thereis}, etc.
1724 * Accumulation Clauses:: @code{collect}, @code{sum}, @code{maximize}, etc.
1725 * Other Clauses:: @code{with}, @code{if}, @code{initially}, @code{finally}.
1726 @end menu
1727
1728 @node Loop Basics
1729 @subsection Loop Basics
1730
1731 @noindent
1732 The @code{cl-loop} macro essentially creates a mini-language within
1733 Lisp that is specially tailored for describing loops. While this
1734 language is a little strange-looking by the standards of regular Lisp,
1735 it turns out to be very easy to learn and well-suited to its purpose.
1736
1737 Since @code{cl-loop} is a macro, all parsing of the loop language
1738 takes place at byte-compile time; compiled @code{cl-loop}s are just
1739 as efficient as the equivalent @code{while} loops written longhand.
1740
1741 @defmac cl-loop clauses@dots{}
1742 A loop construct consists of a series of @var{clause}s, each
1743 introduced by a symbol like @code{for} or @code{do}. Clauses
1744 are simply strung together in the argument list of @code{cl-loop},
1745 with minimal extra parentheses. The various types of clauses
1746 specify initializations, such as the binding of temporary
1747 variables, actions to be taken in the loop, stepping actions,
1748 and final cleanup.
1749
1750 Common Lisp specifies a certain general order of clauses in a
1751 loop:
1752
1753 @example
1754 (cl-loop @var{name-clause}
1755 @var{var-clauses}@dots{}
1756 @var{action-clauses}@dots{})
1757 @end example
1758
1759 The @var{name-clause} optionally gives a name to the implicit
1760 block that surrounds the loop. By default, the implicit block
1761 is named @code{nil}. The @var{var-clauses} specify what
1762 variables should be bound during the loop, and how they should
1763 be modified or iterated throughout the course of the loop. The
1764 @var{action-clauses} are things to be done during the loop, such
1765 as computing, collecting, and returning values.
1766
1767 The Emacs version of the @code{cl-loop} macro is less restrictive about
1768 the order of clauses, but things will behave most predictably if
1769 you put the variable-binding clauses @code{with}, @code{for}, and
1770 @code{repeat} before the action clauses. As in Common Lisp,
1771 @code{initially} and @code{finally} clauses can go anywhere.
1772
1773 Loops generally return @code{nil} by default, but you can cause
1774 them to return a value by using an accumulation clause like
1775 @code{collect}, an end-test clause like @code{always}, or an
1776 explicit @code{return} clause to jump out of the implicit block.
1777 (Because the loop body is enclosed in an implicit block, you can
1778 also use regular Lisp @code{cl-return} or @code{cl-return-from} to
1779 break out of the loop.)
1780 @end defmac
1781
1782 The following sections give some examples of the Loop Macro in
1783 action, and describe the particular loop clauses in great detail.
1784 Consult the second edition of Steele's @dfn{Common Lisp, the Language},
1785 for additional discussion and examples of the @code{loop} macro.
1786
1787 @node Loop Examples
1788 @subsection Loop Examples
1789
1790 @noindent
1791 Before listing the full set of clauses that are allowed, let's
1792 look at a few example loops just to get a feel for the @code{cl-loop}
1793 language.
1794
1795 @example
1796 (cl-loop for buf in (buffer-list)
1797 collect (buffer-file-name buf))
1798 @end example
1799
1800 @noindent
1801 This loop iterates over all Emacs buffers, using the list
1802 returned by @code{buffer-list}. For each buffer @var{buf},
1803 it calls @code{buffer-file-name} and collects the results into
1804 a list, which is then returned from the @code{cl-loop} construct.
1805 The result is a list of the file names of all the buffers in
1806 Emacs's memory. The words @code{for}, @code{in}, and @code{collect}
1807 are reserved words in the @code{cl-loop} language.
1808
1809 @example
1810 (cl-loop repeat 20 do (insert "Yowsa\n"))
1811 @end example
1812
1813 @noindent
1814 This loop inserts the phrase ``Yowsa'' twenty times in the
1815 current buffer.
1816
1817 @example
1818 (cl-loop until (eobp) do (munch-line) (forward-line 1))
1819 @end example
1820
1821 @noindent
1822 This loop calls @code{munch-line} on every line until the end
1823 of the buffer. If point is already at the end of the buffer,
1824 the loop exits immediately.
1825
1826 @example
1827 (cl-loop do (munch-line) until (eobp) do (forward-line 1))
1828 @end example
1829
1830 @noindent
1831 This loop is similar to the above one, except that @code{munch-line}
1832 is always called at least once.
1833
1834 @example
1835 (cl-loop for x from 1 to 100
1836 for y = (* x x)
1837 until (>= y 729)
1838 finally return (list x (= y 729)))
1839 @end example
1840
1841 @noindent
1842 This more complicated loop searches for a number @code{x} whose
1843 square is 729. For safety's sake it only examines @code{x}
1844 values up to 100; dropping the phrase @samp{to 100} would
1845 cause the loop to count upwards with no limit. The second
1846 @code{for} clause defines @code{y} to be the square of @code{x}
1847 within the loop; the expression after the @code{=} sign is
1848 reevaluated each time through the loop. The @code{until}
1849 clause gives a condition for terminating the loop, and the
1850 @code{finally} clause says what to do when the loop finishes.
1851 (This particular example was written less concisely than it
1852 could have been, just for the sake of illustration.)
1853
1854 Note that even though this loop contains three clauses (two
1855 @code{for}s and an @code{until}) that would have been enough to
1856 define loops all by themselves, it still creates a single loop
1857 rather than some sort of triple-nested loop. You must explicitly
1858 nest your @code{cl-loop} constructs if you want nested loops.
1859
1860 @node For Clauses
1861 @subsection For Clauses
1862
1863 @noindent
1864 Most loops are governed by one or more @code{for} clauses.
1865 A @code{for} clause simultaneously describes variables to be
1866 bound, how those variables are to be stepped during the loop,
1867 and usually an end condition based on those variables.
1868
1869 The word @code{as} is a synonym for the word @code{for}. This
1870 word is followed by a variable name, then a word like @code{from}
1871 or @code{across} that describes the kind of iteration desired.
1872 In Common Lisp, the phrase @code{being the} sometimes precedes
1873 the type of iteration; in this package both @code{being} and
1874 @code{the} are optional. The word @code{each} is a synonym
1875 for @code{the}, and the word that follows it may be singular
1876 or plural: @samp{for x being the elements of y} or
1877 @samp{for x being each element of y}. Which form you use
1878 is purely a matter of style.
1879
1880 The variable is bound around the loop as if by @code{let}:
1881
1882 @example
1883 (setq i 'happy)
1884 (cl-loop for i from 1 to 10 do (do-something-with i))
1885 i
1886 @result{} happy
1887 @end example
1888
1889 @table @code
1890 @item for @var{var} from @var{expr1} to @var{expr2} by @var{expr3}
1891 This type of @code{for} clause creates a counting loop. Each of
1892 the three sub-terms is optional, though there must be at least one
1893 term so that the clause is marked as a counting clause.
1894
1895 The three expressions are the starting value, the ending value, and
1896 the step value, respectively, of the variable. The loop counts
1897 upwards by default (@var{expr3} must be positive), from @var{expr1}
1898 to @var{expr2} inclusively. If you omit the @code{from} term, the
1899 loop counts from zero; if you omit the @code{to} term, the loop
1900 counts forever without stopping (unless stopped by some other
1901 loop clause, of course); if you omit the @code{by} term, the loop
1902 counts in steps of one.
1903
1904 You can replace the word @code{from} with @code{upfrom} or
1905 @code{downfrom} to indicate the direction of the loop. Likewise,
1906 you can replace @code{to} with @code{upto} or @code{downto}.
1907 For example, @samp{for x from 5 downto 1} executes five times
1908 with @code{x} taking on the integers from 5 down to 1 in turn.
1909 Also, you can replace @code{to} with @code{below} or @code{above},
1910 which are like @code{upto} and @code{downto} respectively except
1911 that they are exclusive rather than inclusive limits:
1912
1913 @example
1914 (cl-loop for x to 10 collect x)
1915 @result{} (0 1 2 3 4 5 6 7 8 9 10)
1916 (cl-loop for x below 10 collect x)
1917 @result{} (0 1 2 3 4 5 6 7 8 9)
1918 @end example
1919
1920 The @code{by} value is always positive, even for downward-counting
1921 loops. Some sort of @code{from} value is required for downward
1922 loops; @samp{for x downto 5} is not a valid loop clause all by
1923 itself.
1924
1925 @item for @var{var} in @var{list} by @var{function}
1926 This clause iterates @var{var} over all the elements of @var{list},
1927 in turn. If you specify the @code{by} term, then @var{function}
1928 is used to traverse the list instead of @code{cdr}; it must be a
1929 function taking one argument. For example:
1930
1931 @example
1932 (cl-loop for x in '(1 2 3 4 5 6) collect (* x x))
1933 @result{} (1 4 9 16 25 36)
1934 (cl-loop for x in '(1 2 3 4 5 6) by 'cddr collect (* x x))
1935 @result{} (1 9 25)
1936 @end example
1937
1938 @item for @var{var} on @var{list} by @var{function}
1939 This clause iterates @var{var} over all the cons cells of @var{list}.
1940
1941 @example
1942 (cl-loop for x on '(1 2 3 4) collect x)
1943 @result{} ((1 2 3 4) (2 3 4) (3 4) (4))
1944 @end example
1945
1946 With @code{by}, there is no real reason that the @code{on} expression
1947 must be a list. For example:
1948
1949 @example
1950 (cl-loop for x on first-animal by 'next-animal collect x)
1951 @end example
1952
1953 @noindent
1954 where @code{(next-animal x)} takes an ``animal'' @var{x} and returns
1955 the next in the (assumed) sequence of animals, or @code{nil} if
1956 @var{x} was the last animal in the sequence.
1957
1958 @item for @var{var} in-ref @var{list} by @var{function}
1959 This is like a regular @code{in} clause, but @var{var} becomes
1960 a @code{setf}-able ``reference'' onto the elements of the list
1961 rather than just a temporary variable. For example,
1962
1963 @example
1964 (cl-loop for x in-ref my-list do (cl-incf x))
1965 @end example
1966
1967 @noindent
1968 increments every element of @code{my-list} in place. This clause
1969 is an extension to standard Common Lisp.
1970
1971 @item for @var{var} across @var{array}
1972 This clause iterates @var{var} over all the elements of @var{array},
1973 which may be a vector or a string.
1974
1975 @example
1976 (cl-loop for x across "aeiou"
1977 do (use-vowel (char-to-string x)))
1978 @end example
1979
1980 @item for @var{var} across-ref @var{array}
1981 This clause iterates over an array, with @var{var} a @code{setf}-able
1982 reference onto the elements; see @code{in-ref} above.
1983
1984 @item for @var{var} being the elements of @var{sequence}
1985 This clause iterates over the elements of @var{sequence}, which may
1986 be a list, vector, or string. Since the type must be determined
1987 at run-time, this is somewhat less efficient than @code{in} or
1988 @code{across}. The clause may be followed by the additional term
1989 @samp{using (index @var{var2})} to cause @var{var2} to be bound to
1990 the successive indices (starting at 0) of the elements.
1991
1992 This clause type is taken from older versions of the @code{loop} macro,
1993 and is not present in modern Common Lisp. The @samp{using (sequence ...)}
1994 term of the older macros is not supported.
1995
1996 @item for @var{var} being the elements of-ref @var{sequence}
1997 This clause iterates over a sequence, with @var{var} a @code{setf}-able
1998 reference onto the elements; see @code{in-ref} above.
1999
2000 @item for @var{var} being the symbols [of @var{obarray}]
2001 This clause iterates over symbols, either over all interned symbols
2002 or over all symbols in @var{obarray}. The loop is executed with
2003 @var{var} bound to each symbol in turn. The symbols are visited in
2004 an unspecified order.
2005
2006 As an example,
2007
2008 @example
2009 (cl-loop for sym being the symbols
2010 when (fboundp sym)
2011 when (string-match "^map" (symbol-name sym))
2012 collect sym)
2013 @end example
2014
2015 @noindent
2016 returns a list of all the functions whose names begin with @samp{map}.
2017
2018 The Common Lisp words @code{external-symbols} and @code{present-symbols}
2019 are also recognized but are equivalent to @code{symbols} in Emacs Lisp.
2020
2021 Due to a minor implementation restriction, it will not work to have
2022 more than one @code{for} clause iterating over symbols, hash tables,
2023 keymaps, overlays, or intervals in a given @code{cl-loop}. Fortunately,
2024 it would rarely if ever be useful to do so. It @emph{is} valid to mix
2025 one of these types of clauses with other clauses like @code{for ... to}
2026 or @code{while}.
2027
2028 @item for @var{var} being the hash-keys of @var{hash-table}
2029 @itemx for @var{var} being the hash-values of @var{hash-table}
2030 This clause iterates over the entries in @var{hash-table} with
2031 @var{var} bound to each key, or value. A @samp{using} clause can bind
2032 a second variable to the opposite part.
2033
2034 @example
2035 (cl-loop for k being the hash-keys of h
2036 using (hash-values v)
2037 do
2038 (message "key %S -> value %S" k v))
2039 @end example
2040
2041 @item for @var{var} being the key-codes of @var{keymap}
2042 @itemx for @var{var} being the key-bindings of @var{keymap}
2043 This clause iterates over the entries in @var{keymap}.
2044 The iteration does not enter nested keymaps but does enter inherited
2045 (parent) keymaps.
2046 A @code{using} clause can access both the codes and the bindings
2047 together.
2048
2049 @example
2050 (cl-loop for c being the key-codes of (current-local-map)
2051 using (key-bindings b)
2052 do
2053 (message "key %S -> binding %S" c b))
2054 @end example
2055
2056
2057 @item for @var{var} being the key-seqs of @var{keymap}
2058 This clause iterates over all key sequences defined by @var{keymap}
2059 and its nested keymaps, where @var{var} takes on values which are
2060 vectors. The strings or vectors
2061 are reused for each iteration, so you must copy them if you wish to keep
2062 them permanently. You can add a @samp{using (key-bindings ...)}
2063 clause to get the command bindings as well.
2064
2065 @item for @var{var} being the overlays [of @var{buffer}] @dots{}
2066 This clause iterates over the ``overlays'' of a buffer
2067 (the clause @code{extents} is synonymous
2068 with @code{overlays}). If the @code{of} term is omitted, the current
2069 buffer is used.
2070 This clause also accepts optional @samp{from @var{pos}} and
2071 @samp{to @var{pos}} terms, limiting the clause to overlays which
2072 overlap the specified region.
2073
2074 @item for @var{var} being the intervals [of @var{buffer}] @dots{}
2075 This clause iterates over all intervals of a buffer with constant
2076 text properties. The variable @var{var} will be bound to conses
2077 of start and end positions, where one start position is always equal
2078 to the previous end position. The clause allows @code{of},
2079 @code{from}, @code{to}, and @code{property} terms, where the latter
2080 term restricts the search to just the specified property. The
2081 @code{of} term may specify either a buffer or a string.
2082
2083 @item for @var{var} being the frames
2084 This clause iterates over all Emacs frames. The clause @code{screens} is
2085 a synonym for @code{frames}. The frames are visited in
2086 @code{next-frame} order starting from @code{selected-frame}.
2087
2088 @item for @var{var} being the windows [of @var{frame}]
2089 This clause iterates over the windows (in the Emacs sense) of
2090 the current frame, or of the specified @var{frame}. It visits windows
2091 in @code{next-window} order starting from @code{selected-window}
2092 (or @code{frame-selected-window} if you specify @var{frame}).
2093 This clause treats the minibuffer window in the same way as
2094 @code{next-window} does. For greater flexibility, consider using
2095 @code{walk-windows} instead.
2096
2097 @item for @var{var} being the buffers
2098 This clause iterates over all buffers in Emacs. It is equivalent
2099 to @samp{for @var{var} in (buffer-list)}.
2100
2101 @item for @var{var} = @var{expr1} then @var{expr2}
2102 This clause does a general iteration. The first time through
2103 the loop, @var{var} will be bound to @var{expr1}. On the second
2104 and successive iterations it will be set by evaluating @var{expr2}
2105 (which may refer to the old value of @var{var}). For example,
2106 these two loops are effectively the same:
2107
2108 @example
2109 (cl-loop for x on my-list by 'cddr do ...)
2110 (cl-loop for x = my-list then (cddr x) while x do ...)
2111 @end example
2112
2113 Note that this type of @code{for} clause does not imply any sort
2114 of terminating condition; the above example combines it with a
2115 @code{while} clause to tell when to end the loop.
2116
2117 If you omit the @code{then} term, @var{expr1} is used both for
2118 the initial setting and for successive settings:
2119
2120 @example
2121 (cl-loop for x = (random) when (> x 0) return x)
2122 @end example
2123
2124 @noindent
2125 This loop keeps taking random numbers from the @code{(random)}
2126 function until it gets a positive one, which it then returns.
2127 @end table
2128
2129 If you include several @code{for} clauses in a row, they are
2130 treated sequentially (as if by @code{let*} and @code{setq}).
2131 You can instead use the word @code{and} to link the clauses,
2132 in which case they are processed in parallel (as if by @code{let}
2133 and @code{cl-psetq}).
2134
2135 @example
2136 (cl-loop for x below 5 for y = nil then x collect (list x y))
2137 @result{} ((0 nil) (1 1) (2 2) (3 3) (4 4))
2138 (cl-loop for x below 5 and y = nil then x collect (list x y))
2139 @result{} ((0 nil) (1 0) (2 1) (3 2) (4 3))
2140 @end example
2141
2142 @noindent
2143 In the first loop, @code{y} is set based on the value of @code{x}
2144 that was just set by the previous clause; in the second loop,
2145 @code{x} and @code{y} are set simultaneously so @code{y} is set
2146 based on the value of @code{x} left over from the previous time
2147 through the loop.
2148
2149 Another feature of the @code{cl-loop} macro is @dfn{destructuring},
2150 similar in concept to the destructuring provided by @code{defmacro}.
2151 The @var{var} part of any @code{for} clause can be given as a list
2152 of variables instead of a single variable. The values produced
2153 during loop execution must be lists; the values in the lists are
2154 stored in the corresponding variables.
2155
2156 @example
2157 (cl-loop for (x y) in '((2 3) (4 5) (6 7)) collect (+ x y))
2158 @result{} (5 9 13)
2159 @end example
2160
2161 In loop destructuring, if there are more values than variables
2162 the trailing values are ignored, and if there are more variables
2163 than values the trailing variables get the value @code{nil}.
2164 If @code{nil} is used as a variable name, the corresponding
2165 values are ignored. Destructuring may be nested, and dotted
2166 lists of variables like @code{(x . y)} are allowed, so for example
2167 to process an alist
2168
2169 @example
2170 (cl-loop for (key . value) in '((a . 1) (b . 2))
2171 collect value)
2172 @result{} (1 2)
2173 @end example
2174
2175 @node Iteration Clauses
2176 @subsection Iteration Clauses
2177
2178 @noindent
2179 Aside from @code{for} clauses, there are several other loop clauses
2180 that control the way the loop operates. They might be used by
2181 themselves, or in conjunction with one or more @code{for} clauses.
2182
2183 @table @code
2184 @item repeat @var{integer}
2185 This clause simply counts up to the specified number using an
2186 internal temporary variable. The loops
2187
2188 @example
2189 (cl-loop repeat (1+ n) do ...)
2190 (cl-loop for temp to n do ...)
2191 @end example
2192
2193 @noindent
2194 are identical except that the second one forces you to choose
2195 a name for a variable you aren't actually going to use.
2196
2197 @item while @var{condition}
2198 This clause stops the loop when the specified condition (any Lisp
2199 expression) becomes @code{nil}. For example, the following two
2200 loops are equivalent, except for the implicit @code{nil} block
2201 that surrounds the second one:
2202
2203 @example
2204 (while @var{cond} @var{forms}@dots{})
2205 (cl-loop while @var{cond} do @var{forms}@dots{})
2206 @end example
2207
2208 @item until @var{condition}
2209 This clause stops the loop when the specified condition is true,
2210 i.e., non-@code{nil}.
2211
2212 @item always @var{condition}
2213 This clause stops the loop when the specified condition is @code{nil}.
2214 Unlike @code{while}, it stops the loop using @code{return nil} so that
2215 the @code{finally} clauses are not executed. If all the conditions
2216 were non-@code{nil}, the loop returns @code{t}:
2217
2218 @example
2219 (if (cl-loop for size in size-list always (> size 10))
2220 (some-big-sizes)
2221 (no-big-sizes))
2222 @end example
2223
2224 @item never @var{condition}
2225 This clause is like @code{always}, except that the loop returns
2226 @code{t} if any conditions were false, or @code{nil} otherwise.
2227
2228 @item thereis @var{condition}
2229 This clause stops the loop when the specified form is non-@code{nil};
2230 in this case, it returns that non-@code{nil} value. If all the
2231 values were @code{nil}, the loop returns @code{nil}.
2232 @end table
2233
2234 @node Accumulation Clauses
2235 @subsection Accumulation Clauses
2236
2237 @noindent
2238 These clauses cause the loop to accumulate information about the
2239 specified Lisp @var{form}. The accumulated result is returned
2240 from the loop unless overridden, say, by a @code{return} clause.
2241
2242 @table @code
2243 @item collect @var{form}
2244 This clause collects the values of @var{form} into a list. Several
2245 examples of @code{collect} appear elsewhere in this manual.
2246
2247 The word @code{collecting} is a synonym for @code{collect}, and
2248 likewise for the other accumulation clauses.
2249
2250 @item append @var{form}
2251 This clause collects lists of values into a result list using
2252 @code{append}.
2253
2254 @item nconc @var{form}
2255 This clause collects lists of values into a result list by
2256 destructively modifying the lists rather than copying them.
2257
2258 @item concat @var{form}
2259 This clause concatenates the values of the specified @var{form}
2260 into a string. (It and the following clause are extensions to
2261 standard Common Lisp.)
2262
2263 @item vconcat @var{form}
2264 This clause concatenates the values of the specified @var{form}
2265 into a vector.
2266
2267 @item count @var{form}
2268 This clause counts the number of times the specified @var{form}
2269 evaluates to a non-@code{nil} value.
2270
2271 @item sum @var{form}
2272 This clause accumulates the sum of the values of the specified
2273 @var{form}, which must evaluate to a number.
2274
2275 @item maximize @var{form}
2276 This clause accumulates the maximum value of the specified @var{form},
2277 which must evaluate to a number. The return value is undefined if
2278 @code{maximize} is executed zero times.
2279
2280 @item minimize @var{form}
2281 This clause accumulates the minimum value of the specified @var{form}.
2282 @end table
2283
2284 Accumulation clauses can be followed by @samp{into @var{var}} to
2285 cause the data to be collected into variable @var{var} (which is
2286 automatically @code{let}-bound during the loop) rather than an
2287 unnamed temporary variable. Also, @code{into} accumulations do
2288 not automatically imply a return value. The loop must use some
2289 explicit mechanism, such as @code{finally return}, to return
2290 the accumulated result.
2291
2292 It is valid for several accumulation clauses of the same type to
2293 accumulate into the same place. From Steele:
2294
2295 @example
2296 (cl-loop for name in '(fred sue alice joe june)
2297 for kids in '((bob ken) () () (kris sunshine) ())
2298 collect name
2299 append kids)
2300 @result{} (fred bob ken sue alice joe kris sunshine june)
2301 @end example
2302
2303 @node Other Clauses
2304 @subsection Other Clauses
2305
2306 @noindent
2307 This section describes the remaining loop clauses.
2308
2309 @table @code
2310 @item with @var{var} = @var{value}
2311 This clause binds a variable to a value around the loop, but
2312 otherwise leaves the variable alone during the loop. The following
2313 loops are basically equivalent:
2314
2315 @example
2316 (cl-loop with x = 17 do ...)
2317 (let ((x 17)) (cl-loop do ...))
2318 (cl-loop for x = 17 then x do ...)
2319 @end example
2320
2321 Naturally, the variable @var{var} might be used for some purpose
2322 in the rest of the loop. For example:
2323
2324 @example
2325 (cl-loop for x in my-list with res = nil do (push x res)
2326 finally return res)
2327 @end example
2328
2329 This loop inserts the elements of @code{my-list} at the front of
2330 a new list being accumulated in @code{res}, then returns the
2331 list @code{res} at the end of the loop. The effect is similar
2332 to that of a @code{collect} clause, but the list gets reversed
2333 by virtue of the fact that elements are being pushed onto the
2334 front of @code{res} rather than the end.
2335
2336 If you omit the @code{=} term, the variable is initialized to
2337 @code{nil}. (Thus the @samp{= nil} in the above example is
2338 unnecessary.)
2339
2340 Bindings made by @code{with} are sequential by default, as if
2341 by @code{let*}. Just like @code{for} clauses, @code{with} clauses
2342 can be linked with @code{and} to cause the bindings to be made by
2343 @code{let} instead.
2344
2345 @item if @var{condition} @var{clause}
2346 This clause executes the following loop clause only if the specified
2347 condition is true. The following @var{clause} should be an accumulation,
2348 @code{do}, @code{return}, @code{if}, or @code{unless} clause.
2349 Several clauses may be linked by separating them with @code{and}.
2350 These clauses may be followed by @code{else} and a clause or clauses
2351 to execute if the condition was false. The whole construct may
2352 optionally be followed by the word @code{end} (which may be used to
2353 disambiguate an @code{else} or @code{and} in a nested @code{if}).
2354
2355 The actual non-@code{nil} value of the condition form is available
2356 by the name @code{it} in the ``then'' part. For example:
2357
2358 @example
2359 (setq funny-numbers '(6 13 -1))
2360 @result{} (6 13 -1)
2361 (cl-loop for x below 10
2362 if (oddp x)
2363 collect x into odds
2364 and if (memq x funny-numbers) return (cdr it) end
2365 else
2366 collect x into evens
2367 finally return (vector odds evens))
2368 @result{} [(1 3 5 7 9) (0 2 4 6 8)]
2369 (setq funny-numbers '(6 7 13 -1))
2370 @result{} (6 7 13 -1)
2371 (cl-loop <@r{same thing again}>)
2372 @result{} (13 -1)
2373 @end example
2374
2375 Note the use of @code{and} to put two clauses into the ``then''
2376 part, one of which is itself an @code{if} clause. Note also that
2377 @code{end}, while normally optional, was necessary here to make
2378 it clear that the @code{else} refers to the outermost @code{if}
2379 clause. In the first case, the loop returns a vector of lists
2380 of the odd and even values of @var{x}. In the second case, the
2381 odd number 7 is one of the @code{funny-numbers} so the loop
2382 returns early; the actual returned value is based on the result
2383 of the @code{memq} call.
2384
2385 @item when @var{condition} @var{clause}
2386 This clause is just a synonym for @code{if}.
2387
2388 @item unless @var{condition} @var{clause}
2389 The @code{unless} clause is just like @code{if} except that the
2390 sense of the condition is reversed.
2391
2392 @item named @var{name}
2393 This clause gives a name other than @code{nil} to the implicit
2394 block surrounding the loop. The @var{name} is the symbol to be
2395 used as the block name.
2396
2397 @item initially [do] @var{forms}...
2398 This keyword introduces one or more Lisp forms which will be
2399 executed before the loop itself begins (but after any variables
2400 requested by @code{for} or @code{with} have been bound to their
2401 initial values). @code{initially} clauses can appear anywhere;
2402 if there are several, they are executed in the order they appear
2403 in the loop. The keyword @code{do} is optional.
2404
2405 @item finally [do] @var{forms}...
2406 This introduces Lisp forms which will be executed after the loop
2407 finishes (say, on request of a @code{for} or @code{while}).
2408 @code{initially} and @code{finally} clauses may appear anywhere
2409 in the loop construct, but they are executed (in the specified
2410 order) at the beginning or end, respectively, of the loop.
2411
2412 @item finally return @var{form}
2413 This says that @var{form} should be executed after the loop
2414 is done to obtain a return value. (Without this, or some other
2415 clause like @code{collect} or @code{return}, the loop will simply
2416 return @code{nil}.) Variables bound by @code{for}, @code{with},
2417 or @code{into} will still contain their final values when @var{form}
2418 is executed.
2419
2420 @item do @var{forms}...
2421 The word @code{do} may be followed by any number of Lisp expressions
2422 which are executed as an implicit @code{progn} in the body of the
2423 loop. Many of the examples in this section illustrate the use of
2424 @code{do}.
2425
2426 @item return @var{form}
2427 This clause causes the loop to return immediately. The following
2428 Lisp form is evaluated to give the return value of the @code{loop}
2429 form. The @code{finally} clauses, if any, are not executed.
2430 Of course, @code{return} is generally used inside an @code{if} or
2431 @code{unless}, as its use in a top-level loop clause would mean
2432 the loop would never get to ``loop'' more than once.
2433
2434 The clause @samp{return @var{form}} is equivalent to
2435 @c FIXME cl-do, cl-return?
2436 @samp{do (return @var{form})} (or @code{return-from} if the loop
2437 was named). The @code{return} clause is implemented a bit more
2438 efficiently, though.
2439 @end table
2440
2441 While there is no high-level way to add user extensions to @code{cl-loop}
2442 (comparable to @code{defsetf} for @code{setf}, say), this package
2443 does offer two properties called @code{cl-loop-handler} and
2444 @code{cl-loop-for-handler} which are functions to be called when
2445 a given symbol is encountered as a top-level loop clause or
2446 @code{for} clause, respectively. Consult the source code in
2447 file @file{cl-macs.el} for details.
2448
2449 This package's @code{cl-loop} macro is compatible with that of Common
2450 Lisp, except that a few features are not implemented: @code{loop-finish}
2451 and data-type specifiers. Naturally, the @code{for} clauses which
2452 iterate over keymaps, overlays, intervals, frames, windows, and
2453 buffers are Emacs-specific extensions.
2454
2455 @node Multiple Values
2456 @section Multiple Values
2457
2458 @noindent
2459 Common Lisp functions can return zero or more results. Emacs Lisp
2460 functions, by contrast, always return exactly one result. This
2461 package makes no attempt to emulate Common Lisp multiple return
2462 values; Emacs versions of Common Lisp functions that return more
2463 than one value either return just the first value (as in
2464 @code{cl-compiler-macroexpand}) or return a list of values.
2465 This package @emph{does} define placeholders
2466 for the Common Lisp functions that work with multiple values, but
2467 in Emacs Lisp these functions simply operate on lists instead.
2468 The @code{cl-values} form, for example, is a synonym for @code{list}
2469 in Emacs.
2470
2471 @defmac cl-multiple-value-bind (var@dots{}) values-form forms@dots{}
2472 This form evaluates @var{values-form}, which must return a list of
2473 values. It then binds the @var{var}s to these respective values,
2474 as if by @code{let}, and then executes the body @var{forms}.
2475 If there are more @var{var}s than values, the extra @var{var}s
2476 are bound to @code{nil}. If there are fewer @var{var}s than
2477 values, the excess values are ignored.
2478 @end defmac
2479
2480 @defmac cl-multiple-value-setq (var@dots{}) form
2481 This form evaluates @var{form}, which must return a list of values.
2482 It then sets the @var{var}s to these respective values, as if by
2483 @code{setq}. Extra @var{var}s or values are treated the same as
2484 in @code{cl-multiple-value-bind}.
2485 @end defmac
2486
2487 Since a perfect emulation is not feasible in Emacs Lisp, this
2488 package opts to keep it as simple and predictable as possible.
2489
2490 @node Macros
2491 @chapter Macros
2492
2493 @noindent
2494 This package implements the various Common Lisp features of
2495 @code{defmacro}, such as destructuring, @code{&environment},
2496 and @code{&body}. Top-level @code{&whole} is not implemented
2497 for @code{defmacro} due to technical difficulties.
2498 @xref{Argument Lists}.
2499
2500 Destructuring is made available to the user by way of the
2501 following macro:
2502
2503 @defmac cl-destructuring-bind arglist expr forms@dots{}
2504 This macro expands to code which executes @var{forms}, with
2505 the variables in @var{arglist} bound to the list of values
2506 returned by @var{expr}. The @var{arglist} can include all
2507 the features allowed for @code{defmacro} argument lists,
2508 including destructuring. (The @code{&environment} keyword
2509 is not allowed.) The macro expansion will signal an error
2510 if @var{expr} returns a list of the wrong number of arguments
2511 or with incorrect keyword arguments.
2512 @end defmac
2513
2514 This package also includes the Common Lisp @code{cl-define-compiler-macro}
2515 facility, which allows you to define compile-time expansions and
2516 optimizations for your functions.
2517
2518 @defmac cl-define-compiler-macro name arglist forms@dots{}
2519 This form is similar to @code{defmacro}, except that it only expands
2520 calls to @var{name} at compile-time; calls processed by the Lisp
2521 interpreter are not expanded, nor are they expanded by the
2522 @code{macroexpand} function.
2523
2524 The argument list may begin with a @code{&whole} keyword and a
2525 variable. This variable is bound to the macro-call form itself,
2526 i.e., to a list of the form @samp{(@var{name} @var{args}@dots{})}.
2527 If the macro expander returns this form unchanged, then the
2528 compiler treats it as a normal function call. This allows
2529 compiler macros to work as optimizers for special cases of a
2530 function, leaving complicated cases alone.
2531
2532 For example, here is a simplified version of a definition that
2533 appears as a standard part of this package:
2534
2535 @example
2536 (cl-define-compiler-macro cl-member (&whole form a list &rest keys)
2537 (if (and (null keys)
2538 (eq (car-safe a) 'quote)
2539 (not (floatp-safe (cadr a))))
2540 (list 'memq a list)
2541 form))
2542 @end example
2543
2544 @noindent
2545 This definition causes @code{(cl-member @var{a} @var{list})} to change
2546 to a call to the faster @code{memq} in the common case where @var{a}
2547 is a non-floating-point constant; if @var{a} is anything else, or
2548 if there are any keyword arguments in the call, then the original
2549 @code{cl-member} call is left intact. (The actual compiler macro
2550 for @code{cl-member} optimizes a number of other cases, including
2551 common @code{:test} predicates.)
2552 @end defmac
2553
2554 @defun cl-compiler-macroexpand form
2555 This function is analogous to @code{macroexpand}, except that it
2556 expands compiler macros rather than regular macros. It returns
2557 @var{form} unchanged if it is not a call to a function for which
2558 a compiler macro has been defined, or if that compiler macro
2559 decided to punt by returning its @code{&whole} argument. Like
2560 @code{macroexpand}, it expands repeatedly until it reaches a form
2561 for which no further expansion is possible.
2562 @end defun
2563
2564 @xref{Macro Bindings}, for descriptions of the @code{cl-macrolet}
2565 and @code{cl-symbol-macrolet} forms for making ``local'' macro
2566 definitions.
2567
2568 @node Declarations
2569 @chapter Declarations
2570
2571 @noindent
2572 Common Lisp includes a complex and powerful ``declaration''
2573 mechanism that allows you to give the compiler special hints
2574 about the types of data that will be stored in particular variables,
2575 and about the ways those variables and functions will be used. This
2576 package defines versions of all the Common Lisp declaration forms:
2577 @code{cl-declare}, @code{cl-locally}, @code{cl-proclaim}, @code{cl-declaim},
2578 and @code{cl-the}.
2579
2580 Most of the Common Lisp declarations are not currently useful in
2581 Emacs Lisp, as the byte-code system provides little opportunity
2582 to benefit from type information, and @code{special} declarations
2583 are redundant in a fully dynamically-scoped Lisp. A few
2584 declarations are meaningful when the optimizing byte
2585 compiler is being used, however. Under the earlier non-optimizing
2586 compiler, these declarations will effectively be ignored.
2587
2588 @defun cl-proclaim decl-spec
2589 This function records a ``global'' declaration specified by
2590 @var{decl-spec}. Since @code{cl-proclaim} is a function, @var{decl-spec}
2591 is evaluated and thus should normally be quoted.
2592 @end defun
2593
2594 @defmac cl-declaim decl-specs@dots{}
2595 This macro is like @code{cl-proclaim}, except that it takes any number
2596 of @var{decl-spec} arguments, and the arguments are unevaluated and
2597 unquoted. The @code{cl-declaim} macro also puts an @code{(cl-eval-when
2598 (compile load eval) ...)} around the declarations so that they will
2599 be registered at compile-time as well as at run-time. (This is vital,
2600 since normally the declarations are meant to influence the way the
2601 compiler treats the rest of the file that contains the @code{cl-declaim}
2602 form.)
2603 @end defmac
2604
2605 @defmac cl-declare decl-specs@dots{}
2606 This macro is used to make declarations within functions and other
2607 code. Common Lisp allows declarations in various locations, generally
2608 at the beginning of any of the many ``implicit @code{progn}s''
2609 throughout Lisp syntax, such as function bodies, @code{let} bodies,
2610 etc. Currently the only declaration understood by @code{cl-declare}
2611 is @code{special}.
2612 @end defmac
2613
2614 @defmac cl-locally declarations@dots{} forms@dots{}
2615 In this package, @code{cl-locally} is no different from @code{progn}.
2616 @end defmac
2617
2618 @defmac cl-the type form
2619 Type information provided by @code{cl-the} is ignored in this package;
2620 in other words, @code{(cl-the @var{type} @var{form})} is equivalent
2621 to @var{form}. Future versions of the optimizing byte-compiler may
2622 make use of this information.
2623
2624 For example, @code{mapcar} can map over both lists and arrays. It is
2625 hard for the compiler to expand @code{mapcar} into an in-line loop
2626 unless it knows whether the sequence will be a list or an array ahead
2627 of time. With @code{(mapcar 'car (cl-the vector foo))}, a future
2628 compiler would have enough information to expand the loop in-line.
2629 For now, Emacs Lisp will treat the above code as exactly equivalent
2630 to @code{(mapcar 'car foo)}.
2631 @end defmac
2632
2633 Each @var{decl-spec} in a @code{cl-proclaim}, @code{cl-declaim}, or
2634 @code{cl-declare} should be a list beginning with a symbol that says
2635 what kind of declaration it is. This package currently understands
2636 @code{special}, @code{inline}, @code{notinline}, @code{optimize},
2637 and @code{warn} declarations. (The @code{warn} declaration is an
2638 extension of standard Common Lisp.) Other Common Lisp declarations,
2639 such as @code{type} and @code{ftype}, are silently ignored.
2640
2641 @table @code
2642 @item special
2643 Since all variables in Emacs Lisp are ``special'' (in the Common
2644 Lisp sense), @code{special} declarations are only advisory. They
2645 simply tell the optimizing byte compiler that the specified
2646 variables are intentionally being referred to without being
2647 bound in the body of the function. The compiler normally emits
2648 warnings for such references, since they could be typographical
2649 errors for references to local variables.
2650
2651 The declaration @code{(cl-declare (special @var{var1} @var{var2}))} is
2652 equivalent to @code{(defvar @var{var1}) (defvar @var{var2})} in the
2653 optimizing compiler, or to nothing at all in older compilers (which
2654 do not warn for non-local references).
2655
2656 In top-level contexts, it is generally better to write
2657 @code{(defvar @var{var})} than @code{(cl-declaim (special @var{var}))},
2658 since @code{defvar} makes your intentions clearer. But the older
2659 byte compilers can not handle @code{defvar}s appearing inside of
2660 functions, while @code{(cl-declare (special @var{var}))} takes care
2661 to work correctly with all compilers.
2662
2663 @item inline
2664 The @code{inline} @var{decl-spec} lists one or more functions
2665 whose bodies should be expanded ``in-line'' into calling functions
2666 whenever the compiler is able to arrange for it. For example,
2667 the Common Lisp function @code{cadr} is declared @code{inline}
2668 by this package so that the form @code{(cadr @var{x})} will
2669 expand directly into @code{(car (cdr @var{x}))} when it is called
2670 in user functions, for a savings of one (relatively expensive)
2671 function call.
2672
2673 The following declarations are all equivalent. Note that the
2674 @code{defsubst} form is a convenient way to define a function
2675 and declare it inline all at once.
2676
2677 @example
2678 (cl-declaim (inline foo bar))
2679 (cl-eval-when (compile load eval)
2680 (cl-proclaim '(inline foo bar)))
2681 (defsubst foo (...) ...) ; instead of defun
2682 @end example
2683
2684 @strong{Please note:} this declaration remains in effect after the
2685 containing source file is done. It is correct to use it to
2686 request that a function you have defined should be inlined,
2687 but it is impolite to use it to request inlining of an external
2688 function.
2689
2690 In Common Lisp, it is possible to use @code{(cl-declare (inline @dots{}))}
2691 before a particular call to a function to cause just that call to
2692 be inlined; the current byte compilers provide no way to implement
2693 this, so @code{(cl-declare (inline @dots{}))} is currently ignored by
2694 this package.
2695
2696 @item notinline
2697 The @code{notinline} declaration lists functions which should
2698 not be inlined after all; it cancels a previous @code{inline}
2699 declaration.
2700
2701 @item optimize
2702 This declaration controls how much optimization is performed by
2703 the compiler. Naturally, it is ignored by the earlier non-optimizing
2704 compilers.
2705
2706 The word @code{optimize} is followed by any number of lists like
2707 @code{(speed 3)} or @code{(safety 2)}. Common Lisp defines several
2708 optimization ``qualities''; this package ignores all but @code{speed}
2709 and @code{safety}. The value of a quality should be an integer from
2710 0 to 3, with 0 meaning ``unimportant'' and 3 meaning ``very important''.
2711 The default level for both qualities is 1.
2712
2713 In this package, with the optimizing compiler, the
2714 @code{speed} quality is tied to the @code{byte-optimize}
2715 flag, which is set to @code{nil} for @code{(speed 0)} and to
2716 @code{t} for higher settings; and the @code{safety} quality is
2717 tied to the @code{byte-compile-delete-errors} flag, which is
2718 set to @code{nil} for @code{(safety 3)} and to @code{t} for all
2719 lower settings. (The latter flag controls whether the compiler
2720 is allowed to optimize out code whose only side-effect could
2721 be to signal an error, e.g., rewriting @code{(progn foo bar)} to
2722 @code{bar} when it is not known whether @code{foo} will be bound
2723 at run-time.)
2724
2725 Note that even compiling with @code{(safety 0)}, the Emacs
2726 byte-code system provides sufficient checking to prevent real
2727 harm from being done. For example, barring serious bugs in
2728 Emacs itself, Emacs will not crash with a segmentation fault
2729 just because of an error in a fully-optimized Lisp program.
2730
2731 The @code{optimize} declaration is normally used in a top-level
2732 @code{cl-proclaim} or @code{cl-declaim} in a file; Common Lisp allows
2733 it to be used with @code{cl-declare} to set the level of optimization
2734 locally for a given form, but this will not work correctly with the
2735 current version of the optimizing compiler. (The @code{cl-declare}
2736 will set the new optimization level, but that level will not
2737 automatically be unset after the enclosing form is done.)
2738
2739 @item warn
2740 This declaration controls what sorts of warnings are generated
2741 by the byte compiler. Again, only the optimizing compiler
2742 generates warnings. The word @code{warn} is followed by any
2743 number of ``warning qualities'', similar in form to optimization
2744 qualities. The currently supported warning types are
2745 @code{redefine}, @code{callargs}, @code{unresolved}, and
2746 @code{free-vars}; in the current system, a value of 0 will
2747 disable these warnings and any higher value will enable them.
2748 See the documentation for the optimizing byte compiler for details.
2749 @end table
2750
2751 @node Symbols
2752 @chapter Symbols
2753
2754 @noindent
2755 This package defines several symbol-related features that were
2756 missing from Emacs Lisp.
2757
2758 @menu
2759 * Property Lists:: @code{cl-get}, @code{cl-remprop}, @code{cl-getf}, @code{cl-remf}.
2760 * Creating Symbols:: @code{cl-gensym}, @code{cl-gentemp}.
2761 @end menu
2762
2763 @node Property Lists
2764 @section Property Lists
2765
2766 @noindent
2767 These functions augment the standard Emacs Lisp functions @code{get}
2768 and @code{put} for operating on properties attached to symbols.
2769 There are also functions for working with property lists as
2770 first-class data structures not attached to particular symbols.
2771
2772 @defun cl-get symbol property &optional default
2773 This function is like @code{get}, except that if the property is
2774 not found, the @var{default} argument provides the return value.
2775 (The Emacs Lisp @code{get} function always uses @code{nil} as
2776 the default; this package's @code{cl-get} is equivalent to Common
2777 Lisp's @code{get}.)
2778
2779 The @code{cl-get} function is @code{setf}-able; when used in this
2780 fashion, the @var{default} argument is allowed but ignored.
2781 @end defun
2782
2783 @defun cl-remprop symbol property
2784 This function removes the entry for @var{property} from the property
2785 list of @var{symbol}. It returns a true value if the property was
2786 indeed found and removed, or @code{nil} if there was no such property.
2787 (This function was probably omitted from Emacs originally because,
2788 since @code{get} did not allow a @var{default}, it was very difficult
2789 to distinguish between a missing property and a property whose value
2790 was @code{nil}; thus, setting a property to @code{nil} was close
2791 enough to @code{cl-remprop} for most purposes.)
2792 @end defun
2793
2794 @defun cl-getf place property &optional default
2795 This function scans the list @var{place} as if it were a property
2796 list, i.e., a list of alternating property names and values. If
2797 an even-numbered element of @var{place} is found which is @code{eq}
2798 to @var{property}, the following odd-numbered element is returned.
2799 Otherwise, @var{default} is returned (or @code{nil} if no default
2800 is given).
2801
2802 In particular,
2803
2804 @example
2805 (get sym prop) @equiv{} (cl-get (symbol-plist sym) prop)
2806 @end example
2807
2808 It is valid to use @code{getf} as a @code{setf} place, in which case
2809 its @var{place} argument must itself be a valid @code{setf} place.
2810 The @var{default} argument, if any, is ignored in this context.
2811 The effect is to change (via @code{setcar}) the value cell in the
2812 list that corresponds to @var{property}, or to cons a new property-value
2813 pair onto the list if the property is not yet present.
2814
2815 @example
2816 (put sym prop val) @equiv{} (setf (cl-get (symbol-plist sym) prop) val)
2817 @end example
2818
2819 The @code{get} and @code{cl-get} functions are also @code{setf}-able.
2820 The fact that @code{default} is ignored can sometimes be useful:
2821
2822 @example
2823 (cl-incf (cl-get 'foo 'usage-count 0))
2824 @end example
2825
2826 Here, symbol @code{foo}'s @code{usage-count} property is incremented
2827 if it exists, or set to 1 (an incremented 0) otherwise.
2828
2829 @c FIXME cl-getf?
2830 When not used as a @code{setf} form, @code{getf} is just a regular
2831 function and its @var{place} argument can actually be any Lisp
2832 expression.
2833 @end defun
2834
2835 @defmac cl-remf place property
2836 This macro removes the property-value pair for @var{property} from
2837 the property list stored at @var{place}, which is any @code{setf}-able
2838 place expression. It returns true if the property was found. Note
2839 that if @var{property} happens to be first on the list, this will
2840 effectively do a @code{(setf @var{place} (cddr @var{place}))},
2841 whereas if it occurs later, this simply uses @code{setcdr} to splice
2842 out the property and value cells.
2843 @end defmac
2844
2845 @node Creating Symbols
2846 @section Creating Symbols
2847
2848 @noindent
2849 These functions create unique symbols, typically for use as
2850 temporary variables.
2851
2852 @defun cl-gensym &optional x
2853 This function creates a new, uninterned symbol (using @code{make-symbol})
2854 with a unique name. (The name of an uninterned symbol is relevant
2855 only if the symbol is printed.) By default, the name is generated
2856 from an increasing sequence of numbers, @samp{G1000}, @samp{G1001},
2857 @samp{G1002}, etc. If the optional argument @var{x} is a string, that
2858 string is used as a prefix instead of @samp{G}. Uninterned symbols
2859 are used in macro expansions for temporary variables, to ensure that
2860 their names will not conflict with ``real'' variables in the user's
2861 code.
2862 @end defun
2863
2864 @defvar cl--gensym-counter
2865 This variable holds the counter used to generate @code{cl-gensym} names.
2866 It is incremented after each use by @code{cl-gensym}. In Common Lisp
2867 this is initialized with 0, but this package initializes it with a
2868 random (time-dependent) value to avoid trouble when two files that
2869 each used @code{cl-gensym} in their compilation are loaded together.
2870 (Uninterned symbols become interned when the compiler writes them
2871 out to a file and the Emacs loader loads them, so their names have to
2872 be treated a bit more carefully than in Common Lisp where uninterned
2873 symbols remain uninterned after loading.)
2874 @end defvar
2875
2876 @defun cl-gentemp &optional x
2877 This function is like @code{cl-gensym}, except that it produces a new
2878 @emph{interned} symbol. If the symbol that is generated already
2879 exists, the function keeps incrementing the counter and trying
2880 again until a new symbol is generated.
2881 @end defun
2882
2883 This package automatically creates all keywords that are called for by
2884 @code{&key} argument specifiers, and discourages the use of keywords
2885 as data unrelated to keyword arguments, so the related function
2886 @code{defkeyword} (to create self-quoting keyword symbols) is not
2887 provided.
2888
2889 @node Numbers
2890 @chapter Numbers
2891
2892 @noindent
2893 This section defines a few simple Common Lisp operations on numbers
2894 which were left out of Emacs Lisp.
2895
2896 @menu
2897 * Predicates on Numbers:: @code{cl-plusp}, @code{cl-oddp}, @code{cl-floatp-safe}, etc.
2898 * Numerical Functions:: @code{abs}, @code{cl-floor}, etc.
2899 * Random Numbers:: @code{cl-random}, @code{cl-make-random-state}.
2900 * Implementation Parameters:: @code{cl-most-positive-float}.
2901 @end menu
2902
2903 @node Predicates on Numbers
2904 @section Predicates on Numbers
2905
2906 @noindent
2907 These functions return @code{t} if the specified condition is
2908 true of the numerical argument, or @code{nil} otherwise.
2909
2910 @defun cl-plusp number
2911 This predicate tests whether @var{number} is positive. It is an
2912 error if the argument is not a number.
2913 @end defun
2914
2915 @defun cl-minusp number
2916 This predicate tests whether @var{number} is negative. It is an
2917 error if the argument is not a number.
2918 @end defun
2919
2920 @defun cl-oddp integer
2921 This predicate tests whether @var{integer} is odd. It is an
2922 error if the argument is not an integer.
2923 @end defun
2924
2925 @defun cl-evenp integer
2926 This predicate tests whether @var{integer} is even. It is an
2927 error if the argument is not an integer.
2928 @end defun
2929
2930 @defun cl-floatp-safe object
2931 This predicate tests whether @var{object} is a floating-point
2932 number. On systems that support floating-point, this is equivalent
2933 to @code{floatp}. On other systems, this always returns @code{nil}.
2934 @end defun
2935
2936 @node Numerical Functions
2937 @section Numerical Functions
2938
2939 @noindent
2940 These functions perform various arithmetic operations on numbers.
2941
2942 @defun cl-gcd &rest integers
2943 This function returns the Greatest Common Divisor of the arguments.
2944 For one argument, it returns the absolute value of that argument.
2945 For zero arguments, it returns zero.
2946 @end defun
2947
2948 @defun cl-lcm &rest integers
2949 This function returns the Least Common Multiple of the arguments.
2950 For one argument, it returns the absolute value of that argument.
2951 For zero arguments, it returns one.
2952 @end defun
2953
2954 @defun cl-isqrt integer
2955 This function computes the ``integer square root'' of its integer
2956 argument, i.e., the greatest integer less than or equal to the true
2957 square root of the argument.
2958 @end defun
2959
2960 @defun cl-floor number &optional divisor
2961 With one argument, @code{cl-floor} returns a list of two numbers:
2962 The argument rounded down (toward minus infinity) to an integer,
2963 and the ``remainder'' which would have to be added back to the
2964 first return value to yield the argument again. If the argument
2965 is an integer @var{x}, the result is always the list @code{(@var{x} 0)}.
2966 If the argument is a floating-point number, the first
2967 result is a Lisp integer and the second is a Lisp float between
2968 0 (inclusive) and 1 (exclusive).
2969
2970 With two arguments, @code{cl-floor} divides @var{number} by
2971 @var{divisor}, and returns the floor of the quotient and the
2972 corresponding remainder as a list of two numbers. If
2973 @code{(cl-floor @var{x} @var{y})} returns @code{(@var{q} @var{r})},
2974 then @code{@var{q}*@var{y} + @var{r} = @var{x}}, with @var{r}
2975 between 0 (inclusive) and @var{r} (exclusive). Also, note
2976 that @code{(cl-floor @var{x})} is exactly equivalent to
2977 @code{(cl-floor @var{x} 1)}.
2978
2979 This function is entirely compatible with Common Lisp's @code{floor}
2980 function, except that it returns the two results in a list since
2981 Emacs Lisp does not support multiple-valued functions.
2982 @end defun
2983
2984 @defun cl-ceiling number &optional divisor
2985 This function implements the Common Lisp @code{ceiling} function,
2986 which is analogous to @code{floor} except that it rounds the
2987 argument or quotient of the arguments up toward plus infinity.
2988 The remainder will be between 0 and minus @var{r}.
2989 @end defun
2990
2991 @defun cl-truncate number &optional divisor
2992 This function implements the Common Lisp @code{truncate} function,
2993 which is analogous to @code{floor} except that it rounds the
2994 argument or quotient of the arguments toward zero. Thus it is
2995 equivalent to @code{cl-floor} if the argument or quotient is
2996 positive, or to @code{cl-ceiling} otherwise. The remainder has
2997 the same sign as @var{number}.
2998 @end defun
2999
3000 @defun cl-round number &optional divisor
3001 This function implements the Common Lisp @code{round} function,
3002 which is analogous to @code{floor} except that it rounds the
3003 argument or quotient of the arguments to the nearest integer.
3004 In the case of a tie (the argument or quotient is exactly
3005 halfway between two integers), it rounds to the even integer.
3006 @end defun
3007
3008 @defun cl-mod number divisor
3009 This function returns the same value as the second return value
3010 of @code{cl-floor}.
3011 @end defun
3012
3013 @defun cl-rem number divisor
3014 This function returns the same value as the second return value
3015 of @code{cl-truncate}.
3016 @end defun
3017
3018 @node Random Numbers
3019 @section Random Numbers
3020
3021 @noindent
3022 This package also provides an implementation of the Common Lisp
3023 random number generator. It uses its own additive-congruential
3024 algorithm, which is much more likely to give statistically clean
3025 random numbers than the simple generators supplied by many
3026 operating systems.
3027
3028 @defun cl-random number &optional state
3029 This function returns a random nonnegative number less than
3030 @var{number}, and of the same type (either integer or floating-point).
3031 The @var{state} argument should be a @code{random-state} object
3032 which holds the state of the random number generator. The
3033 function modifies this state object as a side effect. If
3034 @var{state} is omitted, it defaults to the variable
3035 @code{cl--random-state}, which contains a pre-initialized
3036 @code{random-state} object.
3037 @end defun
3038
3039 @defvar cl--random-state
3040 This variable contains the system ``default'' @code{random-state}
3041 object, used for calls to @code{cl-random} that do not specify an
3042 alternative state object. Since any number of programs in the
3043 Emacs process may be accessing @code{cl--random-state} in interleaved
3044 fashion, the sequence generated from this variable will be
3045 irreproducible for all intents and purposes.
3046 @end defvar
3047
3048 @defun cl-make-random-state &optional state
3049 This function creates or copies a @code{random-state} object.
3050 If @var{state} is omitted or @code{nil}, it returns a new copy of
3051 @code{cl--random-state}. This is a copy in the sense that future
3052 sequences of calls to @code{(cl-random @var{n})} and
3053 @code{(cl-random @var{n} @var{s})} (where @var{s} is the new
3054 random-state object) will return identical sequences of random
3055 numbers.
3056
3057 If @var{state} is a @code{random-state} object, this function
3058 returns a copy of that object. If @var{state} is @code{t}, this
3059 function returns a new @code{random-state} object seeded from the
3060 date and time. As an extension to Common Lisp, @var{state} may also
3061 be an integer in which case the new object is seeded from that
3062 integer; each different integer seed will result in a completely
3063 different sequence of random numbers.
3064
3065 It is valid to print a @code{random-state} object to a buffer or
3066 file and later read it back with @code{read}. If a program wishes
3067 to use a sequence of pseudo-random numbers which can be reproduced
3068 later for debugging, it can call @code{(cl-make-random-state t)} to
3069 get a new sequence, then print this sequence to a file. When the
3070 program is later rerun, it can read the original run's random-state
3071 from the file.
3072 @end defun
3073
3074 @defun cl-random-state-p object
3075 This predicate returns @code{t} if @var{object} is a
3076 @code{random-state} object, or @code{nil} otherwise.
3077 @end defun
3078
3079 @node Implementation Parameters
3080 @section Implementation Parameters
3081
3082 @noindent
3083 This package defines several useful constants having to with numbers.
3084
3085 The following parameters have to do with floating-point numbers.
3086 This package determines their values by exercising the computer's
3087 floating-point arithmetic in various ways. Because this operation
3088 might be slow, the code for initializing them is kept in a separate
3089 function that must be called before the parameters can be used.
3090
3091 @defun cl-float-limits
3092 This function makes sure that the Common Lisp floating-point parameters
3093 like @code{cl-most-positive-float} have been initialized. Until it is
3094 called, these parameters will be @code{nil}. If this version of Emacs
3095 does not support floats, the parameters will remain @code{nil}. If the
3096 parameters have already been initialized, the function returns
3097 immediately.
3098
3099 The algorithm makes assumptions that will be valid for most modern
3100 machines, but will fail if the machine's arithmetic is extremely
3101 unusual, e.g., decimal.
3102 @end defun
3103
3104 Since true Common Lisp supports up to four different floating-point
3105 precisions, it has families of constants like
3106 @code{most-positive-single-float}, @code{most-positive-double-float},
3107 @code{most-positive-long-float}, and so on. Emacs has only one
3108 floating-point precision, so this package omits the precision word
3109 from the constants' names.
3110
3111 @defvar cl-most-positive-float
3112 This constant equals the largest value a Lisp float can hold.
3113 For those systems whose arithmetic supports infinities, this is
3114 the largest @emph{finite} value. For IEEE machines, the value
3115 is approximately @code{1.79e+308}.
3116 @end defvar
3117
3118 @defvar cl-most-negative-float
3119 This constant equals the most-negative value a Lisp float can hold.
3120 (It is assumed to be equal to @code{(- cl-most-positive-float)}.)
3121 @end defvar
3122
3123 @defvar cl-least-positive-float
3124 This constant equals the smallest Lisp float value greater than zero.
3125 For IEEE machines, it is about @code{4.94e-324} if denormals are
3126 supported or @code{2.22e-308} if not.
3127 @end defvar
3128
3129 @defvar cl-least-positive-normalized-float
3130 This constant equals the smallest @emph{normalized} Lisp float greater
3131 than zero, i.e., the smallest value for which IEEE denormalization
3132 will not result in a loss of precision. For IEEE machines, this
3133 value is about @code{2.22e-308}. For machines that do not support
3134 the concept of denormalization and gradual underflow, this constant
3135 will always equal @code{cl-least-positive-float}.
3136 @end defvar
3137
3138 @defvar cl-least-negative-float
3139 This constant is the negative counterpart of @code{cl-least-positive-float}.
3140 @end defvar
3141
3142 @defvar cl-least-negative-normalized-float
3143 This constant is the negative counterpart of
3144 @code{cl-least-positive-normalized-float}.
3145 @end defvar
3146
3147 @defvar cl-float-epsilon
3148 This constant is the smallest positive Lisp float that can be added
3149 to 1.0 to produce a distinct value. Adding a smaller number to 1.0
3150 will yield 1.0 again due to roundoff. For IEEE machines, epsilon
3151 is about @code{2.22e-16}.
3152 @end defvar
3153
3154 @defvar cl-float-negative-epsilon
3155 This is the smallest positive value that can be subtracted from
3156 1.0 to produce a distinct value. For IEEE machines, it is about
3157 @code{1.11e-16}.
3158 @end defvar
3159
3160 @node Sequences
3161 @chapter Sequences
3162
3163 @noindent
3164 Common Lisp defines a number of functions that operate on
3165 @dfn{sequences}, which are either lists, strings, or vectors.
3166 Emacs Lisp includes a few of these, notably @code{elt} and
3167 @code{length}; this package defines most of the rest.
3168
3169 @menu
3170 * Sequence Basics:: Arguments shared by all sequence functions.
3171 * Mapping over Sequences:: @code{cl-mapcar}, @code{cl-mapcan}, @code{cl-map}, @code{cl-every}, etc.
3172 * Sequence Functions:: @code{cl-subseq}, @code{cl-remove}, @code{cl-substitute}, etc.
3173 * Searching Sequences:: @code{cl-find}, @code{cl-position}, @code{cl-count}, @code{cl-search}, etc.
3174 * Sorting Sequences:: @code{cl-sort}, @code{cl-stable-sort}, @code{cl-merge}.
3175 @end menu
3176
3177 @node Sequence Basics
3178 @section Sequence Basics
3179
3180 @noindent
3181 Many of the sequence functions take keyword arguments; @pxref{Argument
3182 Lists}. All keyword arguments are optional and, if specified,
3183 may appear in any order.
3184
3185 The @code{:key} argument should be passed either @code{nil}, or a
3186 function of one argument. This key function is used as a filter
3187 through which the elements of the sequence are seen; for example,
3188 @code{(cl-find x y :key 'car)} is similar to @code{(cl-assoc x y)}:
3189 It searches for an element of the list whose @code{car} equals
3190 @code{x}, rather than for an element which equals @code{x} itself.
3191 If @code{:key} is omitted or @code{nil}, the filter is effectively
3192 the identity function.
3193
3194 The @code{:test} and @code{:test-not} arguments should be either
3195 @code{nil}, or functions of two arguments. The test function is
3196 used to compare two sequence elements, or to compare a search value
3197 with sequence elements. (The two values are passed to the test
3198 function in the same order as the original sequence function
3199 arguments from which they are derived, or, if they both come from
3200 the same sequence, in the same order as they appear in that sequence.)
3201 The @code{:test} argument specifies a function which must return
3202 true (non-@code{nil}) to indicate a match; instead, you may use
3203 @code{:test-not} to give a function which returns @emph{false} to
3204 indicate a match. The default test function is @code{eql}.
3205
3206 Many functions which take @var{item} and @code{:test} or @code{:test-not}
3207 arguments also come in @code{-if} and @code{-if-not} varieties,
3208 where a @var{predicate} function is passed instead of @var{item},
3209 and sequence elements match if the predicate returns true on them
3210 (or false in the case of @code{-if-not}). For example:
3211
3212 @example
3213 (cl-remove 0 seq :test '=) @equiv{} (cl-remove-if 'zerop seq)
3214 @end example
3215
3216 @noindent
3217 to remove all zeros from sequence @code{seq}.
3218
3219 Some operations can work on a subsequence of the argument sequence;
3220 these function take @code{:start} and @code{:end} arguments which
3221 default to zero and the length of the sequence, respectively.
3222 Only elements between @var{start} (inclusive) and @var{end}
3223 (exclusive) are affected by the operation. The @var{end} argument
3224 may be passed @code{nil} to signify the length of the sequence;
3225 otherwise, both @var{start} and @var{end} must be integers, with
3226 @code{0 <= @var{start} <= @var{end} <= (length @var{seq})}.
3227 If the function takes two sequence arguments, the limits are
3228 defined by keywords @code{:start1} and @code{:end1} for the first,
3229 and @code{:start2} and @code{:end2} for the second.
3230
3231 A few functions accept a @code{:from-end} argument, which, if
3232 non-@code{nil}, causes the operation to go from right-to-left
3233 through the sequence instead of left-to-right, and a @code{:count}
3234 argument, which specifies an integer maximum number of elements
3235 to be removed or otherwise processed.
3236
3237 The sequence functions make no guarantees about the order in
3238 which the @code{:test}, @code{:test-not}, and @code{:key} functions
3239 are called on various elements. Therefore, it is a bad idea to depend
3240 on side effects of these functions. For example, @code{:from-end}
3241 may cause the sequence to be scanned actually in reverse, or it may
3242 be scanned forwards but computing a result ``as if'' it were scanned
3243 backwards. (Some functions, like @code{cl-mapcar} and @code{cl-every},
3244 @emph{do} specify exactly the order in which the function is called
3245 so side effects are perfectly acceptable in those cases.)
3246
3247 Strings may contain ``text properties'' as well
3248 as character data. Except as noted, it is undefined whether or
3249 not text properties are preserved by sequence functions. For
3250 example, @code{(cl-remove ?A @var{str})} may or may not preserve
3251 the properties of the characters copied from @var{str} into the
3252 result.
3253
3254 @node Mapping over Sequences
3255 @section Mapping over Sequences
3256
3257 @noindent
3258 These functions ``map'' the function you specify over the elements
3259 of lists or arrays. They are all variations on the theme of the
3260 built-in function @code{mapcar}.
3261
3262 @defun cl-mapcar function seq &rest more-seqs
3263 This function calls @var{function} on successive parallel sets of
3264 elements from its argument sequences. Given a single @var{seq}
3265 argument it is equivalent to @code{mapcar}; given @var{n} sequences,
3266 it calls the function with the first elements of each of the sequences
3267 as the @var{n} arguments to yield the first element of the result
3268 list, then with the second elements, and so on. The mapping stops as
3269 soon as the shortest sequence runs out. The argument sequences may
3270 be any mixture of lists, strings, and vectors; the return sequence
3271 is always a list.
3272
3273 Common Lisp's @code{mapcar} accepts multiple arguments but works
3274 only on lists; Emacs Lisp's @code{mapcar} accepts a single sequence
3275 argument. This package's @code{cl-mapcar} works as a compatible
3276 superset of both.
3277 @end defun
3278
3279 @defun cl-map result-type function seq &rest more-seqs
3280 This function maps @var{function} over the argument sequences,
3281 just like @code{cl-mapcar}, but it returns a sequence of type
3282 @var{result-type} rather than a list. @var{result-type} must
3283 be one of the following symbols: @code{vector}, @code{string},
3284 @code{list} (in which case the effect is the same as for
3285 @code{cl-mapcar}), or @code{nil} (in which case the results are
3286 thrown away and @code{cl-map} returns @code{nil}).
3287 @end defun
3288
3289 @defun cl-maplist function list &rest more-lists
3290 This function calls @var{function} on each of its argument lists,
3291 then on the @code{cdr}s of those lists, and so on, until the
3292 shortest list runs out. The results are returned in the form
3293 of a list. Thus, @code{cl-maplist} is like @code{cl-mapcar} except
3294 that it passes in the list pointers themselves rather than the
3295 @code{car}s of the advancing pointers.
3296 @end defun
3297
3298 @c FIXME does not exist?
3299 @defun cl-mapc function seq &rest more-seqs
3300 This function is like @code{cl-mapcar}, except that the values returned
3301 by @var{function} are ignored and thrown away rather than being
3302 collected into a list. The return value of @code{cl-mapc} is @var{seq},
3303 the first sequence. This function is more general than the Emacs
3304 primitive @code{mapc}.
3305 @end defun
3306
3307 @defun cl-mapl function list &rest more-lists
3308 This function is like @code{cl-maplist}, except that it throws away
3309 the values returned by @var{function}.
3310 @end defun
3311
3312 @defun cl-mapcan function seq &rest more-seqs
3313 This function is like @code{cl-mapcar}, except that it concatenates
3314 the return values (which must be lists) using @code{nconc},
3315 rather than simply collecting them into a list.
3316 @end defun
3317
3318 @defun cl-mapcon function list &rest more-lists
3319 This function is like @code{cl-maplist}, except that it concatenates
3320 the return values using @code{nconc}.
3321 @end defun
3322
3323 @defun cl-some predicate seq &rest more-seqs
3324 This function calls @var{predicate} on each element of @var{seq}
3325 in turn; if @var{predicate} returns a non-@code{nil} value,
3326 @code{some} returns that value, otherwise it returns @code{nil}.
3327 Given several sequence arguments, it steps through the sequences
3328 in parallel until the shortest one runs out, just as in
3329 @code{cl-mapcar}. You can rely on the left-to-right order in which
3330 the elements are visited, and on the fact that mapping stops
3331 immediately as soon as @var{predicate} returns non-@code{nil}.
3332 @end defun
3333
3334 @defun cl-every predicate seq &rest more-seqs
3335 This function calls @var{predicate} on each element of the sequence(s)
3336 in turn; it returns @code{nil} as soon as @var{predicate} returns
3337 @code{nil} for any element, or @code{t} if the predicate was true
3338 for all elements.
3339 @end defun
3340
3341 @defun cl-notany predicate seq &rest more-seqs
3342 This function calls @var{predicate} on each element of the sequence(s)
3343 in turn; it returns @code{nil} as soon as @var{predicate} returns
3344 a non-@code{nil} value for any element, or @code{t} if the predicate
3345 was @code{nil} for all elements.
3346 @end defun
3347
3348 @defun cl-notevery predicate seq &rest more-seqs
3349 This function calls @var{predicate} on each element of the sequence(s)
3350 in turn; it returns a non-@code{nil} value as soon as @var{predicate}
3351 returns @code{nil} for any element, or @code{t} if the predicate was
3352 true for all elements.
3353 @end defun
3354
3355 @defun cl-reduce function seq @t{&key :from-end :start :end :initial-value :key}
3356 This function combines the elements of @var{seq} using an associative
3357 binary operation. Suppose @var{function} is @code{*} and @var{seq} is
3358 the list @code{(2 3 4 5)}. The first two elements of the list are
3359 combined with @code{(* 2 3) = 6}; this is combined with the next
3360 element, @code{(* 6 4) = 24}, and that is combined with the final
3361 element: @code{(* 24 5) = 120}. Note that the @code{*} function happens
3362 to be self-reducing, so that @code{(* 2 3 4 5)} has the same effect as
3363 an explicit call to @code{cl-reduce}.
3364
3365 If @code{:from-end} is true, the reduction is right-associative instead
3366 of left-associative:
3367
3368 @example
3369 (cl-reduce '- '(1 2 3 4))
3370 @equiv{} (- (- (- 1 2) 3) 4) @result{} -8
3371 (cl-reduce '- '(1 2 3 4) :from-end t)
3372 @equiv{} (- 1 (- 2 (- 3 4))) @result{} -2
3373 @end example
3374
3375 If @code{:key} is specified, it is a function of one argument which
3376 is called on each of the sequence elements in turn.
3377
3378 If @code{:initial-value} is specified, it is effectively added to the
3379 front (or rear in the case of @code{:from-end}) of the sequence.
3380 The @code{:key} function is @emph{not} applied to the initial value.
3381
3382 If the sequence, including the initial value, has exactly one element
3383 then that element is returned without ever calling @var{function}.
3384 If the sequence is empty (and there is no initial value), then
3385 @var{function} is called with no arguments to obtain the return value.
3386 @end defun
3387
3388 All of these mapping operations can be expressed conveniently in
3389 terms of the @code{cl-loop} macro. In compiled code, @code{cl-loop} will
3390 be faster since it generates the loop as in-line code with no
3391 function calls.
3392
3393 @node Sequence Functions
3394 @section Sequence Functions
3395
3396 @noindent
3397 This section describes a number of Common Lisp functions for
3398 operating on sequences.
3399
3400 @defun cl-subseq sequence start &optional end
3401 This function returns a given subsequence of the argument
3402 @var{sequence}, which may be a list, string, or vector.
3403 The indices @var{start} and @var{end} must be in range, and
3404 @var{start} must be no greater than @var{end}. If @var{end}
3405 is omitted, it defaults to the length of the sequence. The
3406 return value is always a copy; it does not share structure
3407 with @var{sequence}.
3408
3409 As an extension to Common Lisp, @var{start} and/or @var{end}
3410 may be negative, in which case they represent a distance back
3411 from the end of the sequence. This is for compatibility with
3412 Emacs's @code{substring} function. Note that @code{cl-subseq} is
3413 the @emph{only} sequence function that allows negative
3414 @var{start} and @var{end}.
3415
3416 You can use @code{setf} on a @code{cl-subseq} form to replace a
3417 specified range of elements with elements from another sequence.
3418 The replacement is done as if by @code{cl-replace}, described below.
3419 @end defun
3420
3421 @defun cl-concatenate result-type &rest seqs
3422 This function concatenates the argument sequences together to
3423 form a result sequence of type @var{result-type}, one of the
3424 symbols @code{vector}, @code{string}, or @code{list}. The
3425 arguments are always copied, even in cases such as
3426 @code{(cl-concatenate 'list '(1 2 3))} where the result is
3427 identical to an argument.
3428 @end defun
3429
3430 @defun cl-fill seq item @t{&key :start :end}
3431 This function fills the elements of the sequence (or the specified
3432 part of the sequence) with the value @var{item}.
3433 @end defun
3434
3435 @defun cl-replace seq1 seq2 @t{&key :start1 :end1 :start2 :end2}
3436 This function copies part of @var{seq2} into part of @var{seq1}.
3437 The sequence @var{seq1} is not stretched or resized; the amount
3438 of data copied is simply the shorter of the source and destination
3439 (sub)sequences. The function returns @var{seq1}.
3440
3441 If @var{seq1} and @var{seq2} are @code{eq}, then the replacement
3442 will work correctly even if the regions indicated by the start
3443 and end arguments overlap. However, if @var{seq1} and @var{seq2}
3444 are lists which share storage but are not @code{eq}, and the
3445 start and end arguments specify overlapping regions, the effect
3446 is undefined.
3447 @end defun
3448
3449 @defun cl-remove item seq @t{&key :test :test-not :key :count :start :end :from-end}
3450 This returns a copy of @var{seq} with all elements matching
3451 @var{item} removed. The result may share storage with or be
3452 @code{eq} to @var{seq} in some circumstances, but the original
3453 @var{seq} will not be modified. The @code{:test}, @code{:test-not},
3454 and @code{:key} arguments define the matching test that is used;
3455 by default, elements @code{eql} to @var{item} are removed. The
3456 @code{:count} argument specifies the maximum number of matching
3457 elements that can be removed (only the leftmost @var{count} matches
3458 are removed). The @code{:start} and @code{:end} arguments specify
3459 a region in @var{seq} in which elements will be removed; elements
3460 outside that region are not matched or removed. The @code{:from-end}
3461 argument, if true, says that elements should be deleted from the
3462 end of the sequence rather than the beginning (this matters only
3463 if @var{count} was also specified).
3464 @end defun
3465
3466 @defun cl-delete item seq @t{&key :test :test-not :key :count :start :end :from-end}
3467 This deletes all elements of @var{seq} which match @var{item}.
3468 It is a destructive operation. Since Emacs Lisp does not support
3469 stretchable strings or vectors, this is the same as @code{cl-remove}
3470 for those sequence types. On lists, @code{cl-remove} will copy the
3471 list if necessary to preserve the original list, whereas
3472 @code{cl-delete} will splice out parts of the argument list.
3473 Compare @code{append} and @code{nconc}, which are analogous
3474 non-destructive and destructive list operations in Emacs Lisp.
3475 @end defun
3476
3477 @findex cl-remove-if
3478 @findex cl-remove-if-not
3479 @findex cl-delete-if
3480 @findex cl-delete-if-not
3481 The predicate-oriented functions @code{cl-remove-if}, @code{cl-remove-if-not},
3482 @code{cl-delete-if}, and @code{cl-delete-if-not} are defined similarly.
3483
3484 @defun cl-remove-duplicates seq @t{&key :test :test-not :key :start :end :from-end}
3485 This function returns a copy of @var{seq} with duplicate elements
3486 removed. Specifically, if two elements from the sequence match
3487 according to the @code{:test}, @code{:test-not}, and @code{:key}
3488 arguments, only the rightmost one is retained. If @code{:from-end}
3489 is true, the leftmost one is retained instead. If @code{:start} or
3490 @code{:end} is specified, only elements within that subsequence are
3491 examined or removed.
3492 @end defun
3493
3494 @defun cl-delete-duplicates seq @t{&key :test :test-not :key :start :end :from-end}
3495 This function deletes duplicate elements from @var{seq}. It is
3496 a destructive version of @code{cl-remove-duplicates}.
3497 @end defun
3498
3499 @defun cl-substitute new old seq @t{&key :test :test-not :key :count :start :end :from-end}
3500 This function returns a copy of @var{seq}, with all elements
3501 matching @var{old} replaced with @var{new}. The @code{:count},
3502 @code{:start}, @code{:end}, and @code{:from-end} arguments may be
3503 used to limit the number of substitutions made.
3504 @end defun
3505
3506 @defun cl-nsubstitute new old seq @t{&key :test :test-not :key :count :start :end :from-end}
3507 This is a destructive version of @code{cl-substitute}; it performs
3508 the substitution using @code{setcar} or @code{aset} rather than
3509 by returning a changed copy of the sequence.
3510 @end defun
3511
3512 @findex cl-substitute-if
3513 @findex cl-substitute-if-not
3514 @findex cl-nsubstitute-if
3515 @findex cl-nsubstitute-if-not
3516 The functions @code{cl-substitute-if}, @code{cl-substitute-if-not},
3517 @code{cl-nsubstitute-if}, and @code{cl-nsubstitute-if-not} are defined
3518 similarly. For these, a @var{predicate} is given in place of the
3519 @var{old} argument.
3520
3521 @node Searching Sequences
3522 @section Searching Sequences
3523
3524 @noindent
3525 These functions search for elements or subsequences in a sequence.
3526 (See also @code{cl-member} and @code{cl-assoc}; @pxref{Lists}.)
3527
3528 @defun cl-find item seq @t{&key :test :test-not :key :start :end :from-end}
3529 This function searches @var{seq} for an element matching @var{item}.
3530 If it finds a match, it returns the matching element. Otherwise,
3531 it returns @code{nil}. It returns the leftmost match, unless
3532 @code{:from-end} is true, in which case it returns the rightmost
3533 match. The @code{:start} and @code{:end} arguments may be used to
3534 limit the range of elements that are searched.
3535 @end defun
3536
3537 @defun cl-position item seq @t{&key :test :test-not :key :start :end :from-end}
3538 This function is like @code{cl-find}, except that it returns the
3539 integer position in the sequence of the matching item rather than
3540 the item itself. The position is relative to the start of the
3541 sequence as a whole, even if @code{:start} is non-zero. The function
3542 returns @code{nil} if no matching element was found.
3543 @end defun
3544
3545 @defun cl-count item seq @t{&key :test :test-not :key :start :end}
3546 This function returns the number of elements of @var{seq} which
3547 match @var{item}. The result is always a nonnegative integer.
3548 @end defun
3549
3550 @findex cl-find-if
3551 @findex cl-find-if-not
3552 @findex cl-position-if
3553 @findex cl-position-if-not
3554 @findex cl-count-if
3555 @findex cl-count-if-not
3556 The @code{cl-find-if}, @code{cl-find-if-not}, @code{cl-position-if},
3557 @code{cl-position-if-not}, @code{cl-count-if}, and @code{cl-count-if-not}
3558 functions are defined similarly.
3559
3560 @defun cl-mismatch seq1 seq2 @t{&key :test :test-not :key :start1 :end1 :start2 :end2 :from-end}
3561 This function compares the specified parts of @var{seq1} and
3562 @var{seq2}. If they are the same length and the corresponding
3563 elements match (according to @code{:test}, @code{:test-not},
3564 and @code{:key}), the function returns @code{nil}. If there is
3565 a mismatch, the function returns the index (relative to @var{seq1})
3566 of the first mismatching element. This will be the leftmost pair of
3567 elements which do not match, or the position at which the shorter of
3568 the two otherwise-matching sequences runs out.
3569
3570 If @code{:from-end} is true, then the elements are compared from right
3571 to left starting at @code{(1- @var{end1})} and @code{(1- @var{end2})}.
3572 If the sequences differ, then one plus the index of the rightmost
3573 difference (relative to @var{seq1}) is returned.
3574
3575 An interesting example is @code{(cl-mismatch str1 str2 :key 'upcase)},
3576 which compares two strings case-insensitively.
3577 @end defun
3578
3579 @defun cl-search seq1 seq2 @t{&key :test :test-not :key :from-end :start1 :end1 :start2 :end2}
3580 This function searches @var{seq2} for a subsequence that matches
3581 @var{seq1} (or part of it specified by @code{:start1} and
3582 @code{:end1}.) Only matches which fall entirely within the region
3583 defined by @code{:start2} and @code{:end2} will be considered.
3584 The return value is the index of the leftmost element of the
3585 leftmost match, relative to the start of @var{seq2}, or @code{nil}
3586 if no matches were found. If @code{:from-end} is true, the
3587 function finds the @emph{rightmost} matching subsequence.
3588 @end defun
3589
3590 @node Sorting Sequences
3591 @section Sorting Sequences
3592
3593 @defun clsort seq predicate @t{&key :key}
3594 This function sorts @var{seq} into increasing order as determined
3595 by using @var{predicate} to compare pairs of elements. @var{predicate}
3596 should return true (non-@code{nil}) if and only if its first argument
3597 is less than (not equal to) its second argument. For example,
3598 @code{<} and @code{string-lessp} are suitable predicate functions
3599 for sorting numbers and strings, respectively; @code{>} would sort
3600 numbers into decreasing rather than increasing order.
3601
3602 This function differs from Emacs's built-in @code{sort} in that it
3603 can operate on any type of sequence, not just lists. Also, it
3604 accepts a @code{:key} argument which is used to preprocess data
3605 fed to the @var{predicate} function. For example,
3606
3607 @example
3608 (setq data (cl-sort data 'string-lessp :key 'downcase))
3609 @end example
3610
3611 @noindent
3612 sorts @var{data}, a sequence of strings, into increasing alphabetical
3613 order without regard to case. A @code{:key} function of @code{car}
3614 would be useful for sorting association lists. It should only be a
3615 simple accessor though, it's used heavily in the current
3616 implementation.
3617
3618 The @code{cl-sort} function is destructive; it sorts lists by actually
3619 rearranging the @code{cdr} pointers in suitable fashion.
3620 @end defun
3621
3622 @defun cl-stable-sort seq predicate @t{&key :key}
3623 This function sorts @var{seq} @dfn{stably}, meaning two elements
3624 which are equal in terms of @var{predicate} are guaranteed not to
3625 be rearranged out of their original order by the sort.
3626
3627 In practice, @code{cl-sort} and @code{cl-stable-sort} are equivalent
3628 in Emacs Lisp because the underlying @code{sort} function is
3629 stable by default. However, this package reserves the right to
3630 use non-stable methods for @code{cl-sort} in the future.
3631 @end defun
3632
3633 @defun cl-merge type seq1 seq2 predicate @t{&key :key}
3634 This function merges two sequences @var{seq1} and @var{seq2} by
3635 interleaving their elements. The result sequence, of type @var{type}
3636 (in the sense of @code{cl-concatenate}), has length equal to the sum
3637 of the lengths of the two input sequences. The sequences may be
3638 modified destructively. Order of elements within @var{seq1} and
3639 @var{seq2} is preserved in the interleaving; elements of the two
3640 sequences are compared by @var{predicate} (in the sense of
3641 @code{sort}) and the lesser element goes first in the result.
3642 When elements are equal, those from @var{seq1} precede those from
3643 @var{seq2} in the result. Thus, if @var{seq1} and @var{seq2} are
3644 both sorted according to @var{predicate}, then the result will be
3645 a merged sequence which is (stably) sorted according to
3646 @var{predicate}.
3647 @end defun
3648
3649 @node Lists
3650 @chapter Lists
3651
3652 @noindent
3653 The functions described here operate on lists.
3654
3655 @menu
3656 * List Functions:: @code{cl-caddr}, @code{cl-first}, @code{cl-list*}, etc.
3657 * Substitution of Expressions:: @code{cl-subst}, @code{cl-sublis}, etc.
3658 * Lists as Sets:: @code{cl-member}, @code{cl-adjoin}, @code{cl-union}, etc.
3659 * Association Lists:: @code{cl-assoc}, @code{cl-rassoc}, @code{cl-acons}, @code{cl-pairlis}.
3660 @end menu
3661
3662 @node List Functions
3663 @section List Functions
3664
3665 @noindent
3666 This section describes a number of simple operations on lists,
3667 i.e., chains of cons cells.
3668
3669 @defun cl-caddr x
3670 This function is equivalent to @code{(car (cdr (cdr @var{x})))}.
3671 Likewise, this package defines all 28 @code{c@var{xxx}r} functions
3672 where @var{xxx} is up to four @samp{a}s and/or @samp{d}s.
3673 All of these functions are @code{setf}-able, and calls to them
3674 are expanded inline by the byte-compiler for maximum efficiency.
3675 @end defun
3676
3677 @defun cl-first x
3678 This function is a synonym for @code{(car @var{x})}. Likewise,
3679 the functions @code{cl-second}, @code{cl-third}, @dots{}, through
3680 @code{cl-tenth} return the given element of the list @var{x}.
3681 @end defun
3682
3683 @defun cl-rest x
3684 This function is a synonym for @code{(cdr @var{x})}.
3685 @end defun
3686
3687 @defun cl-endp x
3688 Common Lisp defines this function to act like @code{null}, but
3689 signaling an error if @code{x} is neither a @code{nil} nor a
3690 cons cell. This package simply defines @code{cl-endp} as a synonym
3691 for @code{null}.
3692 @end defun
3693
3694 @defun cl-list-length x
3695 This function returns the length of list @var{x}, exactly like
3696 @code{(length @var{x})}, except that if @var{x} is a circular
3697 list (where the cdr-chain forms a loop rather than terminating
3698 with @code{nil}), this function returns @code{nil}. (The regular
3699 @code{length} function would get stuck if given a circular list.)
3700 @end defun
3701
3702 @defun cl-list* arg &rest others
3703 This function constructs a list of its arguments. The final
3704 argument becomes the @code{cdr} of the last cell constructed.
3705 Thus, @code{(cl-list* @var{a} @var{b} @var{c})} is equivalent to
3706 @code{(cons @var{a} (cons @var{b} @var{c}))}, and
3707 @code{(cl-list* @var{a} @var{b} nil)} is equivalent to
3708 @code{(list @var{a} @var{b})}.
3709 @end defun
3710
3711 @defun cl-ldiff list sublist
3712 If @var{sublist} is a sublist of @var{list}, i.e., is @code{eq} to
3713 one of the cons cells of @var{list}, then this function returns
3714 a copy of the part of @var{list} up to but not including
3715 @var{sublist}. For example, @code{(cl-ldiff x (cddr x))} returns
3716 the first two elements of the list @code{x}. The result is a
3717 copy; the original @var{list} is not modified. If @var{sublist}
3718 is not a sublist of @var{list}, a copy of the entire @var{list}
3719 is returned.
3720 @end defun
3721
3722 @defun cl-copy-list list
3723 This function returns a copy of the list @var{list}. It copies
3724 dotted lists like @code{(1 2 . 3)} correctly.
3725 @end defun
3726
3727 @defun copy-tree x &optional vecp
3728 This function returns a copy of the tree of cons cells @var{x}.
3729 @c FIXME? cl-copy-list is not an alias of copy-sequence.
3730 Unlike @code{copy-sequence} (and its alias @code{cl-copy-list}),
3731 which copies only along the @code{cdr} direction, this function
3732 copies (recursively) along both the @code{car} and the @code{cdr}
3733 directions. If @var{x} is not a cons cell, the function simply
3734 returns @var{x} unchanged. If the optional @var{vecp} argument
3735 is true, this function copies vectors (recursively) as well as
3736 cons cells.
3737 @end defun
3738
3739 @defun cl-tree-equal x y @t{&key :test :test-not :key}
3740 This function compares two trees of cons cells. If @var{x} and
3741 @var{y} are both cons cells, their @code{car}s and @code{cdr}s are
3742 compared recursively. If neither @var{x} nor @var{y} is a cons
3743 cell, they are compared by @code{eql}, or according to the
3744 specified test. The @code{:key} function, if specified, is
3745 applied to the elements of both trees. @xref{Sequences}.
3746 @end defun
3747
3748 @node Substitution of Expressions
3749 @section Substitution of Expressions
3750
3751 @noindent
3752 These functions substitute elements throughout a tree of cons
3753 cells. (@xref{Sequence Functions}, for the @code{cl-substitute}
3754 function, which works on just the top-level elements of a list.)
3755
3756 @defun cl-subst new old tree @t{&key :test :test-not :key}
3757 This function substitutes occurrences of @var{old} with @var{new}
3758 in @var{tree}, a tree of cons cells. It returns a substituted
3759 tree, which will be a copy except that it may share storage with
3760 the argument @var{tree} in parts where no substitutions occurred.
3761 The original @var{tree} is not modified. This function recurses
3762 on, and compares against @var{old}, both @code{car}s and @code{cdr}s
3763 of the component cons cells. If @var{old} is itself a cons cell,
3764 then matching cells in the tree are substituted as usual without
3765 recursively substituting in that cell. Comparisons with @var{old}
3766 are done according to the specified test (@code{eql} by default).
3767 The @code{:key} function is applied to the elements of the tree
3768 but not to @var{old}.
3769 @end defun
3770
3771 @defun cl-nsubst new old tree @t{&key :test :test-not :key}
3772 This function is like @code{cl-subst}, except that it works by
3773 destructive modification (by @code{setcar} or @code{setcdr})
3774 rather than copying.
3775 @end defun
3776
3777 @findex cl-subst-if
3778 @findex cl-subst-if-not
3779 @findex cl-nsubst-if
3780 @findex cl-nsubst-if-not
3781 The @code{cl-subst-if}, @code{cl-subst-if-not}, @code{cl-nsubst-if}, and
3782 @code{cl-nsubst-if-not} functions are defined similarly.
3783
3784 @defun cl-sublis alist tree @t{&key :test :test-not :key}
3785 This function is like @code{cl-subst}, except that it takes an
3786 association list @var{alist} of @var{old}-@var{new} pairs.
3787 Each element of the tree (after applying the @code{:key}
3788 function, if any), is compared with the @code{car}s of
3789 @var{alist}; if it matches, it is replaced by the corresponding
3790 @code{cdr}.
3791 @end defun
3792
3793 @defun cl-nsublis alist tree @t{&key :test :test-not :key}
3794 This is a destructive version of @code{cl-sublis}.
3795 @end defun
3796
3797 @node Lists as Sets
3798 @section Lists as Sets
3799
3800 @noindent
3801 These functions perform operations on lists which represent sets
3802 of elements.
3803
3804 @defun cl-member item list @t{&key :test :test-not :key}
3805 This function searches @var{list} for an element matching @var{item}.
3806 If a match is found, it returns the cons cell whose @code{car} was
3807 the matching element. Otherwise, it returns @code{nil}. Elements
3808 are compared by @code{eql} by default; you can use the @code{:test},
3809 @code{:test-not}, and @code{:key} arguments to modify this behavior.
3810 @xref{Sequences}.
3811
3812 The standard Emacs lisp function @code{member} uses @code{equal} for
3813 comparisons; it is equivalent to @code{(cl-member @var{item} @var{list}
3814 :test 'equal)}.
3815 @end defun
3816
3817 @findex cl-member-if
3818 @findex cl-member-if-not
3819 The @code{cl-member-if} and @code{cl-member-if-not} functions
3820 analogously search for elements which satisfy a given predicate.
3821
3822 @defun cl-tailp sublist list
3823 This function returns @code{t} if @var{sublist} is a sublist of
3824 @var{list}, i.e., if @var{sublist} is @code{eql} to @var{list} or to
3825 any of its @code{cdr}s.
3826 @end defun
3827
3828 @defun cl-adjoin item list @t{&key :test :test-not :key}
3829 This function conses @var{item} onto the front of @var{list},
3830 like @code{(cons @var{item} @var{list})}, but only if @var{item}
3831 is not already present on the list (as determined by @code{cl-member}).
3832 If a @code{:key} argument is specified, it is applied to
3833 @var{item} as well as to the elements of @var{list} during
3834 the search, on the reasoning that @var{item} is ``about'' to
3835 become part of the list.
3836 @end defun
3837
3838 @defun cl-union list1 list2 @t{&key :test :test-not :key}
3839 This function combines two lists which represent sets of items,
3840 returning a list that represents the union of those two sets.
3841 The result list will contain all items which appear in @var{list1}
3842 or @var{list2}, and no others. If an item appears in both
3843 @var{list1} and @var{list2} it will be copied only once. If
3844 an item is duplicated in @var{list1} or @var{list2}, it is
3845 undefined whether or not that duplication will survive in the
3846 result list. The order of elements in the result list is also
3847 undefined.
3848 @end defun
3849
3850 @defun cl-nunion list1 list2 @t{&key :test :test-not :key}
3851 This is a destructive version of @code{cl-union}; rather than copying,
3852 it tries to reuse the storage of the argument lists if possible.
3853 @end defun
3854
3855 @defun cl-intersection list1 list2 @t{&key :test :test-not :key}
3856 This function computes the intersection of the sets represented
3857 by @var{list1} and @var{list2}. It returns the list of items
3858 which appear in both @var{list1} and @var{list2}.
3859 @end defun
3860
3861 @defun cl-nintersection list1 list2 @t{&key :test :test-not :key}
3862 This is a destructive version of @code{cl-intersection}. It
3863 tries to reuse storage of @var{list1} rather than copying.
3864 It does @emph{not} reuse the storage of @var{list2}.
3865 @end defun
3866
3867 @defun cl-set-difference list1 list2 @t{&key :test :test-not :key}
3868 This function computes the ``set difference'' of @var{list1}
3869 and @var{list2}, i.e., the set of elements that appear in
3870 @var{list1} but @emph{not} in @var{list2}.
3871 @end defun
3872
3873 @defun cl-nset-difference list1 list2 @t{&key :test :test-not :key}
3874 This is a destructive @code{cl-set-difference}, which will try
3875 to reuse @var{list1} if possible.
3876 @end defun
3877
3878 @defun cl-set-exclusive-or list1 list2 @t{&key :test :test-not :key}
3879 This function computes the ``set exclusive or'' of @var{list1}
3880 and @var{list2}, i.e., the set of elements that appear in
3881 exactly one of @var{list1} and @var{list2}.
3882 @end defun
3883
3884 @defun cl-nset-exclusive-or list1 list2 @t{&key :test :test-not :key}
3885 This is a destructive @code{cl-set-exclusive-or}, which will try
3886 to reuse @var{list1} and @var{list2} if possible.
3887 @end defun
3888
3889 @defun cl-subsetp list1 list2 @t{&key :test :test-not :key}
3890 This function checks whether @var{list1} represents a subset
3891 of @var{list2}, i.e., whether every element of @var{list1}
3892 also appears in @var{list2}.
3893 @end defun
3894
3895 @node Association Lists
3896 @section Association Lists
3897
3898 @noindent
3899 An @dfn{association list} is a list representing a mapping from
3900 one set of values to another; any list whose elements are cons
3901 cells is an association list.
3902
3903 @defun cl-assoc item a-list @t{&key :test :test-not :key}
3904 This function searches the association list @var{a-list} for an
3905 element whose @code{car} matches (in the sense of @code{:test},
3906 @code{:test-not}, and @code{:key}, or by comparison with @code{eql})
3907 a given @var{item}. It returns the matching element, if any,
3908 otherwise @code{nil}. It ignores elements of @var{a-list} which
3909 are not cons cells. (This corresponds to the behavior of
3910 @code{assq} and @code{assoc} in Emacs Lisp; Common Lisp's
3911 @code{assoc} ignores @code{nil}s but considers any other non-cons
3912 elements of @var{a-list} to be an error.)
3913 @end defun
3914
3915 @defun cl-rassoc item a-list @t{&key :test :test-not :key}
3916 This function searches for an element whose @code{cdr} matches
3917 @var{item}. If @var{a-list} represents a mapping, this applies
3918 the inverse of the mapping to @var{item}.
3919 @end defun
3920
3921 @findex cl-assoc-if
3922 @findex cl-assoc-if-not
3923 @findex cl-rassoc-if
3924 @findex cl-rassoc-if-not
3925 The @code{cl-assoc-if}, @code{cl-assoc-if-not}, @code{cl-rassoc-if},
3926 and @code{cl-rassoc-if-not} functions are defined similarly.
3927
3928 Two simple functions for constructing association lists are:
3929
3930 @defun cl-acons key value alist
3931 This is equivalent to @code{(cons (cons @var{key} @var{value}) @var{alist})}.
3932 @end defun
3933
3934 @defun cl-pairlis keys values &optional alist
3935 This is equivalent to @code{(nconc (cl-mapcar 'cons @var{keys} @var{values})
3936 @var{alist})}.
3937 @end defun
3938
3939 @node Structures
3940 @chapter Structures
3941
3942 @noindent
3943 The Common Lisp @dfn{structure} mechanism provides a general way
3944 to define data types similar to C's @code{struct} types. A
3945 structure is a Lisp object containing some number of @dfn{slots},
3946 each of which can hold any Lisp data object. Functions are
3947 provided for accessing and setting the slots, creating or copying
3948 structure objects, and recognizing objects of a particular structure
3949 type.
3950
3951 In true Common Lisp, each structure type is a new type distinct
3952 from all existing Lisp types. Since the underlying Emacs Lisp
3953 system provides no way to create new distinct types, this package
3954 implements structures as vectors (or lists upon request) with a
3955 special ``tag'' symbol to identify them.
3956
3957 @defmac cl-defstruct name slots@dots{}
3958 The @code{cl-defstruct} form defines a new structure type called
3959 @var{name}, with the specified @var{slots}. (The @var{slots}
3960 may begin with a string which documents the structure type.)
3961 In the simplest case, @var{name} and each of the @var{slots}
3962 are symbols. For example,
3963
3964 @example
3965 (cl-defstruct person name age sex)
3966 @end example
3967
3968 @noindent
3969 defines a struct type called @code{person} which contains three
3970 slots. Given a @code{person} object @var{p}, you can access those
3971 slots by calling @code{(person-name @var{p})}, @code{(person-age @var{p})},
3972 and @code{(person-sex @var{p})}. You can also change these slots by
3973 using @code{setf} on any of these place forms:
3974
3975 @example
3976 (cl-incf (person-age birthday-boy))
3977 @end example
3978
3979 You can create a new @code{person} by calling @code{make-person},
3980 which takes keyword arguments @code{:name}, @code{:age}, and
3981 @code{:sex} to specify the initial values of these slots in the
3982 new object. (Omitting any of these arguments leaves the corresponding
3983 slot ``undefined'', according to the Common Lisp standard; in Emacs
3984 Lisp, such uninitialized slots are filled with @code{nil}.)
3985
3986 Given a @code{person}, @code{(copy-person @var{p})} makes a new
3987 object of the same type whose slots are @code{eq} to those of @var{p}.
3988
3989 Given any Lisp object @var{x}, @code{(person-p @var{x})} returns
3990 true if @var{x} looks like a @code{person}, false otherwise. (Again,
3991 in Common Lisp this predicate would be exact; in Emacs Lisp the
3992 best it can do is verify that @var{x} is a vector of the correct
3993 length which starts with the correct tag symbol.)
3994
3995 Accessors like @code{person-name} normally check their arguments
3996 (effectively using @code{person-p}) and signal an error if the
3997 argument is the wrong type. This check is affected by
3998 @code{(optimize (safety @dots{}))} declarations. Safety level 1,
3999 the default, uses a somewhat optimized check that will detect all
4000 incorrect arguments, but may use an uninformative error message
4001 (e.g., ``expected a vector'' instead of ``expected a @code{person}'').
4002 Safety level 0 omits all checks except as provided by the underlying
4003 @code{aref} call; safety levels 2 and 3 do rigorous checking that will
4004 always print a descriptive error message for incorrect inputs.
4005 @xref{Declarations}.
4006
4007 @example
4008 (setq dave (make-person :name "Dave" :sex 'male))
4009 @result{} [cl-struct-person "Dave" nil male]
4010 (setq other (copy-person dave))
4011 @result{} [cl-struct-person "Dave" nil male]
4012 (eq dave other)
4013 @result{} nil
4014 (eq (person-name dave) (person-name other))
4015 @result{} t
4016 (person-p dave)
4017 @result{} t
4018 (person-p [1 2 3 4])
4019 @result{} nil
4020 (person-p "Bogus")
4021 @result{} nil
4022 (person-p '[cl-struct-person counterfeit person object])
4023 @result{} t
4024 @end example
4025
4026 In general, @var{name} is either a name symbol or a list of a name
4027 symbol followed by any number of @dfn{struct options}; each @var{slot}
4028 is either a slot symbol or a list of the form @samp{(@var{slot-name}
4029 @var{default-value} @var{slot-options}@dots{})}. The @var{default-value}
4030 is a Lisp form which is evaluated any time an instance of the
4031 structure type is created without specifying that slot's value.
4032
4033 Common Lisp defines several slot options, but the only one
4034 implemented in this package is @code{:read-only}. A non-@code{nil}
4035 value for this option means the slot should not be @code{setf}-able;
4036 the slot's value is determined when the object is created and does
4037 not change afterward.
4038
4039 @example
4040 (cl-defstruct person
4041 (name nil :read-only t)
4042 age
4043 (sex 'unknown))
4044 @end example
4045
4046 Any slot options other than @code{:read-only} are ignored.
4047
4048 For obscure historical reasons, structure options take a different
4049 form than slot options. A structure option is either a keyword
4050 symbol, or a list beginning with a keyword symbol possibly followed
4051 by arguments. (By contrast, slot options are key-value pairs not
4052 enclosed in lists.)
4053
4054 @example
4055 (cl-defstruct (person (:constructor create-person)
4056 (:type list)
4057 :named)
4058 name age sex)
4059 @end example
4060
4061 The following structure options are recognized.
4062
4063 @table @code
4064 @item :conc-name
4065 The argument is a symbol whose print name is used as the prefix for
4066 the names of slot accessor functions. The default is the name of
4067 the struct type followed by a hyphen. The option @code{(:conc-name p-)}
4068 would change this prefix to @code{p-}. Specifying @code{nil} as an
4069 argument means no prefix, so that the slot names themselves are used
4070 to name the accessor functions.
4071
4072 @item :constructor
4073 In the simple case, this option takes one argument which is an
4074 alternate name to use for the constructor function. The default
4075 is @code{make-@var{name}}, e.g., @code{make-person}. The above
4076 example changes this to @code{create-person}. Specifying @code{nil}
4077 as an argument means that no standard constructor should be
4078 generated at all.
4079
4080 In the full form of this option, the constructor name is followed
4081 by an arbitrary argument list. @xref{Program Structure}, for a
4082 description of the format of Common Lisp argument lists. All
4083 options, such as @code{&rest} and @code{&key}, are supported.
4084 The argument names should match the slot names; each slot is
4085 initialized from the corresponding argument. Slots whose names
4086 do not appear in the argument list are initialized based on the
4087 @var{default-value} in their slot descriptor. Also, @code{&optional}
4088 and @code{&key} arguments which don't specify defaults take their
4089 defaults from the slot descriptor. It is valid to include arguments
4090 which don't correspond to slot names; these are useful if they are
4091 referred to in the defaults for optional, keyword, or @code{&aux}
4092 arguments which @emph{do} correspond to slots.
4093
4094 You can specify any number of full-format @code{:constructor}
4095 options on a structure. The default constructor is still generated
4096 as well unless you disable it with a simple-format @code{:constructor}
4097 option.
4098
4099 @example
4100 (cl-defstruct
4101 (person
4102 (:constructor nil) ; no default constructor
4103 (:constructor new-person
4104 (name sex &optional (age 0)))
4105 (:constructor new-hound (&key (name "Rover")
4106 (dog-years 0)
4107 &aux (age (* 7 dog-years))
4108 (sex 'canine))))
4109 name age sex)
4110 @end example
4111
4112 The first constructor here takes its arguments positionally rather
4113 than by keyword. (In official Common Lisp terminology, constructors
4114 that work By Order of Arguments instead of by keyword are called
4115 ``BOA constructors''. No, I'm not making this up.) For example,
4116 @code{(new-person "Jane" 'female)} generates a person whose slots
4117 are @code{"Jane"}, 0, and @code{female}, respectively.
4118
4119 The second constructor takes two keyword arguments, @code{:name},
4120 which initializes the @code{name} slot and defaults to @code{"Rover"},
4121 and @code{:dog-years}, which does not itself correspond to a slot
4122 but which is used to initialize the @code{age} slot. The @code{sex}
4123 slot is forced to the symbol @code{canine} with no syntax for
4124 overriding it.
4125
4126 @item :copier
4127 The argument is an alternate name for the copier function for
4128 this type. The default is @code{copy-@var{name}}. @code{nil}
4129 means not to generate a copier function. (In this implementation,
4130 all copier functions are simply synonyms for @code{copy-sequence}.)
4131
4132 @item :predicate
4133 The argument is an alternate name for the predicate which recognizes
4134 objects of this type. The default is @code{@var{name}-p}. @code{nil}
4135 means not to generate a predicate function. (If the @code{:type}
4136 option is used without the @code{:named} option, no predicate is
4137 ever generated.)
4138
4139 In true Common Lisp, @code{typep} is always able to recognize a
4140 structure object even if @code{:predicate} was used. In this
4141 package, @code{cl-typep} simply looks for a function called
4142 @code{@var{typename}-p}, so it will work for structure types
4143 only if they used the default predicate name.
4144
4145 @item :include
4146 This option implements a very limited form of C++-style inheritance.
4147 The argument is the name of another structure type previously
4148 created with @code{cl-defstruct}. The effect is to cause the new
4149 structure type to inherit all of the included structure's slots
4150 (plus, of course, any new slots described by this struct's slot
4151 descriptors). The new structure is considered a ``specialization''
4152 of the included one. In fact, the predicate and slot accessors
4153 for the included type will also accept objects of the new type.
4154
4155 If there are extra arguments to the @code{:include} option after
4156 the included-structure name, these options are treated as replacement
4157 slot descriptors for slots in the included structure, possibly with
4158 modified default values. Borrowing an example from Steele:
4159
4160 @example
4161 (cl-defstruct person name (age 0) sex)
4162 @result{} person
4163 (cl-defstruct (astronaut (:include person (age 45)))
4164 helmet-size
4165 (favorite-beverage 'tang))
4166 @result{} astronaut
4167
4168 (setq joe (make-person :name "Joe"))
4169 @result{} [cl-struct-person "Joe" 0 nil]
4170 (setq buzz (make-astronaut :name "Buzz"))
4171 @result{} [cl-struct-astronaut "Buzz" 45 nil nil tang]
4172
4173 (list (person-p joe) (person-p buzz))
4174 @result{} (t t)
4175 (list (astronaut-p joe) (astronaut-p buzz))
4176 @result{} (nil t)
4177
4178 (person-name buzz)
4179 @result{} "Buzz"
4180 (astronaut-name joe)
4181 @result{} error: "astronaut-name accessing a non-astronaut"
4182 @end example
4183
4184 Thus, if @code{astronaut} is a specialization of @code{person},
4185 then every @code{astronaut} is also a @code{person} (but not the
4186 other way around). Every @code{astronaut} includes all the slots
4187 of a @code{person}, plus extra slots that are specific to
4188 astronauts. Operations that work on people (like @code{person-name})
4189 work on astronauts just like other people.
4190
4191 @item :print-function
4192 In full Common Lisp, this option allows you to specify a function
4193 which is called to print an instance of the structure type. The
4194 Emacs Lisp system offers no hooks into the Lisp printer which would
4195 allow for such a feature, so this package simply ignores
4196 @code{:print-function}.
4197
4198 @item :type
4199 The argument should be one of the symbols @code{vector} or @code{list}.
4200 This tells which underlying Lisp data type should be used to implement
4201 the new structure type. Vectors are used by default, but
4202 @code{(:type list)} will cause structure objects to be stored as
4203 lists instead.
4204
4205 The vector representation for structure objects has the advantage
4206 that all structure slots can be accessed quickly, although creating
4207 vectors is a bit slower in Emacs Lisp. Lists are easier to create,
4208 but take a relatively long time accessing the later slots.
4209
4210 @item :named
4211 This option, which takes no arguments, causes a characteristic ``tag''
4212 symbol to be stored at the front of the structure object. Using
4213 @code{:type} without also using @code{:named} will result in a
4214 structure type stored as plain vectors or lists with no identifying
4215 features.
4216
4217 The default, if you don't specify @code{:type} explicitly, is to
4218 use named vectors. Therefore, @code{:named} is only useful in
4219 conjunction with @code{:type}.
4220
4221 @example
4222 (cl-defstruct (person1) name age sex)
4223 (cl-defstruct (person2 (:type list) :named) name age sex)
4224 (cl-defstruct (person3 (:type list)) name age sex)
4225
4226 (setq p1 (make-person1))
4227 @result{} [cl-struct-person1 nil nil nil]
4228 (setq p2 (make-person2))
4229 @result{} (person2 nil nil nil)
4230 (setq p3 (make-person3))
4231 @result{} (nil nil nil)
4232
4233 (person1-p p1)
4234 @result{} t
4235 (person2-p p2)
4236 @result{} t
4237 (person3-p p3)
4238 @result{} error: function person3-p undefined
4239 @end example
4240
4241 Since unnamed structures don't have tags, @code{cl-defstruct} is not
4242 able to make a useful predicate for recognizing them. Also,
4243 accessors like @code{person3-name} will be generated but they
4244 will not be able to do any type checking. The @code{person3-name}
4245 function, for example, will simply be a synonym for @code{car} in
4246 this case. By contrast, @code{person2-name} is able to verify
4247 that its argument is indeed a @code{person2} object before
4248 proceeding.
4249
4250 @item :initial-offset
4251 The argument must be a nonnegative integer. It specifies a
4252 number of slots to be left ``empty'' at the front of the
4253 structure. If the structure is named, the tag appears at the
4254 specified position in the list or vector; otherwise, the first
4255 slot appears at that position. Earlier positions are filled
4256 with @code{nil} by the constructors and ignored otherwise. If
4257 the type @code{:include}s another type, then @code{:initial-offset}
4258 specifies a number of slots to be skipped between the last slot
4259 of the included type and the first new slot.
4260 @end table
4261 @end defmac
4262
4263 Except as noted, the @code{cl-defstruct} facility of this package is
4264 entirely compatible with that of Common Lisp.
4265
4266 @node Assertions
4267 @chapter Assertions and Errors
4268
4269 @noindent
4270 This section describes two macros that test @dfn{assertions}, i.e.,
4271 conditions which must be true if the program is operating correctly.
4272 Assertions never add to the behavior of a Lisp program; they simply
4273 make ``sanity checks'' to make sure everything is as it should be.
4274
4275 If the optimization property @code{speed} has been set to 3, and
4276 @code{safety} is less than 3, then the byte-compiler will optimize
4277 away the following assertions. Because assertions might be optimized
4278 away, it is a bad idea for them to include side-effects.
4279
4280 @defmac cl-assert test-form [show-args string args@dots{}]
4281 This form verifies that @var{test-form} is true (i.e., evaluates to
4282 a non-@code{nil} value). If so, it returns @code{nil}. If the test
4283 is not satisfied, @code{cl-assert} signals an error.
4284
4285 A default error message will be supplied which includes @var{test-form}.
4286 You can specify a different error message by including a @var{string}
4287 argument plus optional extra arguments. Those arguments are simply
4288 passed to @code{error} to signal the error.
4289
4290 If the optional second argument @var{show-args} is @code{t} instead
4291 of @code{nil}, then the error message (with or without @var{string})
4292 will also include all non-constant arguments of the top-level
4293 @var{form}. For example:
4294
4295 @example
4296 (cl-assert (> x 10) t "x is too small: %d")
4297 @end example
4298
4299 This usage of @var{show-args} is an extension to Common Lisp. In
4300 true Common Lisp, the second argument gives a list of @var{places}
4301 which can be @code{setf}'d by the user before continuing from the
4302 error. Since Emacs Lisp does not support continuable errors, it
4303 makes no sense to specify @var{places}.
4304 @end defmac
4305
4306 @defmac cl-check-type form type [string]
4307 This form verifies that @var{form} evaluates to a value of type
4308 @var{type}. If so, it returns @code{nil}. If not, @code{cl-check-type}
4309 signals a @code{wrong-type-argument} error. The default error message
4310 lists the erroneous value along with @var{type} and @var{form}
4311 themselves. If @var{string} is specified, it is included in the
4312 error message in place of @var{type}. For example:
4313
4314 @example
4315 (cl-check-type x (integer 1 *) "a positive integer")
4316 @end example
4317
4318 @xref{Type Predicates}, for a description of the type specifiers
4319 that may be used for @var{type}.
4320
4321 Note that in Common Lisp, the first argument to @code{check-type}
4322 must be a @var{place} suitable for use by @code{setf}, because
4323 @code{check-type} signals a continuable error that allows the
4324 user to modify @var{place}.
4325 @end defmac
4326
4327 @node Efficiency Concerns
4328 @appendix Efficiency Concerns
4329
4330 @appendixsec Macros
4331
4332 @noindent
4333 Many of the advanced features of this package, such as @code{cl-defun},
4334 @code{cl-loop}, etc., are implemented as Lisp macros. In
4335 byte-compiled code, these complex notations will be expanded into
4336 equivalent Lisp code which is simple and efficient. For example,
4337 the form
4338
4339 @example
4340 (cl-incf i n)
4341 @end example
4342
4343 @noindent
4344 is expanded at compile-time to the Lisp form
4345
4346 @example
4347 (setq i (+ i n))
4348 @end example
4349
4350 @noindent
4351 which is the most efficient ways of doing this operation
4352 in Lisp. Thus, there is no performance penalty for using the more
4353 readable @code{cl-incf} form in your compiled code.
4354
4355 @emph{Interpreted} code, on the other hand, must expand these macros
4356 every time they are executed. For this reason it is strongly
4357 recommended that code making heavy use of macros be compiled.
4358 A loop using @code{cl-incf} a hundred times will execute considerably
4359 faster if compiled, and will also garbage-collect less because the
4360 macro expansion will not have to be generated, used, and thrown away a
4361 hundred times.
4362
4363 You can find out how a macro expands by using the
4364 @code{cl-prettyexpand} function.
4365
4366 @defun cl-prettyexpand form &optional full
4367 This function takes a single Lisp form as an argument and inserts
4368 a nicely formatted copy of it in the current buffer (which must be
4369 in Lisp mode so that indentation works properly). It also expands
4370 all Lisp macros which appear in the form. The easiest way to use
4371 this function is to go to the @file{*scratch*} buffer and type, say,
4372
4373 @example
4374 (cl-prettyexpand '(cl-loop for x below 10 collect x))
4375 @end example
4376
4377 @noindent
4378 and type @kbd{C-x C-e} immediately after the closing parenthesis;
4379 the expansion
4380
4381 @example
4382 (cl-block nil
4383 (let* ((x 0)
4384 (G1004 nil))
4385 (while (< x 10)
4386 (setq G1004 (cons x G1004))
4387 (setq x (+ x 1)))
4388 (nreverse G1004)))
4389 @end example
4390
4391 @noindent
4392 will be inserted into the buffer. (The @code{cl-block} macro is
4393 expanded differently in the interpreter and compiler, so
4394 @code{cl-prettyexpand} just leaves it alone. The temporary
4395 variable @code{G1004} was created by @code{cl-gensym}.)
4396
4397 If the optional argument @var{full} is true, then @emph{all}
4398 macros are expanded, including @code{cl-block}, @code{cl-eval-when},
4399 and compiler macros. Expansion is done as if @var{form} were
4400 a top-level form in a file being compiled. For example,
4401
4402 @example
4403 (cl-prettyexpand '(cl-pushnew 'x list))
4404 @print{} (setq list (cl-adjoin 'x list))
4405 (cl-prettyexpand '(cl-pushnew 'x list) t)
4406 @print{} (setq list (if (memq 'x list) list (cons 'x list)))
4407 (cl-prettyexpand '(caddr (cl-member 'a list)) t)
4408 @print{} (car (cdr (cdr (memq 'a list))))
4409 @end example
4410
4411 Note that @code{cl-adjoin}, @code{cl-caddr}, and @code{cl-member} all
4412 have built-in compiler macros to optimize them in common cases.
4413 @end defun
4414
4415 @ifinfo
4416 @example
4417
4418 @end example
4419 @end ifinfo
4420 @appendixsec Error Checking
4421
4422 @noindent
4423 Common Lisp compliance has in general not been sacrificed for the
4424 sake of efficiency. A few exceptions have been made for cases
4425 where substantial gains were possible at the expense of marginal
4426 incompatibility.
4427
4428 The Common Lisp standard (as embodied in Steele's book) uses the
4429 phrase ``it is an error if'' to indicate a situation which is not
4430 supposed to arise in complying programs; implementations are strongly
4431 encouraged but not required to signal an error in these situations.
4432 This package sometimes omits such error checking in the interest of
4433 compactness and efficiency. For example, @code{cl-do} variable
4434 specifiers are supposed to be lists of one, two, or three forms;
4435 extra forms are ignored by this package rather than signaling a
4436 syntax error. The @code{cl-endp} function is simply a synonym for
4437 @code{null} in this package. Functions taking keyword arguments
4438 will accept an odd number of arguments, treating the trailing
4439 keyword as if it were followed by the value @code{nil}.
4440
4441 Argument lists (as processed by @code{cl-defun} and friends)
4442 @emph{are} checked rigorously except for the minor point just
4443 mentioned; in particular, keyword arguments are checked for
4444 validity, and @code{&allow-other-keys} and @code{:allow-other-keys}
4445 are fully implemented. Keyword validity checking is slightly
4446 time consuming (though not too bad in byte-compiled code);
4447 you can use @code{&allow-other-keys} to omit this check. Functions
4448 defined in this package such as @code{cl-find} and @code{cl-member}
4449 do check their keyword arguments for validity.
4450
4451 @ifinfo
4452 @example
4453
4454 @end example
4455 @end ifinfo
4456 @appendixsec Optimizing Compiler
4457
4458 @noindent
4459 Use of the optimizing Emacs compiler is highly recommended; many of the Common
4460 Lisp macros emit
4461 code which can be improved by optimization. In particular,
4462 @code{cl-block}s (whether explicit or implicit in constructs like
4463 @code{cl-defun} and @code{cl-loop}) carry a fair run-time penalty; the
4464 optimizing compiler removes @code{cl-block}s which are not actually
4465 referenced by @code{cl-return} or @code{cl-return-from} inside the block.
4466
4467 @node Common Lisp Compatibility
4468 @appendix Common Lisp Compatibility
4469
4470 @noindent
4471 Following is a list of all known incompatibilities between this
4472 package and Common Lisp as documented in Steele (2nd edition).
4473
4474 The word @code{cl-defun} is required instead of @code{defun} in order
4475 to use extended Common Lisp argument lists in a function. Likewise,
4476 @code{cl-defmacro} and @code{cl-function} are versions of those forms
4477 which understand full-featured argument lists. The @code{&whole}
4478 keyword does not work in @code{defmacro} argument lists (except
4479 inside recursive argument lists).
4480
4481 The @code{equal} predicate does not distinguish
4482 between IEEE floating-point plus and minus zero. The @code{cl-equalp}
4483 predicate has several differences with Common Lisp; @pxref{Predicates}.
4484
4485 @c FIXME no longer provided by cl.
4486 The @code{setf} mechanism is entirely compatible, except that
4487 setf-methods return a list of five values rather than five
4488 values directly. Also, the new ``@code{setf} function'' concept
4489 (typified by @code{(defun (setf foo) @dots{})}) is not implemented.
4490
4491 The @code{cl-do-all-symbols} form is the same as @code{cl-do-symbols}
4492 with no @var{obarray} argument. In Common Lisp, this form would
4493 iterate over all symbols in all packages. Since Emacs obarrays
4494 are not a first-class package mechanism, there is no way for
4495 @code{cl-do-all-symbols} to locate any but the default obarray.
4496
4497 The @code{cl-loop} macro is complete except that @code{loop-finish}
4498 and type specifiers are unimplemented.
4499
4500 The multiple-value return facility treats lists as multiple
4501 values, since Emacs Lisp cannot support multiple return values
4502 directly. The macros will be compatible with Common Lisp if
4503 @code{cl-values} or @code{cl-values-list} is always used to return to
4504 a @code{cl-multiple-value-bind} or other multiple-value receiver;
4505 if @code{cl-values} is used without @code{cl-multiple-value-@dots{}}
4506 or vice-versa the effect will be different from Common Lisp.
4507
4508 Many Common Lisp declarations are ignored, and others match
4509 the Common Lisp standard in concept but not in detail. For
4510 example, local @code{special} declarations, which are purely
4511 advisory in Emacs Lisp, do not rigorously obey the scoping rules
4512 set down in Steele's book.
4513
4514 The variable @code{cl--gensym-counter} starts out with a pseudo-random
4515 value rather than with zero. This is to cope with the fact that
4516 generated symbols become interned when they are written to and
4517 loaded back from a file.
4518
4519 The @code{cl-defstruct} facility is compatible, except that structures
4520 are of type @code{:type vector :named} by default rather than some
4521 special, distinct type. Also, the @code{:type} slot option is ignored.
4522
4523 The second argument of @code{cl-check-type} is treated differently.
4524
4525 @node Porting Common Lisp
4526 @appendix Porting Common Lisp
4527
4528 @noindent
4529 This package is meant to be used as an extension to Emacs Lisp,
4530 not as an Emacs implementation of true Common Lisp. Some of the
4531 remaining differences between Emacs Lisp and Common Lisp make it
4532 difficult to port large Common Lisp applications to Emacs. For
4533 one, some of the features in this package are not fully compliant
4534 with ANSI or Steele; @pxref{Common Lisp Compatibility}. But there
4535 are also quite a few features that this package does not provide
4536 at all. Here are some major omissions that you will want to watch out
4537 for when bringing Common Lisp code into Emacs.
4538
4539 @itemize @bullet
4540 @item
4541 Case-insensitivity. Symbols in Common Lisp are case-insensitive
4542 by default. Some programs refer to a function or variable as
4543 @code{foo} in one place and @code{Foo} or @code{FOO} in another.
4544 Emacs Lisp will treat these as three distinct symbols.
4545
4546 Some Common Lisp code is written entirely in upper case. While Emacs
4547 is happy to let the program's own functions and variables use
4548 this convention, calls to Lisp builtins like @code{if} and
4549 @code{defun} will have to be changed to lower case.
4550
4551 @item
4552 Lexical scoping. In Common Lisp, function arguments and @code{let}
4553 bindings apply only to references physically within their bodies (or
4554 within macro expansions in their bodies). Traditionally, Emacs Lisp
4555 uses @dfn{dynamic scoping} wherein a binding to a variable is visible
4556 even inside functions called from the body.
4557 @xref{Dynamic Binding,,,elisp,GNU Emacs Lisp Reference Manual}.
4558 Lexical binding is available since Emacs 24.1, so be sure to set
4559 @code{lexical-binding} to @code{t} if you need to emulate this aspect
4560 of Common Lisp. @xref{Lexical Binding,,,elisp,GNU Emacs Lisp Reference Manual}.
4561
4562 Here is an example of a Common Lisp code fragment that would fail in
4563 Emacs Lisp if @code{lexical-binding} were set to @code{nil}:
4564
4565 @example
4566 (defun map-odd-elements (func list)
4567 (loop for x in list
4568 for flag = t then (not flag)
4569 collect (if flag x (funcall func x))))
4570
4571 (defun add-odd-elements (list x)
4572 (map-odd-elements (lambda (a) (+ a x)) list))
4573 @end example
4574
4575 @noindent
4576 With lexical binding, the two functions' usages of @code{x} are
4577 completely independent. With dynamic binding, the binding to @code{x}
4578 made by @code{add-odd-elements} will have been hidden by the binding
4579 in @code{map-odd-elements} by the time the @code{(+ a x)} function is
4580 called.
4581
4582 Internally, this package uses lexical binding so that such problems do
4583 not occur. @xref{Lexical Bindings}, for a description of the obsolete
4584 @code{lexical-let} form that emulates a Common Lisp-style lexical
4585 binding when dynamic binding is in use.
4586
4587 @item
4588 Reader macros. Common Lisp includes a second type of macro that
4589 works at the level of individual characters. For example, Common
4590 Lisp implements the quote notation by a reader macro called @code{'},
4591 whereas Emacs Lisp's parser just treats quote as a special case.
4592 Some Lisp packages use reader macros to create special syntaxes
4593 for themselves, which the Emacs parser is incapable of reading.
4594
4595 @item
4596 Other syntactic features. Common Lisp provides a number of
4597 notations beginning with @code{#} that the Emacs Lisp parser
4598 won't understand. For example, @samp{#| ... |#} is an
4599 alternate comment notation, and @samp{#+lucid (foo)} tells
4600 the parser to ignore the @code{(foo)} except in Lucid Common
4601 Lisp.
4602
4603 @item
4604 Packages. In Common Lisp, symbols are divided into @dfn{packages}.
4605 Symbols that are Lisp built-ins are typically stored in one package;
4606 symbols that are vendor extensions are put in another, and each
4607 application program would have a package for its own symbols.
4608 Certain symbols are ``exported'' by a package and others are
4609 internal; certain packages ``use'' or import the exported symbols
4610 of other packages. To access symbols that would not normally be
4611 visible due to this importing and exporting, Common Lisp provides
4612 a syntax like @code{package:symbol} or @code{package::symbol}.
4613
4614 Emacs Lisp has a single namespace for all interned symbols, and
4615 then uses a naming convention of putting a prefix like @code{cl-}
4616 in front of the name. Some Emacs packages adopt the Common Lisp-like
4617 convention of using @code{cl:} or @code{cl::} as the prefix.
4618 However, the Emacs parser does not understand colons and just
4619 treats them as part of the symbol name. Thus, while @code{mapcar}
4620 and @code{lisp:mapcar} may refer to the same symbol in Common
4621 Lisp, they are totally distinct in Emacs Lisp. Common Lisp
4622 programs which refer to a symbol by the full name sometimes
4623 and the short name other times will not port cleanly to Emacs.
4624
4625 Emacs Lisp does have a concept of ``obarrays'', which are
4626 package-like collections of symbols, but this feature is not
4627 strong enough to be used as a true package mechanism.
4628
4629 @item
4630 The @code{format} function is quite different between Common
4631 Lisp and Emacs Lisp. It takes an additional ``destination''
4632 argument before the format string. A destination of @code{nil}
4633 means to format to a string as in Emacs Lisp; a destination
4634 of @code{t} means to write to the terminal (similar to
4635 @code{message} in Emacs). Also, format control strings are
4636 utterly different; @code{~} is used instead of @code{%} to
4637 introduce format codes, and the set of available codes is
4638 much richer. There are no notations like @code{\n} for
4639 string literals; instead, @code{format} is used with the
4640 ``newline'' format code, @code{~%}. More advanced formatting
4641 codes provide such features as paragraph filling, case
4642 conversion, and even loops and conditionals.
4643
4644 While it would have been possible to implement most of Common
4645 Lisp @code{format} in this package (under the name @code{cl-format},
4646 of course), it was not deemed worthwhile. It would have required
4647 a huge amount of code to implement even a decent subset of
4648 @code{cl-format}, yet the functionality it would provide over
4649 Emacs Lisp's @code{format} would rarely be useful.
4650
4651 @item
4652 Vector constants use square brackets in Emacs Lisp, but
4653 @code{#(a b c)} notation in Common Lisp. To further complicate
4654 matters, Emacs has its own @code{#(} notation for
4655 something entirely different---strings with properties.
4656
4657 @item
4658 Characters are distinct from integers in Common Lisp. The notation
4659 for character constants is also different: @code{#\A} in Common Lisp
4660 where Emacs Lisp uses @code{?A}. Also, @code{string=} and
4661 @code{string-equal} are synonyms in Emacs Lisp, whereas the latter is
4662 case-insensitive in Common Lisp.
4663
4664 @item
4665 Data types. Some Common Lisp data types do not exist in Emacs
4666 Lisp. Rational numbers and complex numbers are not present,
4667 nor are large integers (all integers are ``fixnums''). All
4668 arrays are one-dimensional. There are no readtables or pathnames;
4669 streams are a set of existing data types rather than a new data
4670 type of their own. Hash tables, random-states, structures, and
4671 packages (obarrays) are built from Lisp vectors or lists rather
4672 than being distinct types.
4673
4674 @item
4675 The Common Lisp Object System (CLOS) is not implemented,
4676 nor is the Common Lisp Condition System. However, the EIEIO package
4677 (@pxref{Top, , Introduction, eieio, EIEIO}) does implement some
4678 CLOS functionality.
4679
4680 @item
4681 Common Lisp features that are completely redundant with Emacs
4682 Lisp features of a different name generally have not been
4683 implemented. For example, Common Lisp writes @code{defconstant}
4684 where Emacs Lisp uses @code{defconst}. Similarly, @code{make-list}
4685 takes its arguments in different ways in the two Lisps but does
4686 exactly the same thing, so this package has not bothered to
4687 implement a Common Lisp-style @code{make-list}.
4688
4689 @item
4690 A few more notable Common Lisp features not included in this
4691 package: @code{compiler-let}, @code{tagbody}, @code{prog},
4692 @code{ldb/dpb}, @code{parse-integer}, @code{cerror}.
4693
4694 @item
4695 Recursion. While recursion works in Emacs Lisp just like it
4696 does in Common Lisp, various details of the Emacs Lisp system
4697 and compiler make recursion much less efficient than it is in
4698 most Lisps. Some schools of thought prefer to use recursion
4699 in Lisp over other techniques; they would sum a list of
4700 numbers using something like
4701
4702 @example
4703 (defun sum-list (list)
4704 (if list
4705 (+ (car list) (sum-list (cdr list)))
4706 0))
4707 @end example
4708
4709 @noindent
4710 where a more iteratively-minded programmer might write one of
4711 these forms:
4712
4713 @example
4714 (let ((total 0)) (dolist (x my-list) (cl-incf total x)) total)
4715 (cl-loop for x in my-list sum x)
4716 @end example
4717
4718 While this would be mainly a stylistic choice in most Common Lisps,
4719 in Emacs Lisp you should be aware that the iterative forms are
4720 much faster than recursion. Also, Lisp programmers will want to
4721 note that the current Emacs Lisp compiler does not optimize tail
4722 recursion.
4723 @end itemize
4724
4725 @node Obsolete Features
4726 @appendix Obsolete Features
4727
4728 This section describes some features of the package that are obsolete
4729 and should not be used in new code. They are either only provided by
4730 the old @file{cl.el} entry point, not by the newer @file{cl-lib.el};
4731 or where versions with a @samp{cl-} prefix do exist they do not behave
4732 in exactly the same way.
4733
4734 @menu
4735 * Lexical Bindings:: An approximation of lexical binding.
4736 * Obsolete Lexical Macros:: Obsolete macros using lexical-let.
4737 * Obsolete Setf Customization:: Obsolete ways to customize setf.
4738 @end menu
4739
4740 @node Lexical Bindings
4741 @appendixsec Lexical Bindings
4742
4743 The following macros are extensions to Common Lisp, where all bindings
4744 are lexical unless declared otherwise. These features are likewise
4745 obsolete since the introduction of true lexical binding in Emacs 24.1.
4746
4747 @defmac lexical-let (bindings@dots{}) forms@dots{}
4748 This form is exactly like @code{let} except that the bindings it
4749 establishes are purely lexical.
4750 @end defmac
4751
4752 @c FIXME remove this and refer to elisp manual.
4753 @c Maybe merge some stuff from here to there?
4754 @noindent
4755 Lexical bindings are similar to local variables in a language like C:
4756 Only the code physically within the body of the @code{lexical-let}
4757 (after macro expansion) may refer to the bound variables.
4758
4759 @example
4760 (setq a 5)
4761 (defun foo (b) (+ a b))
4762 (let ((a 2)) (foo a))
4763 @result{} 4
4764 (lexical-let ((a 2)) (foo a))
4765 @result{} 7
4766 @end example
4767
4768 @noindent
4769 In this example, a regular @code{let} binding of @code{a} actually
4770 makes a temporary change to the global variable @code{a}, so @code{foo}
4771 is able to see the binding of @code{a} to 2. But @code{lexical-let}
4772 actually creates a distinct local variable @code{a} for use within its
4773 body, without any effect on the global variable of the same name.
4774
4775 The most important use of lexical bindings is to create @dfn{closures}.
4776 A closure is a function object that refers to an outside lexical
4777 variable (@pxref{Closures,,,elisp,GNU Emacs Lisp Reference Manual}).
4778 For example:
4779
4780 @example
4781 (defun make-adder (n)
4782 (lexical-let ((n n))
4783 (function (lambda (m) (+ n m)))))
4784 (setq add17 (make-adder 17))
4785 (funcall add17 4)
4786 @result{} 21
4787 @end example
4788
4789 @noindent
4790 The call @code{(make-adder 17)} returns a function object which adds
4791 17 to its argument. If @code{let} had been used instead of
4792 @code{lexical-let}, the function object would have referred to the
4793 global @code{n}, which would have been bound to 17 only during the
4794 call to @code{make-adder} itself.
4795
4796 @example
4797 (defun make-counter ()
4798 (lexical-let ((n 0))
4799 (cl-function (lambda (&optional (m 1)) (cl-incf n m)))))
4800 (setq count-1 (make-counter))
4801 (funcall count-1 3)
4802 @result{} 3
4803 (funcall count-1 14)
4804 @result{} 17
4805 (setq count-2 (make-counter))
4806 (funcall count-2 5)
4807 @result{} 5
4808 (funcall count-1 2)
4809 @result{} 19
4810 (funcall count-2)
4811 @result{} 6
4812 @end example
4813
4814 @noindent
4815 Here we see that each call to @code{make-counter} creates a distinct
4816 local variable @code{n}, which serves as a private counter for the
4817 function object that is returned.
4818
4819 Closed-over lexical variables persist until the last reference to
4820 them goes away, just like all other Lisp objects. For example,
4821 @code{count-2} refers to a function object which refers to an
4822 instance of the variable @code{n}; this is the only reference
4823 to that variable, so after @code{(setq count-2 nil)} the garbage
4824 collector would be able to delete this instance of @code{n}.
4825 Of course, if a @code{lexical-let} does not actually create any
4826 closures, then the lexical variables are free as soon as the
4827 @code{lexical-let} returns.
4828
4829 Many closures are used only during the extent of the bindings they
4830 refer to; these are known as ``downward funargs'' in Lisp parlance.
4831 When a closure is used in this way, regular Emacs Lisp dynamic
4832 bindings suffice and will be more efficient than @code{lexical-let}
4833 closures:
4834
4835 @example
4836 (defun add-to-list (x list)
4837 (mapcar (lambda (y) (+ x y))) list)
4838 (add-to-list 7 '(1 2 5))
4839 @result{} (8 9 12)
4840 @end example
4841
4842 @noindent
4843 Since this lambda is only used while @code{x} is still bound,
4844 it is not necessary to make a true closure out of it.
4845
4846 You can use @code{defun} or @code{flet} inside a @code{lexical-let}
4847 to create a named closure. If several closures are created in the
4848 body of a single @code{lexical-let}, they all close over the same
4849 instance of the lexical variable.
4850
4851 @defmac lexical-let* (bindings@dots{}) forms@dots{}
4852 This form is just like @code{lexical-let}, except that the bindings
4853 are made sequentially in the manner of @code{let*}.
4854 @end defmac
4855
4856 @node Obsolete Lexical Macros
4857 @appendixsec Macros Defined Using Lexical-Let
4858
4859 The following macros are defined using @code{lexical-let}.
4860 They are replaced by versions with a @samp{cl-} prefix that use true
4861 lexical binding (and hence rely on @code{lexical-binding} being set to
4862 @code{t} in code using them).
4863
4864 @defmac flet (bindings@dots{}) forms@dots{}
4865 Replaced by @code{cl-flet} (@pxref{Function Bindings})
4866 or @code{cl-letf} (@pxref{Modify Macros}).
4867 @end defmac
4868
4869 @defmac labels (bindings@dots{}) forms@dots{}
4870 Replaced by @code{cl-labels} (@pxref{Function Bindings}).
4871 @end defmac
4872
4873 @defmac letf (bindings@dots{}) forms@dots{}
4874 Replaced by @code{cl-letf} (@pxref{Modify Macros}).
4875 @end defmac
4876
4877 @node Obsolete Setf Customization
4878 @appendixsec Obsolete Ways to Customize Setf
4879
4880 Common Lisp defines three macros, @code{define-modify-macro},
4881 @code{defsetf}, and @code{define-setf-method}, that allow the
4882 user to extend generalized variables in various ways.
4883 In Emacs, these are obsolete, replaced by various features of
4884 @file{gv.el} in Emacs 24.3.
4885 @c FIXME details.
4886
4887 @defmac define-modify-macro name arglist function [doc-string]
4888 This macro defines a ``read-modify-write'' macro similar to
4889 @code{cl-incf} and @code{cl-decf}. The macro @var{name} is defined
4890 to take a @var{place} argument followed by additional arguments
4891 described by @var{arglist}. The call
4892
4893 @example
4894 (@var{name} @var{place} @var{args}...)
4895 @end example
4896
4897 @noindent
4898 will be expanded to
4899
4900 @example
4901 (cl-callf @var{func} @var{place} @var{args}...)
4902 @end example
4903
4904 @noindent
4905 which in turn is roughly equivalent to
4906
4907 @example
4908 (setf @var{place} (@var{func} @var{place} @var{args}...))
4909 @end example
4910
4911 For example:
4912
4913 @example
4914 (define-modify-macro cl-incf (&optional (n 1)) +)
4915 (define-modify-macro cl-concatf (&rest args) concat)
4916 @end example
4917
4918 Note that @code{&key} is not allowed in @var{arglist}, but
4919 @code{&rest} is sufficient to pass keywords on to the function.
4920
4921 Most of the modify macros defined by Common Lisp do not exactly
4922 follow the pattern of @code{define-modify-macro}. For example,
4923 @code{push} takes its arguments in the wrong order, and @code{pop}
4924 is completely irregular. You can define these macros ``by hand''
4925 using @code{get-setf-method}, or consult the source
4926 to see how to use the internal @code{setf} building blocks.
4927 @end defmac
4928
4929 @defmac defsetf access-fn update-fn
4930 This is the simpler of two @code{defsetf} forms. Where
4931 @var{access-fn} is the name of a function which accesses a place,
4932 this declares @var{update-fn} to be the corresponding store
4933 function. From now on,
4934
4935 @example
4936 (setf (@var{access-fn} @var{arg1} @var{arg2} @var{arg3}) @var{value})
4937 @end example
4938
4939 @noindent
4940 will be expanded to
4941
4942 @example
4943 (@var{update-fn} @var{arg1} @var{arg2} @var{arg3} @var{value})
4944 @end example
4945
4946 @noindent
4947 The @var{update-fn} is required to be either a true function, or
4948 a macro which evaluates its arguments in a function-like way. Also,
4949 the @var{update-fn} is expected to return @var{value} as its result.
4950 Otherwise, the above expansion would not obey the rules for the way
4951 @code{setf} is supposed to behave.
4952
4953 As a special (non-Common-Lisp) extension, a third argument of @code{t}
4954 to @code{defsetf} says that the @code{update-fn}'s return value is
4955 not suitable, so that the above @code{setf} should be expanded to
4956 something more like
4957
4958 @example
4959 (let ((temp @var{value}))
4960 (@var{update-fn} @var{arg1} @var{arg2} @var{arg3} temp)
4961 temp)
4962 @end example
4963
4964 Some examples of the use of @code{defsetf}, drawn from the standard
4965 suite of setf methods, are:
4966
4967 @example
4968 (defsetf car setcar)
4969 (defsetf symbol-value set)
4970 (defsetf buffer-name rename-buffer t)
4971 @end example
4972 @end defmac
4973
4974 @defmac defsetf access-fn arglist (store-var) forms@dots{}
4975 This is the second, more complex, form of @code{defsetf}. It is
4976 rather like @code{defmacro} except for the additional @var{store-var}
4977 argument. The @var{forms} should return a Lisp form which stores
4978 the value of @var{store-var} into the generalized variable formed
4979 by a call to @var{access-fn} with arguments described by @var{arglist}.
4980 The @var{forms} may begin with a string which documents the @code{setf}
4981 method (analogous to the doc string that appears at the front of a
4982 function).
4983
4984 For example, the simple form of @code{defsetf} is shorthand for
4985
4986 @example
4987 (defsetf @var{access-fn} (&rest args) (store)
4988 (append '(@var{update-fn}) args (list store)))
4989 @end example
4990
4991 The Lisp form that is returned can access the arguments from
4992 @var{arglist} and @var{store-var} in an unrestricted fashion;
4993 macros like @code{setf} and @code{cl-incf} which invoke this
4994 setf-method will insert temporary variables as needed to make
4995 sure the apparent order of evaluation is preserved.
4996
4997 Another example drawn from the standard package:
4998
4999 @example
5000 (defsetf nth (n x) (store)
5001 (list 'setcar (list 'nthcdr n x) store))
5002 @end example
5003 @end defmac
5004
5005 @defmac define-setf-method access-fn arglist forms@dots{}
5006 This is the most general way to create new place forms. When
5007 a @code{setf} to @var{access-fn} with arguments described by
5008 @var{arglist} is expanded, the @var{forms} are evaluated and
5009 must return a list of five items:
5010
5011 @enumerate
5012 @item
5013 A list of @dfn{temporary variables}.
5014
5015 @item
5016 A list of @dfn{value forms} corresponding to the temporary variables
5017 above. The temporary variables will be bound to these value forms
5018 as the first step of any operation on the generalized variable.
5019
5020 @item
5021 A list of exactly one @dfn{store variable} (generally obtained
5022 from a call to @code{gensym}).
5023
5024 @item
5025 A Lisp form which stores the contents of the store variable into
5026 the generalized variable, assuming the temporaries have been
5027 bound as described above.
5028
5029 @item
5030 A Lisp form which accesses the contents of the generalized variable,
5031 assuming the temporaries have been bound.
5032 @end enumerate
5033
5034 This is exactly like the Common Lisp macro of the same name,
5035 except that the method returns a list of five values rather
5036 than the five values themselves, since Emacs Lisp does not
5037 support Common Lisp's notion of multiple return values.
5038
5039 Once again, the @var{forms} may begin with a documentation string.
5040
5041 A setf-method should be maximally conservative with regard to
5042 temporary variables. In the setf-methods generated by
5043 @code{defsetf}, the second return value is simply the list of
5044 arguments in the place form, and the first return value is a
5045 list of a corresponding number of temporary variables generated
5046 by @code{cl-gensym}. Macros like @code{setf} and @code{cl-incf} which
5047 use this setf-method will optimize away most temporaries that
5048 turn out to be unnecessary, so there is little reason for the
5049 setf-method itself to optimize.
5050 @end defmac
5051
5052 @defun get-setf-method place &optional env
5053 This function returns the setf-method for @var{place}, by
5054 invoking the definition previously recorded by @code{defsetf}
5055 or @code{define-setf-method}. The result is a list of five
5056 values as described above. You can use this function to build
5057 your own @code{cl-incf}-like modify macros. (Actually, it is
5058 @c FIXME?
5059 better to use the internal functions @code{cl-setf-do-modify}
5060 and @code{cl-setf-do-store}, which are a bit easier to use and
5061 which also do a number of optimizations; consult the source
5062 code for the @code{cl-incf} function for a simple example.)
5063
5064 The argument @var{env} specifies the ``environment'' to be
5065 passed on to @code{macroexpand} if @code{get-setf-method} should
5066 need to expand a macro in @var{place}. It should come from
5067 an @code{&environment} argument to the macro or setf-method
5068 that called @code{get-setf-method}.
5069
5070 See also the source code for the setf-methods for @code{apply}
5071 and @code{substring}, each of which works by calling
5072 @code{get-setf-method} on a simpler case, then massaging
5073 the result in various ways.
5074 @end defun
5075
5076 Modern Common Lisp defines a second, independent way to specify
5077 the @code{setf} behavior of a function, namely ``@code{setf}
5078 functions'' whose names are lists @code{(setf @var{name})}
5079 rather than symbols. For example, @code{(defun (setf foo) @dots{})}
5080 defines the function that is used when @code{setf} is applied to
5081 @code{foo}. This package does not currently support @code{setf}
5082 functions. In particular, it is a compile-time error to use
5083 @code{setf} on a form which has not already been @code{defsetf}'d
5084 or otherwise declared; in newer Common Lisps, this would not be
5085 an error since the function @code{(setf @var{func})} might be
5086 defined later.
5087
5088
5089 @node GNU Free Documentation License
5090 @appendix GNU Free Documentation License
5091 @include doclicense.texi
5092
5093 @node Function Index
5094 @unnumbered Function Index
5095
5096 @printindex fn
5097
5098 @node Variable Index
5099 @unnumbered Variable Index
5100
5101 @printindex vr
5102
5103 @bye
5104