\input texinfo @c -*-texinfo-*-@setfilename ../info/cl@settitle Common Lisp Extensions@copyingThis file documents the GNU Emacs Common Lisp emulation package.Copyright @copyright{} 1993, 2002, 2003, 2004, 2005, 2006 FreeSoftware Foundation, Inc.@quotationPermission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.2 orany later version published by the Free Software Foundation; with noInvariant Sections, with the Front-Cover texts being ``A GNUManual'', and with the Back-Cover Texts as in (a) below. A copy of thelicense is included in the section entitled ``GNU Free DocumentationLicense'' in the Emacs manual.(a) The FSF's Back-Cover Text is: ``You have freedom to copy and modifythis GNU Manual, like GNU software. Copies published by the FreeSoftware Foundation raise funds for GNU development.''This document is part of a collection distributed under the GNU FreeDocumentation License. If you want to distribute this documentseparately from the collection, you can do so by adding a copy of thelicense to the document, as described in section 6 of the license.@end quotation@end copying@dircategory Emacs@direntry* CL: (cl). Partial Common Lisp support for Emacs Lisp.@end direntry@finalout@titlepage@sp 6@center @titlefont{Common Lisp Extensions}@sp 4@center For GNU Emacs Lisp@sp 1@center Version 2.02@sp 5@center Dave Gillespie@center daveg@@synaptics.com@page@vskip 0pt plus 1filll@insertcopying@end titlepage@node Top, Overview, (dir), (dir)@chapter Introduction@noindentThis document describes a set of Emacs Lisp facilities borrowed fromCommon Lisp. All the facilities are described here in detail. Whilethis document does not assume any prior knowledge of Common Lisp, itdoes assume a basic familiarity with Emacs Lisp.@menu* Overview:: Installation, usage, etc.* Program Structure:: Arglists, `eval-when', `defalias'* Predicates:: `typep', `eql', and `equalp'* Control Structure:: `setf', `do', `loop', etc.* Macros:: Destructuring, `define-compiler-macro'* Declarations:: `proclaim', `declare', etc.* Symbols:: Property lists, `gensym'* Numbers:: Predicates, functions, random numbers* Sequences:: Mapping, functions, searching, sorting* Lists:: `cadr', `sublis', `member*', `assoc*', etc.* Structures:: `defstruct'* Assertions:: `check-type', `assert', `ignore-errors'.* Efficiency Concerns:: Hints and techniques* Common Lisp Compatibility:: All known differences with Steele* Old CL Compatibility:: All known differences with old cl.el* Porting Common Lisp:: Hints for porting Common Lisp code* Function Index::* Variable Index::@end menu@node Overview, Program Structure, Top, Top@ifnottex@chapter Overview@end ifnottex@noindentCommon Lisp is a huge language, and Common Lisp systems tend to bemassive and extremely complex. Emacs Lisp, by contrast, is ratherminimalist in the choice of Lisp features it offers the programmer.As Emacs Lisp programmers have grown in number, and the applicationsthey write have grown more ambitious, it has become clear that EmacsLisp could benefit from many of the conveniences of Common Lisp.The @dfn{CL} package adds a number of Common Lisp functions andcontrol structures to Emacs Lisp. While not a 100% completeimplementation of Common Lisp, @dfn{CL} adds enough functionalityto make Emacs Lisp programming significantly more convenient.@strong{Please note:} the @dfn{CL} functions are not standard parts ofthe Emacs Lisp name space, so it is legitimate for users to definethem with other, conflicting meanings. To avoid conflicting withthose user activities, we have a policy that packages installed inEmacs must not load @dfn{CL} at run time. (It is ok for them to load@dfn{CL} at compile time only, with @code{eval-when-compile}, and usethe macros it provides.) If you are writing packages that you plan todistribute and invite widespread use for, you might want to observethe same rule.Some Common Lisp features have been omitted from this packagefor various reasons:@itemize @bullet@itemSome features are too complex or bulky relative to their benefitto Emacs Lisp programmers. CLOS and Common Lisp streams are fineexamples of this group.@itemOther features cannot be implemented without modification to theEmacs Lisp interpreter itself, such as multiple return values,lexical scoping, case-insensitive symbols, and complex numbers.The @dfn{CL} package generally makes no attempt to emulate thesefeatures.@itemSome features conflict with existing things in Emacs Lisp. Forexample, Emacs' @code{assoc} function is incompatible with theCommon Lisp @code{assoc}. In such cases, this package usuallyadds the suffix @samp{*} to the function name of the CommonLisp version of the function (e.g., @code{assoc*}).@end itemizeThe package described here was written by Dave Gillespie,@file{daveg@@synaptics.com}. It is a total rewrite of the original1986 @file{cl.el} package by Cesar Quiroz. Most features of theQuiroz package have been retained; any incompatibilities arenoted in the descriptions below. Care has been taken in thisversion to ensure that each function is defined efficiently,concisely, and with minimal impact on the rest of the Emacsenvironment.@menu* Usage:: How to use the CL package* Organization:: The package's five component files* Installation:: Compiling and installing CL* Naming Conventions:: Notes on CL function names@end menu@node Usage, Organization, Overview, Overview@section Usage@noindentLisp code that uses features from the @dfn{CL} package shouldinclude at the beginning:@example(require 'cl)@end example@noindentIf you want to ensure that the new (Gillespie) version of @dfn{CL}is the one that is present, add an additional @code{(require 'cl-19)}call:@example(require 'cl)(require 'cl-19)@end example@noindentThe second call will fail (with ``@file{cl-19.el} not found'') ifthe old @file{cl.el} package was in use.It is safe to arrange to load @dfn{CL} at all times, e.g.,in your @file{.emacs} file. But it's a good idea, for portability,to @code{(require 'cl)} in your code even if you do this.@node Organization, Installation, Usage, Overview@section Organization@noindentThe Common Lisp package is organized into four files:@table @file@item cl.elThis is the ``main'' file, which contains basic functionsand information about the package. This file is relativelycompact---about 700 lines.@item cl-extra.elThis file contains the larger, more complex or unusual functions.It is kept separate so that packages which only want to use CommonLisp fundamentals like the @code{cadr} function won't need to paythe overhead of loading the more advanced functions.@item cl-seq.elThis file contains most of the advanced functions for operatingon sequences or lists, such as @code{delete-if} and @code{assoc*}.@item cl-macs.elThis file contains the features of the packages which are macrosinstead of functions. Macros expand when the caller is compiled,not when it is run, so the macros generally only need to bepresent when the byte-compiler is running (or when the macros areused in uncompiled code such as a @file{.emacs} file). Most ofthe macros of this package are isolated in @file{cl-macs.el} sothat they won't take up memory unless you are compiling.@end tableThe file @file{cl.el} includes all necessary @code{autoload}commands for the functions and macros in the other three files.All you have to do is @code{(require 'cl)}, and @file{cl.el}will take care of pulling in the other files when they areneeded.There is another file, @file{cl-compat.el}, which defines someroutines from the older @file{cl.el} package that are no longerpresent in the new package. This includes internal routineslike @code{setelt} and @code{zip-lists}, deprecated featureslike @code{defkeyword}, and an emulation of the old-stylemultiple-values feature. @xref{Old CL Compatibility}.@node Installation, Naming Conventions, Organization, Overview@section Installation@noindentInstallation of the @dfn{CL} package is simple: Just put thebyte-compiled files @file{cl.elc}, @file{cl-extra.elc},@file{cl-seq.elc}, @file{cl-macs.elc}, and @file{cl-compat.elc}into a directory on your @code{load-path}.There are no special requirements to compile this package:The files do not have to be loaded before they are compiled,nor do they need to be compiled in any particular order.You may choose to put the files into your main @file{lisp/}directory, replacing the original @file{cl.el} file there. Or,you could put them into a directory that comes before @file{lisp/}on your @code{load-path} so that the old @file{cl.el} iseffectively hidden.Also, format the @file{cl.texinfo} file and put the resultingInfo files in the @file{info/} directory or another suitable place.You may instead wish to leave this package's components all intheir own directory, and then add this directory to your@code{load-path} and @code{Info-directory-list}.Add the directory to the front of the list so the old @dfn{CL}package and its documentation are hidden.@node Naming Conventions, , Installation, Overview@section Naming Conventions@noindentExcept where noted, all functions defined by this package have thesame names and calling conventions as their Common Lisp counterparts.Following is a complete list of functions whose names were changedfrom Common Lisp, usually to avoid conflicts with Emacs. In eachcase, a @samp{*} has been appended to the Common Lisp name to obtainthe Emacs name:@exampledefun* defsubst* defmacro* function*member* assoc* rassoc* get*remove* delete* mapcar* sort*floor* ceiling* truncate* round*mod* rem* random*@end exampleInternal function and variable names in the package are prefixedby @code{cl-}. Here is a complete list of functions @emph{not}prefixed by @code{cl-} which were not taken from Common Lisp:@examplefloatp-safe lexical-let lexical-let*callf callf2 letf letf*defsubst*@end exampleThe following simple functions and macros are defined in @file{cl.el};they do not cause other components like @file{cl-extra} to be loaded.@exampleeql floatp-safe endpevenp oddp plusp minuspcaaar .. cddddrlist* ldiff rest first .. tenthcopy-list subst mapcar* [2]adjoin [3] acons pairlis pop [4]push [4] pushnew [3,4] incf [4] decf [4]proclaim declaim@end example@noindent[2] Only for one sequence argument or two list arguments.@noindent[3] Only if @code{:test} is @code{eq}, @code{equal}, or unspecified,and @code{:key} is not used.@noindent[4] Only when @var{place} is a plain variable name.@iftex@chapno=4@end iftex@node Program Structure, Predicates, Overview, Top@chapter Program Structure@noindentThis section describes features of the @dfn{CL} package which have todo with programs as a whole: advanced argument lists for functions,and the @code{eval-when} construct.@menu* Argument Lists:: `&key', `&aux', `defun*', `defmacro*'.* Time of Evaluation:: The `eval-when' construct.@end menu@iftex@secno=1@end iftex@node Argument Lists, Time of Evaluation, Program Structure, Program Structure@section Argument Lists@noindentEmacs Lisp's notation for argument lists of functions is a subset ofthe Common Lisp notation. As well as the familiar @code{&optional}and @code{&rest} markers, Common Lisp allows you to specify defaultvalues for optional arguments, and it provides the additional markers@code{&key} and @code{&aux}.Since argument parsing is built-in to Emacs, there is no way forthis package to implement Common Lisp argument lists seamlessly.Instead, this package defines alternates for several Lisp formswhich you must use if you need Common Lisp argument lists.@defspec defun* name arglist body...This form is identical to the regular @code{defun} form, exceptthat @var{arglist} is allowed to be a full Common Lisp argumentlist. Also, the function body is enclosed in an implicit blockcalled @var{name}; @pxref{Blocks and Exits}.@end defspec@defspec defsubst* name arglist body...This is just like @code{defun*}, except that the function thatis defined is automatically proclaimed @code{inline}, i.e.,calls to it may be expanded into in-line code by the byte compiler.This is analogous to the @code{defsubst} form;@code{defsubst*} uses a different method (compiler macros) whichworks in all version of Emacs, and also generates somewhat moreefficient inline expansions. In particular, @code{defsubst*}arranges for the processing of keyword arguments, default values,etc., to be done at compile-time whenever possible.@end defspec@defspec defmacro* name arglist body...This is identical to the regular @code{defmacro} form,except that @var{arglist} is allowed to be a full Common Lispargument list. The @code{&environment} keyword is supported asdescribed in Steele. The @code{&whole} keyword is supported onlywithin destructured lists (see below); top-level @code{&whole}cannot be implemented with the current Emacs Lisp interpreter.The macro expander body is enclosed in an implicit block called@var{name}.@end defspec@defspec function* symbol-or-lambdaThis is identical to the regular @code{function} form,except that if the argument is a @code{lambda} form then thatform may use a full Common Lisp argument list.@end defspecAlso, all forms (such as @code{defsetf} and @code{flet}) definedin this package that include @var{arglist}s in their syntax allowfull Common Lisp argument lists.Note that it is @emph{not} necessary to use @code{defun*} inorder to have access to most @dfn{CL} features in your function.These features are always present; @code{defun*}'s onlydifference from @code{defun} is its more flexible argumentlists and its implicit block.The full form of a Common Lisp argument list is@example(@var{var}... &optional (@var{var} @var{initform} @var{svar})... &rest @var{var} &key ((@var{keyword} @var{var}) @var{initform} @var{svar})... &aux (@var{var} @var{initform})...)@end exampleEach of the five argument list sections is optional. The @var{svar},@var{initform}, and @var{keyword} parts are optional; if they areomitted, then @samp{(@var{var})} may be written simply @samp{@var{var}}.The first section consists of zero or more @dfn{required} arguments.These arguments must always be specified in a call to the function;there is no difference between Emacs Lisp and Common Lisp as far asrequired arguments are concerned.The second section consists of @dfn{optional} arguments. Thesearguments may be specified in the function call; if they are not,@var{initform} specifies the default value used for the argument.(No @var{initform} means to use @code{nil} as the default.) The@var{initform} is evaluated with the bindings for the precedingarguments already established; @code{(a &optional (b (1+ a)))}matches one or two arguments, with the second argument defaultingto one plus the first argument. If the @var{svar} is specified,it is an auxiliary variable which is bound to @code{t} if the optionalargument was specified, or to @code{nil} if the argument was omitted.If you don't use an @var{svar}, then there will be no way for yourfunction to tell whether it was called with no argument, or withthe default value passed explicitly as an argument.The third section consists of a single @dfn{rest} argument. Ifmore arguments were passed to the function than are accounted forby the required and optional arguments, those extra arguments arecollected into a list and bound to the ``rest'' argument variable.Common Lisp's @code{&rest} is equivalent to that of Emacs Lisp.Common Lisp accepts @code{&body} as a synonym for @code{&rest} inmacro contexts; this package accepts it all the time.The fourth section consists of @dfn{keyword} arguments. Theseare optional arguments which are specified by name rather thanpositionally in the argument list. For example,@example(defun* foo (a &optional b &key c d (e 17)))@end example@noindentdefines a function which may be called with one, two, or morearguments. The first two arguments are bound to @code{a} and@code{b} in the usual way. The remaining arguments must bepairs of the form @code{:c}, @code{:d}, or @code{:e} followedby the value to be bound to the corresponding argument variable.(Symbols whose names begin with a colon are called @dfn{keywords},and they are self-quoting in the same way as @code{nil} and@code{t}.)For example, the call @code{(foo 1 2 :d 3 :c 4)} sets the fivearguments to 1, 2, 4, 3, and 17, respectively. If the same keywordappears more than once in the function call, the first occurrencetakes precedence over the later ones. Note that it is not possibleto specify keyword arguments without specifying the optionalargument @code{b} as well, since @code{(foo 1 :c 2)} would bind@code{b} to the keyword @code{:c}, then signal an error because@code{2} is not a valid keyword.If a @var{keyword} symbol is explicitly specified in the argumentlist as shown in the above diagram, then that keyword will beused instead of just the variable name prefixed with a colon.You can specify a @var{keyword} symbol which does not begin witha colon at all, but such symbols will not be self-quoting; youwill have to quote them explicitly with an apostrophe in thefunction call.Ordinarily it is an error to pass an unrecognized keyword toa function, e.g., @code{(foo 1 2 :c 3 :goober 4)}. You can askLisp to ignore unrecognized keywords, either by adding themarker @code{&allow-other-keys} after the keyword sectionof the argument list, or by specifying an @code{:allow-other-keys}argument in the call whose value is non-@code{nil}. If thefunction uses both @code{&rest} and @code{&key} at the same time,the ``rest'' argument is bound to the keyword list as it appearsin the call. For example:@smallexample(defun* find-thing (thing &rest rest &key need &allow-other-keys) (or (apply 'member* thing thing-list :allow-other-keys t rest) (if need (error "Thing not found"))))@end smallexample@noindentThis function takes a @code{:need} keyword argument, but alsoaccepts other keyword arguments which are passed on to the@code{member*} function. @code{allow-other-keys} is used tokeep both @code{find-thing} and @code{member*} from complainingabout each others' keywords in the arguments.The fifth section of the argument list consists of @dfn{auxiliaryvariables}. These are not really arguments at all, but simplyvariables which are bound to @code{nil} or to the specified@var{initforms} during execution of the function. There is nodifference between the following two functions, except for amatter of stylistic taste:@example(defun* foo (a b &aux (c (+ a b)) d) @var{body})(defun* foo (a b) (let ((c (+ a b)) d) @var{body}))@end exampleArgument lists support @dfn{destructuring}. In Common Lisp,destructuring is only allowed with @code{defmacro}; this packageallows it with @code{defun*} and other argument lists as well.In destructuring, any argument variable (@var{var} in the abovediagram) can be replaced by a list of variables, or more generally,a recursive argument list. The corresponding argument value mustbe a list whose elements match this recursive argument list.For example:@example(defmacro* dolist ((var listform &optional resultform) &rest body) ...)@end exampleThis says that the first argument of @code{dolist} must be a listof two or three items; if there are other arguments as well as thislist, they are stored in @code{body}. All features allowed inregular argument lists are allowed in these recursive argument lists.In addition, the clause @samp{&whole @var{var}} is allowed at thefront of a recursive argument list. It binds @var{var} to thewhole list being matched; thus @code{(&whole all a b)} matchesa list of two things, with @code{a} bound to the first thing,@code{b} bound to the second thing, and @code{all} bound to thelist itself. (Common Lisp allows @code{&whole} in top-level@code{defmacro} argument lists as well, but Emacs Lisp does notsupport this usage.)One last feature of destructuring is that the argument list may bedotted, so that the argument list @code{(a b . c)} is functionallyequivalent to @code{(a b &rest c)}.If the optimization quality @code{safety} is set to 0(@pxref{Declarations}), error checking for wrong number ofarguments and invalid keyword arguments is disabled. By default,argument lists are rigorously checked.@node Time of Evaluation, , Argument Lists, Program Structure@section Time of Evaluation@noindentNormally, the byte-compiler does not actually execute the forms ina file it compiles. For example, if a file contains @code{(setq foo t)},the act of compiling it will not actually set @code{foo} to @code{t}.This is true even if the @code{setq} was a top-level form (i.e., notenclosed in a @code{defun} or other form). Sometimes, though, youwould like to have certain top-level forms evaluated at compile-time.For example, the compiler effectively evaluates @code{defmacro} formsat compile-time so that later parts of the file can refer to themacros that are defined.@defspec eval-when (situations...) forms...This form controls when the body @var{forms} are evaluated.The @var{situations} list may contain any set of the symbols@code{compile}, @code{load}, and @code{eval} (or their long-windedANSI equivalents, @code{:compile-toplevel}, @code{:load-toplevel},and @code{:execute}).The @code{eval-when} form is handled differently depending onwhether or not it is being compiled as a top-level form.Specifically, it gets special treatment if it is being compiledby a command such as @code{byte-compile-file} which compiles filesor buffers of code, and it appears either literally at thetop level of the file or inside a top-level @code{progn}.For compiled top-level @code{eval-when}s, the body @var{forms} areexecuted at compile-time if @code{compile} is in the @var{situations}list, and the @var{forms} are written out to the file (to be executedat load-time) if @code{load} is in the @var{situations} list.For non-compiled-top-level forms, only the @code{eval} situation isrelevant. (This includes forms executed by the interpreter, formscompiled with @code{byte-compile} rather than @code{byte-compile-file},and non-top-level forms.) The @code{eval-when} acts like a@code{progn} if @code{eval} is specified, and like @code{nil}(ignoring the body @var{forms}) if not.The rules become more subtle when @code{eval-when}s are nested;consult Steele (second edition) for the gruesome details (andsome gruesome examples).Some simple examples:@example;; Top-level forms in foo.el:(eval-when (compile) (setq foo1 'bar))(eval-when (load) (setq foo2 'bar))(eval-when (compile load) (setq foo3 'bar))(eval-when (eval) (setq foo4 'bar))(eval-when (eval compile) (setq foo5 'bar))(eval-when (eval load) (setq foo6 'bar))(eval-when (eval compile load) (setq foo7 'bar))@end exampleWhen @file{foo.el} is compiled, these variables will be set duringthe compilation itself:@examplefoo1 foo3 foo5 foo7 ; `compile'@end exampleWhen @file{foo.elc} is loaded, these variables will be set:@examplefoo2 foo3 foo6 foo7 ; `load'@end exampleAnd if @file{foo.el} is loaded uncompiled, these variables willbe set:@examplefoo4 foo5 foo6 foo7 ; `eval'@end exampleIf these seven @code{eval-when}s had been, say, inside a @code{defun},then the first three would have been equivalent to @code{nil} and thelast four would have been equivalent to the corresponding @code{setq}s.Note that @code{(eval-when (load eval) @dots{})} is equivalentto @code{(progn @dots{})} in all contexts. The compiler treatscertain top-level forms, like @code{defmacro} (sort-of) and@code{require}, as if they were wrapped in @code{(eval-when(compile load eval) @dots{})}.@end defspecEmacs includes two special forms related to @code{eval-when}.One of these, @code{eval-when-compile}, is not quite equivalent toany @code{eval-when} construct and is described below.The other form, @code{(eval-and-compile @dots{})}, is exactlyequivalent to @samp{(eval-when (compile load eval) @dots{})} andso is not itself defined by this package.@defspec eval-when-compile forms...The @var{forms} are evaluated at compile-time; at execution time,this form acts like a quoted constant of the resulting value. Usedat top-level, @code{eval-when-compile} is just like @samp{eval-when(compile eval)}. In other contexts, @code{eval-when-compile}allows code to be evaluated once at compile-time for efficiencyor other reasons.This form is similar to the @samp{#.} syntax of true Common Lisp.@end defspec@defspec load-time-value formThe @var{form} is evaluated at load-time; at execution time,this form acts like a quoted constant of the resulting value.Early Common Lisp had a @samp{#,} syntax that was similar tothis, but ANSI Common Lisp replaced it with @code{load-time-value}and gave it more well-defined semantics.In a compiled file, @code{load-time-value} arranges for @var{form}to be evaluated when the @file{.elc} file is loaded and then usedas if it were a quoted constant. In code compiled by@code{byte-compile} rather than @code{byte-compile-file}, theeffect is identical to @code{eval-when-compile}. In uncompiledcode, both @code{eval-when-compile} and @code{load-time-value}act exactly like @code{progn}.@example(defun report () (insert "This function was executed on: " (current-time-string) ", compiled on: " (eval-when-compile (current-time-string)) ;; or '#.(current-time-string) in real Common Lisp ", and loaded on: " (load-time-value (current-time-string))))@end example@noindentByte-compiled, the above defun will result in the following code(or its compiled equivalent, of course) in the @file{.elc} file:@example(setq --temp-- (current-time-string))(defun report () (insert "This function was executed on: " (current-time-string) ", compiled on: " '"Wed Jun 23 18:33:43 1993" ", and loaded on: " --temp--))@end example@end defspec@node Predicates, Control Structure, Program Structure, Top@chapter Predicates@noindentThis section describes functions for testing whether variousfacts are true or false.@menu* Type Predicates:: `typep', `deftype', and `coerce'* Equality Predicates:: `eql' and `equalp'@end menu@node Type Predicates, Equality Predicates, Predicates, Predicates@section Type Predicates@noindentThe @dfn{CL} package defines a version of the Common Lisp @code{typep}predicate.@defun typep object typeCheck if @var{object} is of type @var{type}, where @var{type} is a(quoted) type name of the sort used by Common Lisp. For example,@code{(typep foo 'integer)} is equivalent to @code{(integerp foo)}.@end defunThe @var{type} argument to the above function is either a symbolor a list beginning with a symbol.@itemize @bullet@itemIf the type name is a symbol, Emacs appends @samp{-p} to thesymbol name to form the name of a predicate function for testingthe type. (Built-in predicates whose names end in @samp{p} ratherthan @samp{-p} are used when appropriate.)@itemThe type symbol @code{t} stands for the union of all types.@code{(typep @var{object} t)} is always true. Likewise, thetype symbol @code{nil} stands for nothing at all, and@code{(typep @var{object} nil)} is always false.@itemThe type symbol @code{null} represents the symbol @code{nil}.Thus @code{(typep @var{object} 'null)} is equivalent to@code{(null @var{object})}.@itemThe type symbol @code{atom} represents all objects that are not conscells. Thus @code{(typep @var{object} 'atom)} is equivalent to@code{(atom @var{object})}.@itemThe type symbol @code{real} is a synonym for @code{number}, and@code{fixnum} is a synonym for @code{integer}.@itemThe type symbols @code{character} and @code{string-char} matchintegers in the range from 0 to 255.@itemThe type symbol @code{float} uses the @code{floatp-safe} predicatedefined by this package rather than @code{floatp}, so it will workcorrectly even in Emacs versions without floating-point support.@itemThe type list @code{(integer @var{low} @var{high})} represents allintegers between @var{low} and @var{high}, inclusive. Either boundmay be a list of a single integer to specify an exclusive limit,or a @code{*} to specify no limit. The type @code{(integer * *)}is thus equivalent to @code{integer}.@itemLikewise, lists beginning with @code{float}, @code{real}, or@code{number} represent numbers of that type falling in a particularrange.@itemLists beginning with @code{and}, @code{or}, and @code{not} formcombinations of types. For example, @code{(or integer (float 0 *))}represents all objects that are integers or non-negative floats.@itemLists beginning with @code{member} or @code{member*} representobjects @code{eql} to any of the following values. For example,@code{(member 1 2 3 4)} is equivalent to @code{(integer 1 4)},and @code{(member nil)} is equivalent to @code{null}.@itemLists of the form @code{(satisfies @var{predicate})} representall objects for which @var{predicate} returns true when calledwith that object as an argument.@end itemizeThe following function and macro (not technically predicates) arerelated to @code{typep}.@defun coerce object typeThis function attempts to convert @var{object} to the specified@var{type}. If @var{object} is already of that type as determined by@code{typep}, it is simply returned. Otherwise, certain types ofconversions will be made: If @var{type} is any sequence type(@code{string}, @code{list}, etc.) then @var{object} will beconverted to that type if possible. If @var{type} is@code{character}, then strings of length one and symbols withone-character names can be coerced. If @var{type} is @code{float},then integers can be coerced in versions of Emacs that supportfloats. In all other circumstances, @code{coerce} signals anerror.@end defun@defspec deftype name arglist forms...This macro defines a new type called @var{name}. It is similarto @code{defmacro} in many ways; when @var{name} is encounteredas a type name, the body @var{forms} are evaluated and shouldreturn a type specifier that is equivalent to the type. The@var{arglist} is a Common Lisp argument list of the sort acceptedby @code{defmacro*}. The type specifier @samp{(@var{name} @var{args}...)}is expanded by calling the expander with those arguments; the typesymbol @samp{@var{name}} is expanded by calling the expander withno arguments. The @var{arglist} is processed the same as for@code{defmacro*} except that optional arguments without explicitdefaults use @code{*} instead of @code{nil} as the ``default''default. Some examples:@example(deftype null () '(satisfies null)) ; predefined(deftype list () '(or null cons)) ; predefined(deftype unsigned-byte (&optional bits) (list 'integer 0 (if (eq bits '*) bits (1- (lsh 1 bits)))))(unsigned-byte 8) @equiv{} (integer 0 255)(unsigned-byte) @equiv{} (integer 0 *)unsigned-byte @equiv{} (integer 0 *)@end example@noindentThe last example shows how the Common Lisp @code{unsigned-byte}type specifier could be implemented if desired; this package doesnot implement @code{unsigned-byte} by default.@end defspecThe @code{typecase} and @code{check-type} macros also use typenames. @xref{Conditionals}. @xref{Assertions}. The @code{map},@code{concatenate}, and @code{merge} functions take type-namearguments to specify the type of sequence to return. @xref{Sequences}.@node Equality Predicates, , Type Predicates, Predicates@section Equality Predicates@noindentThis package defines two Common Lisp predicates, @code{eql} and@code{equalp}.@defun eql a bThis function is almost the same as @code{eq}, except that if @var{a}and @var{b} are numbers of the same type, it compares them for numericequality (as if by @code{equal} instead of @code{eq}). This makes adifference only for versions of Emacs that are compiled withfloating-point support. Emacs floats are allocatedobjects just like cons cells, which means that @code{(eq 3.0 3.0)}will not necessarily be true---if the two @code{3.0}s were allocatedseparately, the pointers will be different even though the numbers arethe same. But @code{(eql 3.0 3.0)} will always be true.The types of the arguments must match, so @code{(eql 3 3.0)} isstill false.Note that Emacs integers are ``direct'' rather than allocated, whichbasically means @code{(eq 3 3)} will always be true. Thus @code{eq}and @code{eql} behave differently only if floating-point numbers areinvolved, and are indistinguishable on Emacs versions that don'tsupport floats.There is a slight inconsistency with Common Lisp in the treatment ofpositive and negative zeros. Some machines, notably those with IEEEstandard arithmetic, represent @code{+0} and @code{-0} as distinctvalues. Normally this doesn't matter because the standard specifiesthat @code{(= 0.0 -0.0)} should always be true, and this is indeedwhat Emacs Lisp and Common Lisp do. But the Common Lisp standardstates that @code{(eql 0.0 -0.0)} and @code{(equal 0.0 -0.0)} shouldbe false on IEEE-like machines; Emacs Lisp does not do this, and infact the only known way to distinguish between the two zeros in EmacsLisp is to @code{format} them and check for a minus sign.@end defun@defun equalp a bThis function is a more flexible version of @code{equal}. Inparticular, it compares strings case-insensitively, and it comparesnumbers without regard to type (so that @code{(equalp 3 3.0)} istrue). Vectors and conses are compared recursively. All otherobjects are compared as if by @code{equal}.This function differs from Common Lisp @code{equalp} in severalrespects. First, Common Lisp's @code{equalp} also compares@emph{characters} case-insensitively, which would be impracticalin this package since Emacs does not distinguish between integersand characters. In keeping with the idea that strings are lessvector-like in Emacs Lisp, this package's @code{equalp} also willnot compare strings against vectors of integers.@end defunAlso note that the Common Lisp functions @code{member} and @code{assoc}use @code{eql} to compare elements, whereas Emacs Lisp follows theMacLisp tradition and uses @code{equal} for these two functions.In Emacs, use @code{member*} and @code{assoc*} to get functionswhich use @code{eql} for comparisons.@node Control Structure, Macros, Predicates, Top@chapter Control Structure@noindentThe features described in the following sections implementvarious advanced control structures, including the powerful@code{setf} facility and a number of looping and conditionalconstructs.@menu* Assignment:: The `psetq' form* Generalized Variables:: `setf', `incf', `push', etc.* Variable Bindings:: `progv', `lexical-let', `flet', `macrolet'* Conditionals:: `case', `typecase'* Blocks and Exits:: `block', `return', `return-from'* Iteration:: `do', `dotimes', `dolist', `do-symbols'* Loop Facility:: The Common Lisp `loop' macro* Multiple Values:: `values', `multiple-value-bind', etc.@end menu@node Assignment, Generalized Variables, Control Structure, Control Structure@section Assignment@noindentThe @code{psetq} form is just like @code{setq}, except that multipleassignments are done in parallel rather than sequentially.@defspec psetq [symbol form]@dots{}This special form (actually a macro) is used to assign to severalvariables simultaneously. Given only one @var{symbol} and @var{form},it has the same effect as @code{setq}. Given several @var{symbol}and @var{form} pairs, it evaluates all the @var{form}s in advanceand then stores the corresponding variables afterwards.@example(setq x 2 y 3)(setq x (+ x y) y (* x y))x @result{} 5y ; @r{@code{y} was computed after @code{x} was set.} @result{} 15(setq x 2 y 3)(psetq x (+ x y) y (* x y))x @result{} 5y ; @r{@code{y} was computed before @code{x} was set.} @result{} 6@end exampleThe simplest use of @code{psetq} is @code{(psetq x y y x)}, whichexchanges the values of two variables. (The @code{rotatef} formprovides an even more convenient way to swap two variables;@pxref{Modify Macros}.)@code{psetq} always returns @code{nil}.@end defspec@node Generalized Variables, Variable Bindings, Assignment, Control Structure@section Generalized Variables@noindentA ``generalized variable'' or ``place form'' is one of the many placesin Lisp memory where values can be stored. The simplest place form isa regular Lisp variable. But the cars and cdrs of lists, elementsof arrays, properties of symbols, and many other locations are alsoplaces where Lisp values are stored.The @code{setf} form is like @code{setq}, except that it acceptsarbitrary place forms on the left side rather than justsymbols. For example, @code{(setf (car a) b)} sets the car of@code{a} to @code{b}, doing the same operation as @code{(setcar a b)}but without having to remember two separate functions for settingand accessing every type of place.Generalized variables are analogous to ``lvalues'' in the Clanguage, where @samp{x = a[i]} gets an element from an arrayand @samp{a[i] = x} stores an element using the same notation.Just as certain forms like @code{a[i]} can be lvalues in C, thereis a set of forms that can be generalized variables in Lisp.@menu* Basic Setf:: `setf' and place forms* Modify Macros:: `incf', `push', `rotatef', `letf', `callf', etc.* Customizing Setf:: `define-modify-macro', `defsetf', `define-setf-method'@end menu@node Basic Setf, Modify Macros, Generalized Variables, Generalized Variables@subsection Basic Setf@noindentThe @code{setf} macro is the most basic way to operate on generalizedvariables.@defspec setf [place form]@dots{}This macro evaluates @var{form} and stores it in @var{place}, whichmust be a valid generalized variable form. If there are several@var{place} and @var{form} pairs, the assignments are done sequentiallyjust as with @code{setq}. @code{setf} returns the value of the last@var{form}.The following Lisp forms will work as generalized variables, andso may appear in the @var{place} argument of @code{setf}:@itemize @bullet@itemA symbol naming a variable. In other words, @code{(setf x y)} isexactly equivalent to @code{(setq x y)}, and @code{setq} itself isstrictly speaking redundant now that @code{setf} exists. Manyprogrammers continue to prefer @code{setq} for setting simplevariables, though, purely for stylistic or historical reasons.The macro @code{(setf x y)} actually expands to @code{(setq x y)},so there is no performance penalty for using it in compiled code.@itemA call to any of the following Lisp functions:@smallexamplecar cdr caar .. cddddrnth rest first .. tentharef elt nthcdrsymbol-function symbol-value symbol-plistget get* getfgethash subseq@end smallexample@noindentNote that for @code{nthcdr} and @code{getf}, the list argumentof the function must itself be a valid @var{place} form. Forexample, @code{(setf (nthcdr 0 foo) 7)} will set @code{foo} itselfto 7. Note that @code{push} and @code{pop} on an @code{nthcdr}place can be used to insert or delete at any position in a list.The use of @code{nthcdr} as a @var{place} form is an extensionto standard Common Lisp.@itemThe following Emacs-specific functions are also @code{setf}-able.@smallexamplebuffer-file-name marker-positionbuffer-modified-p match-databuffer-name mouse-positionbuffer-string overlay-endbuffer-substring overlay-getcurrent-buffer overlay-startcurrent-case-table pointcurrent-column point-markercurrent-global-map point-maxcurrent-input-mode point-mincurrent-local-map process-buffercurrent-window-configuration process-filterdefault-file-modes process-sentineldefault-value read-mouse-positiondocumentation-property screen-heightextent-data screen-menubarextent-end-position screen-widthextent-start-position selected-windowface-background selected-screenface-background-pixmap selected-frameface-font standard-case-tableface-foreground syntax-tableface-underline-p window-bufferfile-modes window-dedicated-pframe-height window-display-tableframe-parameters window-heightframe-visible-p window-hscrollframe-width window-pointget-register window-startgetenv window-widthglobal-key-binding x-get-cut-bufferkeymap-parent x-get-cutbufferlocal-key-binding x-get-secondary-selectionmark x-get-selectionmark-marker@end smallexampleMost of these have directly corresponding ``set'' functions, like@code{use-local-map} for @code{current-local-map}, or @code{goto-char}for @code{point}. A few, like @code{point-min}, expand to longersequences of code when they are @code{setf}'d (@code{(narrow-to-regionx (point-max))} in this case).@itemA call of the form @code{(substring @var{subplace} @var{n} [@var{m}])},where @var{subplace} is itself a valid generalized variable whosecurrent value is a string, and where the value stored is also astring. The new string is spliced into the specified part of thedestination string. For example:@example(setq a (list "hello" "world")) @result{} ("hello" "world")(cadr a) @result{} "world"(substring (cadr a) 2 4) @result{} "rl"(setf (substring (cadr a) 2 4) "o") @result{} "o"(cadr a) @result{} "wood"a @result{} ("hello" "wood")@end exampleThe generalized variable @code{buffer-substring}, listed above,also works in this way by replacing a portion of the current buffer.@itemA call of the form @code{(apply '@var{func} @dots{})} or@code{(apply (function @var{func}) @dots{})}, where @var{func}is a @code{setf}-able function whose store function is ``suitable''in the sense described in Steele's book; since none of the standardEmacs place functions are suitable in this sense, this feature isonly interesting when used with places you define yourself with@code{define-setf-method} or the long form of @code{defsetf}.@itemA macro call, in which case the macro is expanded and @code{setf}is applied to the resulting form.@itemAny form for which a @code{defsetf} or @code{define-setf-method}has been made.@end itemizeUsing any forms other than these in the @var{place} argument to@code{setf} will signal an error.The @code{setf} macro takes care to evaluate all subforms inthe proper left-to-right order; for example,@example(setf (aref vec (incf i)) i)@end example@noindentlooks like it will evaluate @code{(incf i)} exactly once, before thefollowing access to @code{i}; the @code{setf} expander will inserttemporary variables as necessary to ensure that it does in fact workthis way no matter what setf-method is defined for @code{aref}.(In this case, @code{aset} would be used and no such steps wouldbe necessary since @code{aset} takes its arguments in a convenientorder.)However, if the @var{place} form is a macro which explicitlyevaluates its arguments in an unusual order, this unusual orderwill be preserved. Adapting an example from Steele, given@example(defmacro wrong-order (x y) (list 'aref y x))@end example@noindentthe form @code{(setf (wrong-order @var{a} @var{b}) 17)} willevaluate @var{b} first, then @var{a}, just as in an actual callto @code{wrong-order}.@end defspec@node Modify Macros, Customizing Setf, Basic Setf, Generalized Variables@subsection Modify Macros@noindentThis package defines a number of other macros besides @code{setf}that operate on generalized variables. Many are interesting anduseful even when the @var{place} is just a variable name.@defspec psetf [place form]@dots{}This macro is to @code{setf} what @code{psetq} is to @code{setq}:When several @var{place}s and @var{form}s are involved, theassignments take place in parallel rather than sequentially.Specifically, all subforms are evaluated from left to right, thenall the assignments are done (in an undefined order).@end defspec@defspec incf place &optional xThis macro increments the number stored in @var{place} by one, orby @var{x} if specified. The incremented value is returned. Forexample, @code{(incf i)} is equivalent to @code{(setq i (1+ i))}, and@code{(incf (car x) 2)} is equivalent to @code{(setcar x (+ (car x) 2))}.Once again, care is taken to preserve the ``apparent'' order ofevaluation. For example,@example(incf (aref vec (incf i)))@end example@noindentappears to increment @code{i} once, then increment the element of@code{vec} addressed by @code{i}; this is indeed exactly what itdoes, which means the above form is @emph{not} equivalent to the``obvious'' expansion,@example(setf (aref vec (incf i)) (1+ (aref vec (incf i)))) ; Wrong!@end example@noindentbut rather to something more like@example(let ((temp (incf i))) (setf (aref vec temp) (1+ (aref vec temp))))@end example@noindentAgain, all of this is taken care of automatically by @code{incf} andthe other generalized-variable macros.As a more Emacs-specific example of @code{incf}, the expression@code{(incf (point) @var{n})} is essentially equivalent to@code{(forward-char @var{n})}.@end defspec@defspec decf place &optional xThis macro decrements the number stored in @var{place} by one, orby @var{x} if specified.@end defspec@defspec pop placeThis macro removes and returns the first element of the list storedin @var{place}. It is analogous to @code{(prog1 (car @var{place})(setf @var{place} (cdr @var{place})))}, except that it takes careto evaluate all subforms only once.@end defspec@defspec push x placeThis macro inserts @var{x} at the front of the list stored in@var{place}. It is analogous to @code{(setf @var{place} (cons@var{x} @var{place}))}, except for evaluation of the subforms.@end defspec@defspec pushnew x place @t{&key :test :test-not :key}This macro inserts @var{x} at the front of the list stored in@var{place}, but only if @var{x} was not @code{eql} to anyexisting element of the list. The optional keyword argumentsare interpreted in the same way as for @code{adjoin}.@xref{Lists as Sets}.@end defspec@defspec shiftf place@dots{} newvalueThis macro shifts the @var{place}s left by one, shifting in thevalue of @var{newvalue} (which may be any Lisp expression, not justa generalized variable), and returning the value shifted out ofthe first @var{place}. Thus, @code{(shiftf @var{a} @var{b} @var{c}@var{d})} is equivalent to@example(prog1 @var{a} (psetf @var{a} @var{b} @var{b} @var{c} @var{c} @var{d}))@end example@noindentexcept that the subforms of @var{a}, @var{b}, and @var{c} are actuallyevaluated only once each and in the apparent order.@end defspec@defspec rotatef place@dots{}This macro rotates the @var{place}s left by one in circular fashion.Thus, @code{(rotatef @var{a} @var{b} @var{c} @var{d})} is equivalent to@example(psetf @var{a} @var{b} @var{b} @var{c} @var{c} @var{d} @var{d} @var{a})@end example@noindentexcept for the evaluation of subforms. @code{rotatef} alwaysreturns @code{nil}. Note that @code{(rotatef @var{a} @var{b})}conveniently exchanges @var{a} and @var{b}.@end defspecThe following macros were invented for this package; they have noanalogues in Common Lisp.@defspec letf (bindings@dots{}) forms@dots{}This macro is analogous to @code{let}, but for generalized variablesrather than just symbols. Each @var{binding} should be of the form@code{(@var{place} @var{value})}; the original contents of the@var{place}s are saved, the @var{value}s are stored in them, andthen the body @var{form}s are executed. Afterwards, the @var{places}are set back to their original saved contents. This cleanup happenseven if the @var{form}s exit irregularly due to a @code{throw} or anerror.For example,@example(letf (((point) (point-min)) (a 17)) ...)@end example@noindentmoves ``point'' in the current buffer to the beginning of the buffer,and also binds @code{a} to 17 (as if by a normal @code{let}, since@code{a} is just a regular variable). After the body exits, @code{a}is set back to its original value and point is moved back to itsoriginal position.Note that @code{letf} on @code{(point)} is not quite like a@code{save-excursion}, as the latter effectively saves a markerwhich tracks insertions and deletions in the buffer. Actually,a @code{letf} of @code{(point-marker)} is much closer to thisbehavior. (@code{point} and @code{point-marker} are equivalentas @code{setf} places; each will accept either an integer or amarker as the stored value.)Since generalized variables look like lists, @code{let}'s shorthandof using @samp{foo} for @samp{(foo nil)} as a @var{binding} wouldbe ambiguous in @code{letf} and is not allowed.However, a @var{binding} specifier may be a one-element list@samp{(@var{place})}, which is similar to @samp{(@var{place}@var{place})}. In other words, the @var{place} is not disturbedon entry to the body, and the only effect of the @code{letf} isto restore the original value of @var{place} afterwards. (Theredundant access-and-store suggested by the @code{(@var{place}@var{place})} example does not actually occur.)In most cases, the @var{place} must have a well-defined value onentry to the @code{letf} form. The only exceptions are plainvariables and calls to @code{symbol-value} and @code{symbol-function}.If the symbol is not bound on entry, it is simply made unbound by@code{makunbound} or @code{fmakunbound} on exit.@end defspec@defspec letf* (bindings@dots{}) forms@dots{}This macro is to @code{letf} what @code{let*} is to @code{let}:It does the bindings in sequential rather than parallel order.@end defspec@defspec callf @var{function} @var{place} @var{args}@dots{}This is the ``generic'' modify macro. It calls @var{function},which should be an unquoted function name, macro name, or lambda.It passes @var{place} and @var{args} as arguments, and assigns theresult back to @var{place}. For example, @code{(incf @var{place}@var{n})} is the same as @code{(callf + @var{place} @var{n})}.Some more examples:@example(callf abs my-number)(callf concat (buffer-name) "<" (int-to-string n) ">")(callf union happy-people (list joe bob) :test 'same-person)@end example@xref{Customizing Setf}, for @code{define-modify-macro}, a wayto create even more concise notations for modify macros. Noteagain that @code{callf} is an extension to standard Common Lisp.@end defspec@defspec callf2 @var{function} @var{arg1} @var{place} @var{args}@dots{}This macro is like @code{callf}, except that @var{place} isthe @emph{second} argument of @var{function} rather than thefirst. For example, @code{(push @var{x} @var{place})} isequivalent to @code{(callf2 cons @var{x} @var{place})}.@end defspecThe @code{callf} and @code{callf2} macros serve as buildingblocks for other macros like @code{incf}, @code{pushnew}, and@code{define-modify-macro}. The @code{letf} and @code{letf*}macros are used in the processing of symbol macros;@pxref{Macro Bindings}.@node Customizing Setf, , Modify Macros, Generalized Variables@subsection Customizing Setf@noindentCommon Lisp defines three macros, @code{define-modify-macro},@code{defsetf}, and @code{define-setf-method}, that allow theuser to extend generalized variables in various ways.@defspec define-modify-macro name arglist function [doc-string]This macro defines a ``read-modify-write'' macro similar to@code{incf} and @code{decf}. The macro @var{name} is definedto take a @var{place} argument followed by additional argumentsdescribed by @var{arglist}. The call@example(@var{name} @var{place} @var{args}...)@end example@noindentwill be expanded to@example(callf @var{func} @var{place} @var{args}...)@end example@noindentwhich in turn is roughly equivalent to@example(setf @var{place} (@var{func} @var{place} @var{args}...))@end exampleFor example:@example(define-modify-macro incf (&optional (n 1)) +)(define-modify-macro concatf (&rest args) concat)@end exampleNote that @code{&key} is not allowed in @var{arglist}, but@code{&rest} is sufficient to pass keywords on to the function.Most of the modify macros defined by Common Lisp do not exactlyfollow the pattern of @code{define-modify-macro}. For example,@code{push} takes its arguments in the wrong order, and @code{pop}is completely irregular. You can define these macros ``by hand''using @code{get-setf-method}, or consult the source file@file{cl-macs.el} to see how to use the internal @code{setf}building blocks.@end defspec@defspec defsetf access-fn update-fnThis is the simpler of two @code{defsetf} forms. Where@var{access-fn} is the name of a function which accesses a place,this declares @var{update-fn} to be the corresponding storefunction. From now on,@example(setf (@var{access-fn} @var{arg1} @var{arg2} @var{arg3}) @var{value})@end example@noindentwill be expanded to@example(@var{update-fn} @var{arg1} @var{arg2} @var{arg3} @var{value})@end example@noindentThe @var{update-fn} is required to be either a true function, ora macro which evaluates its arguments in a function-like way. Also,the @var{update-fn} is expected to return @var{value} as its result.Otherwise, the above expansion would not obey the rules for the way@code{setf} is supposed to behave.As a special (non-Common-Lisp) extension, a third argument of @code{t}to @code{defsetf} says that the @code{update-fn}'s return value isnot suitable, so that the above @code{setf} should be expanded tosomething more like@example(let ((temp @var{value})) (@var{update-fn} @var{arg1} @var{arg2} @var{arg3} temp) temp)@end exampleSome examples of the use of @code{defsetf}, drawn from the standardsuite of setf methods, are:@example(defsetf car setcar)(defsetf symbol-value set)(defsetf buffer-name rename-buffer t)@end example@end defspec@defspec defsetf access-fn arglist (store-var) forms@dots{}This is the second, more complex, form of @code{defsetf}. It israther like @code{defmacro} except for the additional @var{store-var}argument. The @var{forms} should return a Lisp form which storesthe value of @var{store-var} into the generalized variable formedby a call to @var{access-fn} with arguments described by @var{arglist}.The @var{forms} may begin with a string which documents the @code{setf}method (analogous to the doc string that appears at the front of afunction).For example, the simple form of @code{defsetf} is shorthand for@example(defsetf @var{access-fn} (&rest args) (store) (append '(@var{update-fn}) args (list store)))@end exampleThe Lisp form that is returned can access the arguments from@var{arglist} and @var{store-var} in an unrestricted fashion;macros like @code{setf} and @code{incf} which invoke thissetf-method will insert temporary variables as needed to makesure the apparent order of evaluation is preserved.Another example drawn from the standard package:@example(defsetf nth (n x) (store) (list 'setcar (list 'nthcdr n x) store))@end example@end defspec@defspec define-setf-method access-fn arglist forms@dots{}This is the most general way to create new place forms. Whena @code{setf} to @var{access-fn} with arguments described by@var{arglist} is expanded, the @var{forms} are evaluated andmust return a list of five items:@enumerate@itemA list of @dfn{temporary variables}.@itemA list of @dfn{value forms} corresponding to the temporary variablesabove. The temporary variables will be bound to these value formsas the first step of any operation on the generalized variable.@itemA list of exactly one @dfn{store variable} (generally obtainedfrom a call to @code{gensym}).@itemA Lisp form which stores the contents of the store variable intothe generalized variable, assuming the temporaries have beenbound as described above.@itemA Lisp form which accesses the contents of the generalized variable,assuming the temporaries have been bound.@end enumerateThis is exactly like the Common Lisp macro of the same name,except that the method returns a list of five values ratherthan the five values themselves, since Emacs Lisp does notsupport Common Lisp's notion of multiple return values.Once again, the @var{forms} may begin with a documentation string.A setf-method should be maximally conservative with regard totemporary variables. In the setf-methods generated by@code{defsetf}, the second return value is simply the list ofarguments in the place form, and the first return value is alist of a corresponding number of temporary variables generatedby @code{gensym}. Macros like @code{setf} and @code{incf} whichuse this setf-method will optimize away most temporaries thatturn out to be unnecessary, so there is little reason for thesetf-method itself to optimize.@end defspec@defun get-setf-method place &optional envThis function returns the setf-method for @var{place}, byinvoking the definition previously recorded by @code{defsetf}or @code{define-setf-method}. The result is a list of fivevalues as described above. You can use this function to buildyour own @code{incf}-like modify macros. (Actually, it isbetter to use the internal functions @code{cl-setf-do-modify}and @code{cl-setf-do-store}, which are a bit easier to use andwhich also do a number of optimizations; consult the sourcecode for the @code{incf} function for a simple example.)The argument @var{env} specifies the ``environment'' to bepassed on to @code{macroexpand} if @code{get-setf-method} shouldneed to expand a macro in @var{place}. It should come froman @code{&environment} argument to the macro or setf-methodthat called @code{get-setf-method}.See also the source code for the setf-methods for @code{apply}and @code{substring}, each of which works by calling@code{get-setf-method} on a simpler case, then massagingthe result in various ways.@end defunModern Common Lisp defines a second, independent way to specifythe @code{setf} behavior of a function, namely ``@code{setf}functions'' whose names are lists @code{(setf @var{name})}rather than symbols. For example, @code{(defun (setf foo) @dots{})}defines the function that is used when @code{setf} is applied to@code{foo}. This package does not currently support @code{setf}functions. In particular, it is a compile-time error to use@code{setf} on a form which has not already been @code{defsetf}'dor otherwise declared; in newer Common Lisps, this would not bean error since the function @code{(setf @var{func})} might bedefined later.@iftex@secno=4@end iftex@node Variable Bindings, Conditionals, Generalized Variables, Control Structure@section Variable Bindings@noindentThese Lisp forms make bindings to variables and function names,analogous to Lisp's built-in @code{let} form.@xref{Modify Macros}, for the @code{letf} and @code{letf*} forms whichare also related to variable bindings.@menu* Dynamic Bindings:: The `progv' form* Lexical Bindings:: `lexical-let' and lexical closures* Function Bindings:: `flet' and `labels'* Macro Bindings:: `macrolet' and `symbol-macrolet'@end menu@node Dynamic Bindings, Lexical Bindings, Variable Bindings, Variable Bindings@subsection Dynamic Bindings@noindentThe standard @code{let} form binds variables whose names are knownat compile-time. The @code{progv} form provides an easy way tobind variables whose names are computed at run-time.@defspec progv symbols values forms@dots{}This form establishes @code{let}-style variable bindings on aset of variables computed at run-time. The expressions@var{symbols} and @var{values} are evaluated, and must return listsof symbols and values, respectively. The symbols are bound to thecorresponding values for the duration of the body @var{form}s.If @var{values} is shorter than @var{symbols}, the last few symbolsare made unbound (as if by @code{makunbound}) inside the body.If @var{symbols} is shorter than @var{values}, the excess valuesare ignored.@end defspec@node Lexical Bindings, Function Bindings, Dynamic Bindings, Variable Bindings@subsection Lexical Bindings@noindentThe @dfn{CL} package defines the following macro whichmore closely follows the Common Lisp @code{let} form:@defspec lexical-let (bindings@dots{}) forms@dots{}This form is exactly like @code{let} except that the bindings itestablishes are purely lexical. Lexical bindings are similar tolocal variables in a language like C: Only the code physicallywithin the body of the @code{lexical-let} (after macro expansion)may refer to the bound variables.@example(setq a 5)(defun foo (b) (+ a b))(let ((a 2)) (foo a)) @result{} 4(lexical-let ((a 2)) (foo a)) @result{} 7@end example@noindentIn this example, a regular @code{let} binding of @code{a} actuallymakes a temporary change to the global variable @code{a}, so @code{foo}is able to see the binding of @code{a} to 2. But @code{lexical-let}actually creates a distinct local variable @code{a} for use within itsbody, without any effect on the global variable of the same name.The most important use of lexical bindings is to create @dfn{closures}.A closure is a function object that refers to an outside lexicalvariable. For example:@example(defun make-adder (n) (lexical-let ((n n)) (function (lambda (m) (+ n m)))))(setq add17 (make-adder 17))(funcall add17 4) @result{} 21@end example@noindentThe call @code{(make-adder 17)} returns a function object which adds17 to its argument. If @code{let} had been used instead of@code{lexical-let}, the function object would have referred to theglobal @code{n}, which would have been bound to 17 only during thecall to @code{make-adder} itself.@example(defun make-counter () (lexical-let ((n 0)) (function* (lambda (&optional (m 1)) (incf n m)))))(setq count-1 (make-counter))(funcall count-1 3) @result{} 3(funcall count-1 14) @result{} 17(setq count-2 (make-counter))(funcall count-2 5) @result{} 5(funcall count-1 2) @result{} 19(funcall count-2) @result{} 6@end example@noindentHere we see that each call to @code{make-counter} creates a distinctlocal variable @code{n}, which serves as a private counter for thefunction object that is returned.Closed-over lexical variables persist until the last reference tothem goes away, just like all other Lisp objects. For example,@code{count-2} refers to a function object which refers to aninstance of the variable @code{n}; this is the only referenceto that variable, so after @code{(setq count-2 nil)} the garbagecollector would be able to delete this instance of @code{n}.Of course, if a @code{lexical-let} does not actually create anyclosures, then the lexical variables are free as soon as the@code{lexical-let} returns.Many closures are used only during the extent of the bindings theyrefer to; these are known as ``downward funargs'' in Lisp parlance.When a closure is used in this way, regular Emacs Lisp dynamicbindings suffice and will be more efficient than @code{lexical-let}closures:@example(defun add-to-list (x list) (mapcar (lambda (y) (+ x y))) list)(add-to-list 7 '(1 2 5)) @result{} (8 9 12)@end example@noindentSince this lambda is only used while @code{x} is still bound,it is not necessary to make a true closure out of it.You can use @code{defun} or @code{flet} inside a @code{lexical-let}to create a named closure. If several closures are created in thebody of a single @code{lexical-let}, they all close over the sameinstance of the lexical variable.The @code{lexical-let} form is an extension to Common Lisp. Intrue Common Lisp, all bindings are lexical unless declared otherwise.@end defspec@defspec lexical-let* (bindings@dots{}) forms@dots{}This form is just like @code{lexical-let}, except that the bindingsare made sequentially in the manner of @code{let*}.@end defspec@node Function Bindings, Macro Bindings, Lexical Bindings, Variable Bindings@subsection Function Bindings@noindentThese forms make @code{let}-like bindings to functions insteadof variables.@defspec flet (bindings@dots{}) forms@dots{}This form establishes @code{let}-style bindings on the functioncells of symbols rather than on the value cells. Each @var{binding}must be a list of the form @samp{(@var{name} @var{arglist}@var{forms}@dots{})}, which defines a function exactly as ifit were a @code{defun*} form. The function @var{name} is definedaccordingly for the duration of the body of the @code{flet}; thenthe old function definition, or lack thereof, is restored.While @code{flet} in Common Lisp establishes a lexical binding of@var{name}, Emacs Lisp @code{flet} makes a dynamic binding. Theresult is that @code{flet} affects indirect calls to a function aswell as calls directly inside the @code{flet} form itself.You can use @code{flet} to disable or modify the behavior of afunction in a temporary fashion. This will even work on Emacsprimitives, although note that some calls to primitive functionsinternal to Emacs are made without going through the symbol'sfunction cell, and so will not be affected by @code{flet}. Forexample,@example(flet ((message (&rest args) (push args saved-msgs))) (do-something))@end exampleThis code attempts to replace the built-in function @code{message}with a function that simply saves the messages in a list ratherthan displaying them. The original definition of @code{message}will be restored after @code{do-something} exits. This code willwork fine on messages generated by other Lisp code, but messagesgenerated directly inside Emacs will not be caught since they makedirect C-language calls to the message routines rather than goingthrough the Lisp @code{message} function.Functions defined by @code{flet} may use the full Common Lispargument notation supported by @code{defun*}; also, the functionbody is enclosed in an implicit block as if by @code{defun*}.@xref{Program Structure}.@end defspec@defspec labels (bindings@dots{}) forms@dots{}The @code{labels} form is like @code{flet}, except that itmakes lexical bindings of the function names rather thandynamic bindings. (In true Common Lisp, both @code{flet} and@code{labels} make lexical bindings of slightly different sorts;since Emacs Lisp is dynamically bound by default, it seemedmore appropriate for @code{flet} also to use dynamic binding.The @code{labels} form, with its lexical binding, is fullycompatible with Common Lisp.)Lexical scoping means that all references to the namedfunctions must appear physically within the body of the@code{labels} form. References may appear both in the body@var{forms} of @code{labels} itself, and in the bodies ofthe functions themselves. Thus, @code{labels} can definelocal recursive functions, or mutually-recursive sets offunctions.A ``reference'' to a function name is either a call to thatfunction, or a use of its name quoted by @code{quote} or@code{function} to be passed on to, say, @code{mapcar}.@end defspec@node Macro Bindings, , Function Bindings, Variable Bindings@subsection Macro Bindings@noindentThese forms create local macros and ``symbol macros.''@defspec macrolet (bindings@dots{}) forms@dots{}This form is analogous to @code{flet}, but for macros instead offunctions. Each @var{binding} is a list of the same form as thearguments to @code{defmacro*} (i.e., a macro name, argument list,and macro-expander forms). The macro is defined accordingly foruse within the body of the @code{macrolet}.Because of the nature of macros, @code{macrolet} is lexicallyscoped even in Emacs Lisp: The @code{macrolet} binding willaffect only calls that appear physically within the body@var{forms}, possibly after expansion of other macros in thebody.@end defspec@defspec symbol-macrolet (bindings@dots{}) forms@dots{}This form creates @dfn{symbol macros}, which are macros that looklike variable references rather than function calls. Each@var{binding} is a list @samp{(@var{var} @var{expansion})};any reference to @var{var} within the body @var{forms} isreplaced by @var{expansion}.@example(setq bar '(5 . 9))(symbol-macrolet ((foo (car bar))) (incf foo))bar @result{} (6 . 9)@end exampleA @code{setq} of a symbol macro is treated the same as a @code{setf}.I.e., @code{(setq foo 4)} in the above would be equivalent to@code{(setf foo 4)}, which in turn expands to @code{(setf (car bar) 4)}.Likewise, a @code{let} or @code{let*} binding a symbol macro istreated like a @code{letf} or @code{letf*}. This differs from trueCommon Lisp, where the rules of lexical scoping cause a @code{let}binding to shadow a @code{symbol-macrolet} binding. In this package,only @code{lexical-let} and @code{lexical-let*} will shadow a symbolmacro.There is no analogue of @code{defmacro} for symbol macros; all symbolmacros are local. A typical use of @code{symbol-macrolet} is in theexpansion of another macro:@example(defmacro* my-dolist ((x list) &rest body) (let ((var (gensym))) (list 'loop 'for var 'on list 'do (list* 'symbol-macrolet (list (list x (list 'car var))) body))))(setq mylist '(1 2 3 4))(my-dolist (x mylist) (incf x))mylist @result{} (2 3 4 5)@end example@noindentIn this example, the @code{my-dolist} macro is similar to @code{dolist}(@pxref{Iteration}) except that the variable @code{x} becomes a truereference onto the elements of the list. The @code{my-dolist} callshown here expands to@example(loop for G1234 on mylist do (symbol-macrolet ((x (car G1234))) (incf x)))@end example@noindentwhich in turn expands to@example(loop for G1234 on mylist do (incf (car G1234)))@end example@xref{Loop Facility}, for a description of the @code{loop} macro.This package defines a nonstandard @code{in-ref} loop clause thatworks much like @code{my-dolist}.@end defspec@node Conditionals, Blocks and Exits, Variable Bindings, Control Structure@section Conditionals@noindentThese conditional forms augment Emacs Lisp's simple @code{if},@code{and}, @code{or}, and @code{cond} forms.@defspec case keyform clause@dots{}This macro evaluates @var{keyform}, then compares it with the keyvalues listed in the various @var{clause}s. Whichever clause matchesthe key is executed; comparison is done by @code{eql}. If no clausematches, the @code{case} form returns @code{nil}. The clauses areof the form@example(@var{keylist} @var{body-forms}@dots{})@end example@noindentwhere @var{keylist} is a list of key values. If there is exactlyone value, and it is not a cons cell or the symbol @code{nil} or@code{t}, then it can be used by itself as a @var{keylist} withoutbeing enclosed in a list. All key values in the @code{case} formmust be distinct. The final clauses may use @code{t} in place ofa @var{keylist} to indicate a default clause that should be takenif none of the other clauses match. (The symbol @code{otherwise}is also recognized in place of @code{t}. To make a clause thatmatches the actual symbol @code{t}, @code{nil}, or @code{otherwise},enclose the symbol in a list.)For example, this expression reads a keystroke, then does one offour things depending on whether it is an @samp{a}, a @samp{b},a @key{RET} or @kbd{C-j}, or anything else.@example(case (read-char) (?a (do-a-thing)) (?b (do-b-thing)) ((?\r ?\n) (do-ret-thing)) (t (do-other-thing)))@end example@end defspec@defspec ecase keyform clause@dots{}This macro is just like @code{case}, except that if the key doesnot match any of the clauses, an error is signaled rather thansimply returning @code{nil}.@end defspec@defspec typecase keyform clause@dots{}This macro is a version of @code{case} that checks for typesrather than values. Each @var{clause} is of the form@samp{(@var{type} @var{body}...)}. @xref{Type Predicates},for a description of type specifiers. For example,@example(typecase x (integer (munch-integer x)) (float (munch-float x)) (string (munch-integer (string-to-int x))) (t (munch-anything x)))@end exampleThe type specifier @code{t} matches any type of object; the word@code{otherwise} is also allowed. To make one clause match any ofseveral types, use an @code{(or ...)} type specifier.@end defspec@defspec etypecase keyform clause@dots{}This macro is just like @code{typecase}, except that if the key doesnot match any of the clauses, an error is signaled rather thansimply returning @code{nil}.@end defspec@node Blocks and Exits, Iteration, Conditionals, Control Structure@section Blocks and Exits@noindentCommon Lisp @dfn{blocks} provide a non-local exit mechanism verysimilar to @code{catch} and @code{throw}, but lexically rather thandynamically scoped. This package actually implements @code{block}in terms of @code{catch}; however, the lexical scoping allows theoptimizing byte-compiler to omit the costly @code{catch} step if thebody of the block does not actually @code{return-from} the block.@defspec block name forms@dots{}The @var{forms} are evaluated as if by a @code{progn}. However,if any of the @var{forms} execute @code{(return-from @var{name})},they will jump out and return directly from the @code{block} form.The @code{block} returns the result of the last @var{form} unlessa @code{return-from} occurs.The @code{block}/@code{return-from} mechanism is quite similar tothe @code{catch}/@code{throw} mechanism. The main differences arethat block @var{name}s are unevaluated symbols, rather than forms(such as quoted symbols) which evaluate to a tag at run-time; andalso that blocks are lexically scoped whereas @code{catch}/@code{throw}are dynamically scoped. This means that functions called from thebody of a @code{catch} can also @code{throw} to the @code{catch},but the @code{return-from} referring to a block name must appearphysically within the @var{forms} that make up the body of the block.They may not appear within other called functions, although they mayappear within macro expansions or @code{lambda}s in the body. Blocknames and @code{catch} names form independent name-spaces.In true Common Lisp, @code{defun} and @code{defmacro} surroundthe function or expander bodies with implicit blocks with thesame name as the function or macro. This does not occur in EmacsLisp, but this package provides @code{defun*} and @code{defmacro*}forms which do create the implicit block.The Common Lisp looping constructs defined by this package,such as @code{loop} and @code{dolist}, also create implicit blocksjust as in Common Lisp.Because they are implemented in terms of Emacs Lisp @code{catch}and @code{throw}, blocks have the same overhead as actual@code{catch} constructs (roughly two function calls). However,the optimizing byte compiler will optimize away the @code{catch}if the block doesnot in fact contain any @code{return} or @code{return-from} callsthat jump to it. This means that @code{do} loops and @code{defun*}functions which don't use @code{return} don't pay the overhead tosupport it.@end defspec@defspec return-from name [result]This macro returns from the block named @var{name}, which must bean (unevaluated) symbol. If a @var{result} form is specified, itis evaluated to produce the result returned from the @code{block}.Otherwise, @code{nil} is returned.@end defspec@defspec return [result]This macro is exactly like @code{(return-from nil @var{result})}.Common Lisp loops like @code{do} and @code{dolist} implicitly enclosethemselves in @code{nil} blocks.@end defspec@node Iteration, Loop Facility, Blocks and Exits, Control Structure@section Iteration@noindentThe macros described here provide more sophisticated, high-levellooping constructs to complement Emacs Lisp's basic @code{while}loop.@defspec loop forms@dots{}The @dfn{CL} package supports both the simple, old-style meaning of@code{loop} and the extremely powerful and flexible feature known asthe @dfn{Loop Facility} or @dfn{Loop Macro}. This more advancedfacility is discussed in the following section; @pxref{Loop Facility}.The simple form of @code{loop} is described here.If @code{loop} is followed by zero or more Lisp expressions,then @code{(loop @var{exprs}@dots{})} simply creates an infiniteloop executing the expressions over and over. The loop isenclosed in an implicit @code{nil} block. Thus,@example(loop (foo) (if (no-more) (return 72)) (bar))@end example@noindentis exactly equivalent to@example(block nil (while t (foo) (if (no-more) (return 72)) (bar)))@end exampleIf any of the expressions are plain symbols, the loop is insteadinterpreted as a Loop Macro specification as described later.(This is not a restriction in practice, since a plain symbolin the above notation would simply access and throw away thevalue of a variable.)@end defspec@defspec do (spec@dots{}) (end-test [result@dots{}]) forms@dots{}This macro creates a general iterative loop. Each @var{spec} isof the form@example(@var{var} [@var{init} [@var{step}]])@end exampleThe loop works as follows: First, each @var{var} is bound to theassociated @var{init} value as if by a @code{let} form. Then, ineach iteration of the loop, the @var{end-test} is evaluated; iftrue, the loop is finished. Otherwise, the body @var{forms} areevaluated, then each @var{var} is set to the associated @var{step}expression (as if by a @code{psetq} form) and the next iterationbegins. Once the @var{end-test} becomes true, the @var{result}forms are evaluated (with the @var{var}s still bound to theirvalues) to produce the result returned by @code{do}.The entire @code{do} loop is enclosed in an implicit @code{nil}block, so that you can use @code{(return)} to break out of theloop at any time.If there are no @var{result} forms, the loop returns @code{nil}.If a given @var{var} has no @var{step} form, it is bound to its@var{init} value but not otherwise modified during the @code{do}loop (unless the code explicitly modifies it); this case is justa shorthand for putting a @code{(let ((@var{var} @var{init})) @dots{})}around the loop. If @var{init} is also omitted it defaults to@code{nil}, and in this case a plain @samp{@var{var}} can be usedin place of @samp{(@var{var})}, again following the analogy with@code{let}.This example (from Steele) illustrates a loop which applies thefunction @code{f} to successive pairs of values from the lists@code{foo} and @code{bar}; it is equivalent to the call@code{(mapcar* 'f foo bar)}. Note that this loop has no body@var{forms} at all, performing all its work as side effects ofthe rest of the loop.@example(do ((x foo (cdr x)) (y bar (cdr y)) (z nil (cons (f (car x) (car y)) z))) ((or (null x) (null y)) (nreverse z)))@end example@end defspec@defspec do* (spec@dots{}) (end-test [result@dots{}]) forms@dots{}This is to @code{do} what @code{let*} is to @code{let}. Inparticular, the initial values are bound as if by @code{let*}rather than @code{let}, and the steps are assigned as if by@code{setq} rather than @code{psetq}.Here is another way to write the above loop:@example(do* ((xp foo (cdr xp)) (yp bar (cdr yp)) (x (car xp) (car xp)) (y (car yp) (car yp)) z) ((or (null xp) (null yp)) (nreverse z)) (push (f x y) z))@end example@end defspec@defspec dolist (var list [result]) forms@dots{}This is a more specialized loop which iterates across the elementsof a list. @var{list} should evaluate to a list; the body @var{forms}are executed with @var{var} bound to each element of the list inturn. Finally, the @var{result} form (or @code{nil}) is evaluatedwith @var{var} bound to @code{nil} to produce the result returned bythe loop. Unlike with Emacs's built in @code{dolist}, the loop issurrounded by an implicit @code{nil} block.@end defspec@defspec dotimes (var count [result]) forms@dots{}This is a more specialized loop which iterates a specified numberof times. The body is executed with @var{var} bound to the integersfrom zero (inclusive) to @var{count} (exclusive), in turn. Thenthe @code{result} form is evaluated with @var{var} bound to the totalnumber of iterations that were done (i.e., @code{(max 0 @var{count})})to get the return value for the loop form. Unlike with Emacs's built in@code{dolist}, the loop is surrounded by an implicit @code{nil} block.@end defspec@defspec do-symbols (var [obarray [result]]) forms@dots{}This loop iterates over all interned symbols. If @var{obarray}is specified and is not @code{nil}, it loops over all symbols inthat obarray. For each symbol, the body @var{forms} are evaluatedwith @var{var} bound to that symbol. The symbols are visited inan unspecified order. Afterward the @var{result} form, if any,is evaluated (with @var{var} bound to @code{nil}) to get the returnvalue. The loop is surrounded by an implicit @code{nil} block.@end defspec@defspec do-all-symbols (var [result]) forms@dots{}This is identical to @code{do-symbols} except that the @var{obarray}argument is omitted; it always iterates over the default obarray.@end defspec@xref{Mapping over Sequences}, for some more functions foriterating over vectors or lists.@node Loop Facility, Multiple Values, Iteration, Control Structure@section Loop Facility@noindentA common complaint with Lisp's traditional looping constructs isthat they are either too simple and limited, such as Common Lisp's@code{dotimes} or Emacs Lisp's @code{while}, or too unreadable andobscure, like Common Lisp's @code{do} loop.To remedy this, recent versions of Common Lisp have added a newconstruct called the ``Loop Facility'' or ``@code{loop} macro,''with an easy-to-use but very powerful and expressive syntax.@menu* Loop Basics:: `loop' macro, basic clause structure* Loop Examples:: Working examples of `loop' macro* For Clauses:: Clauses introduced by `for' or `as'* Iteration Clauses:: `repeat', `while', `thereis', etc.* Accumulation Clauses:: `collect', `sum', `maximize', etc.* Other Clauses:: `with', `if', `initially', `finally'@end menu@node Loop Basics, Loop Examples, Loop Facility, Loop Facility@subsection Loop Basics@noindentThe @code{loop} macro essentially creates a mini-language withinLisp that is specially tailored for describing loops. While thislanguage is a little strange-looking by the standards of regular Lisp,it turns out to be very easy to learn and well-suited to its purpose.Since @code{loop} is a macro, all parsing of the loop languagetakes place at byte-compile time; compiled @code{loop}s are justas efficient as the equivalent @code{while} loops written longhand.@defspec loop clauses@dots{}A loop construct consists of a series of @var{clause}s, eachintroduced by a symbol like @code{for} or @code{do}. Clausesare simply strung together in the argument list of @code{loop},with minimal extra parentheses. The various types of clausesspecify initializations, such as the binding of temporaryvariables, actions to be taken in the loop, stepping actions,and final cleanup.Common Lisp specifies a certain general order of clauses in aloop:@example(loop @var{name-clause} @var{var-clauses}@dots{} @var{action-clauses}@dots{})@end exampleThe @var{name-clause} optionally gives a name to the implicitblock that surrounds the loop. By default, the implicit blockis named @code{nil}. The @var{var-clauses} specify whatvariables should be bound during the loop, and how they shouldbe modified or iterated throughout the course of the loop. The@var{action-clauses} are things to be done during the loop, suchas computing, collecting, and returning values.The Emacs version of the @code{loop} macro is less restrictive aboutthe order of clauses, but things will behave most predictably ifyou put the variable-binding clauses @code{with}, @code{for}, and@code{repeat} before the action clauses. As in Common Lisp,@code{initially} and @code{finally} clauses can go anywhere.Loops generally return @code{nil} by default, but you can causethem to return a value by using an accumulation clause like@code{collect}, an end-test clause like @code{always}, or anexplicit @code{return} clause to jump out of the implicit block.(Because the loop body is enclosed in an implicit block, you canalso use regular Lisp @code{return} or @code{return-from} tobreak out of the loop.)@end defspecThe following sections give some examples of the Loop Macro inaction, and describe the particular loop clauses in great detail.Consult the second edition of Steele's @dfn{Common Lisp, the Language},for additional discussion and examples of the @code{loop} macro.@node Loop Examples, For Clauses, Loop Basics, Loop Facility@subsection Loop Examples@noindentBefore listing the full set of clauses that are allowed, let'slook at a few example loops just to get a feel for the @code{loop}language.@example(loop for buf in (buffer-list) collect (buffer-file-name buf))@end example@noindentThis loop iterates over all Emacs buffers, using the listreturned by @code{buffer-list}. For each buffer @code{buf},it calls @code{buffer-file-name} and collects the results intoa list, which is then returned from the @code{loop} construct.The result is a list of the file names of all the buffers inEmacs' memory. The words @code{for}, @code{in}, and @code{collect}are reserved words in the @code{loop} language.@example(loop repeat 20 do (insert "Yowsa\n"))@end example@noindentThis loop inserts the phrase ``Yowsa'' twenty times in thecurrent buffer.@example(loop until (eobp) do (munch-line) (forward-line 1))@end example@noindentThis loop calls @code{munch-line} on every line until the endof the buffer. If point is already at the end of the buffer,the loop exits immediately.@example(loop do (munch-line) until (eobp) do (forward-line 1))@end example@noindentThis loop is similar to the above one, except that @code{munch-line}is always called at least once.@example(loop for x from 1 to 100 for y = (* x x) until (>= y 729) finally return (list x (= y 729)))@end example@noindentThis more complicated loop searches for a number @code{x} whosesquare is 729. For safety's sake it only examines @code{x}values up to 100; dropping the phrase @samp{to 100} wouldcause the loop to count upwards with no limit. The second@code{for} clause defines @code{y} to be the square of @code{x}within the loop; the expression after the @code{=} sign isreevaluated each time through the loop. The @code{until}clause gives a condition for terminating the loop, and the@code{finally} clause says what to do when the loop finishes.(This particular example was written less concisely than itcould have been, just for the sake of illustration.)Note that even though this loop contains three clauses (two@code{for}s and an @code{until}) that would have been enough todefine loops all by themselves, it still creates a single looprather than some sort of triple-nested loop. You must explicitlynest your @code{loop} constructs if you want nested loops.@node For Clauses, Iteration Clauses, Loop Examples, Loop Facility@subsection For Clauses@noindentMost loops are governed by one or more @code{for} clauses.A @code{for} clause simultaneously describes variables to bebound, how those variables are to be stepped during the loop,and usually an end condition based on those variables.The word @code{as} is a synonym for the word @code{for}. Thisword is followed by a variable name, then a word like @code{from}or @code{across} that describes the kind of iteration desired.In Common Lisp, the phrase @code{being the} sometimes precedesthe type of iteration; in this package both @code{being} and@code{the} are optional. The word @code{each} is a synonymfor @code{the}, and the word that follows it may be singularor plural: @samp{for x being the elements of y} or@samp{for x being each element of y}. Which form you useis purely a matter of style.The variable is bound around the loop as if by @code{let}:@example(setq i 'happy)(loop for i from 1 to 10 do (do-something-with i))i @result{} happy@end example@table @code@item for @var{var} from @var{expr1} to @var{expr2} by @var{expr3}This type of @code{for} clause creates a counting loop. Each ofthe three sub-terms is optional, though there must be at least oneterm so that the clause is marked as a counting clause.The three expressions are the starting value, the ending value, andthe step value, respectively, of the variable. The loop countsupwards by default (@var{expr3} must be positive), from @var{expr1}to @var{expr2} inclusively. If you omit the @code{from} term, theloop counts from zero; if you omit the @code{to} term, the loopcounts forever without stopping (unless stopped by some otherloop clause, of course); if you omit the @code{by} term, the loopcounts in steps of one.You can replace the word @code{from} with @code{upfrom} or@code{downfrom} to indicate the direction of the loop. Likewise,you can replace @code{to} with @code{upto} or @code{downto}.For example, @samp{for x from 5 downto 1} executes five timeswith @code{x} taking on the integers from 5 down to 1 in turn.Also, you can replace @code{to} with @code{below} or @code{above},which are like @code{upto} and @code{downto} respectively exceptthat they are exclusive rather than inclusive limits:@example(loop for x to 10 collect x) @result{} (0 1 2 3 4 5 6 7 8 9 10)(loop for x below 10 collect x) @result{} (0 1 2 3 4 5 6 7 8 9)@end exampleThe @code{by} value is always positive, even for downward-countingloops. Some sort of @code{from} value is required for downwardloops; @samp{for x downto 5} is not a valid loop clause all byitself.@item for @var{var} in @var{list} by @var{function}This clause iterates @var{var} over all the elements of @var{list},in turn. If you specify the @code{by} term, then @var{function}is used to traverse the list instead of @code{cdr}; it must be afunction taking one argument. For example:@example(loop for x in '(1 2 3 4 5 6) collect (* x x)) @result{} (1 4 9 16 25 36)(loop for x in '(1 2 3 4 5 6) by 'cddr collect (* x x)) @result{} (1 9 25)@end example@item for @var{var} on @var{list} by @var{function}This clause iterates @var{var} over all the cons cells of @var{list}.@example(loop for x on '(1 2 3 4) collect x) @result{} ((1 2 3 4) (2 3 4) (3 4) (4))@end exampleWith @code{by}, there is no real reason that the @code{on} expressionmust be a list. For example:@example(loop for x on first-animal by 'next-animal collect x)@end example@noindentwhere @code{(next-animal x)} takes an ``animal'' @var{x} and returnsthe next in the (assumed) sequence of animals, or @code{nil} if@var{x} was the last animal in the sequence.@item for @var{var} in-ref @var{list} by @var{function}This is like a regular @code{in} clause, but @var{var} becomesa @code{setf}-able ``reference'' onto the elements of the listrather than just a temporary variable. For example,@example(loop for x in-ref my-list do (incf x))@end example@noindentincrements every element of @code{my-list} in place. This clauseis an extension to standard Common Lisp.@item for @var{var} across @var{array}This clause iterates @var{var} over all the elements of @var{array},which may be a vector or a string.@example(loop for x across "aeiou" do (use-vowel (char-to-string x)))@end example@item for @var{var} across-ref @var{array}This clause iterates over an array, with @var{var} a @code{setf}-ablereference onto the elements; see @code{in-ref} above.@item for @var{var} being the elements of @var{sequence}This clause iterates over the elements of @var{sequence}, which maybe a list, vector, or string. Since the type must be determinedat run-time, this is somewhat less efficient than @code{in} or@code{across}. The clause may be followed by the additional term@samp{using (index @var{var2})} to cause @var{var2} to be bound tothe successive indices (starting at 0) of the elements.This clause type is taken from older versions of the @code{loop} macro,and is not present in modern Common Lisp. The @samp{using (sequence ...)}term of the older macros is not supported.@item for @var{var} being the elements of-ref @var{sequence}This clause iterates over a sequence, with @var{var} a @code{setf}-ablereference onto the elements; see @code{in-ref} above.@item for @var{var} being the symbols [of @var{obarray}]This clause iterates over symbols, either over all interned symbolsor over all symbols in @var{obarray}. The loop is executed with@var{var} bound to each symbol in turn. The symbols are visited inan unspecified order.As an example,@example(loop for sym being the symbols when (fboundp sym) when (string-match "^map" (symbol-name sym)) collect sym)@end example@noindentreturns a list of all the functions whose names begin with @samp{map}.The Common Lisp words @code{external-symbols} and @code{present-symbols}are also recognized but are equivalent to @code{symbols} in Emacs Lisp.Due to a minor implementation restriction, it will not work to havemore than one @code{for} clause iterating over symbols, hash tables,keymaps, overlays, or intervals in a given @code{loop}. Fortunately,it would rarely if ever be useful to do so. It @emph{is} valid to mixone of these types of clauses with other clauses like @code{for ... to}or @code{while}.@item for @var{var} being the hash-keys of @var{hash-table}This clause iterates over the entries in @var{hash-table}. For eachhash table entry, @var{var} is bound to the entry's key. If you write@samp{the hash-values} instead, @var{var} is bound to the valuesof the entries. The clause may be followed by the additionalterm @samp{using (hash-values @var{var2})} (where @code{hash-values}is the opposite word of the word following @code{the}) to cause@var{var} and @var{var2} to be bound to the two parts of eachhash table entry.@item for @var{var} being the key-codes of @var{keymap}This clause iterates over the entries in @var{keymap}.The iteration does not enter nested keymaps or inherited (parent) keymaps.You can use @samp{the key-bindings} to access the commands bound tothe keys rather than the key codes, and you can add a @code{using}clause to access both the codes and the bindings together.@item for @var{var} being the key-seqs of @var{keymap}This clause iterates over all key sequences defined by @var{keymap}and its nested keymaps, where @var{var} takes on values which arevectors. The strings or vectorsare reused for each iteration, so you must copy them if you wish to keepthem permanently. You can add a @samp{using (key-bindings ...)}clause to get the command bindings as well.@item for @var{var} being the overlays [of @var{buffer}] @dots{}This clause iterates over the ``overlays'' of a buffer(the clause @code{extents} is synonymouswith @code{overlays}). If the @code{of} term is omitted, the currentbuffer is used.This clause also accepts optional @samp{from @var{pos}} and@samp{to @var{pos}} terms, limiting the clause to overlays whichoverlap the specified region.@item for @var{var} being the intervals [of @var{buffer}] @dots{}This clause iterates over all intervals of a buffer with constanttext properties. The variable @var{var} will be bound to consesof start and end positions, where one start position is always equalto the previous end position. The clause allows @code{of},@code{from}, @code{to}, and @code{property} terms, where the latterterm restricts the search to just the specified property. The@code{of} term may specify either a buffer or a string.@item for @var{var} being the framesThis clause iterates over all frames, i.e., X window system windowsopen on Emacs files. Theclause @code{screens} is a synonym for @code{frames}. The framesare visited in @code{next-frame} order starting from@code{selected-frame}.@item for @var{var} being the windows [of @var{frame}]This clause iterates over the windows (in the Emacs sense) ofthe current frame, or of the specified @var{frame}.@item for @var{var} being the buffersThis clause iterates over all buffers in Emacs. It is equivalentto @samp{for @var{var} in (buffer-list)}.@item for @var{var} = @var{expr1} then @var{expr2}This clause does a general iteration. The first time throughthe loop, @var{var} will be bound to @var{expr1}. On the secondand successive iterations it will be set by evaluating @var{expr2}(which may refer to the old value of @var{var}). For example,these two loops are effectively the same:@example(loop for x on my-list by 'cddr do ...)(loop for x = my-list then (cddr x) while x do ...)@end exampleNote that this type of @code{for} clause does not imply any sortof terminating condition; the above example combines it with a@code{while} clause to tell when to end the loop.If you omit the @code{then} term, @var{expr1} is used both forthe initial setting and for successive settings:@example(loop for x = (random) when (> x 0) return x)@end example@noindentThis loop keeps taking random numbers from the @code{(random)}function until it gets a positive one, which it then returns.@end tableIf you include several @code{for} clauses in a row, they aretreated sequentially (as if by @code{let*} and @code{setq}).You can instead use the word @code{and} to link the clauses,in which case they are processed in parallel (as if by @code{let}and @code{psetq}).@example(loop for x below 5 for y = nil then x collect (list x y)) @result{} ((0 nil) (1 1) (2 2) (3 3) (4 4))(loop for x below 5 and y = nil then x collect (list x y)) @result{} ((0 nil) (1 0) (2 1) (3 2) (4 3))@end example@noindentIn the first loop, @code{y} is set based on the value of @code{x}that was just set by the previous clause; in the second loop,@code{x} and @code{y} are set simultaneously so @code{y} is setbased on the value of @code{x} left over from the previous timethrough the loop.Another feature of the @code{loop} macro is @dfn{destructuring},similar in concept to the destructuring provided by @code{defmacro}.The @var{var} part of any @code{for} clause can be given as a listof variables instead of a single variable. The values producedduring loop execution must be lists; the values in the lists arestored in the corresponding variables.@example(loop for (x y) in '((2 3) (4 5) (6 7)) collect (+ x y)) @result{} (5 9 13)@end exampleIn loop destructuring, if there are more values than variablesthe trailing values are ignored, and if there are more variablesthan values the trailing variables get the value @code{nil}.If @code{nil} is used as a variable name, the correspondingvalues are ignored. Destructuring may be nested, and dottedlists of variables like @code{(x . y)} are allowed.@node Iteration Clauses, Accumulation Clauses, For Clauses, Loop Facility@subsection Iteration Clauses@noindentAside from @code{for} clauses, there are several other loop clausesthat control the way the loop operates. They might be used bythemselves, or in conjunction with one or more @code{for} clauses.@table @code@item repeat @var{integer}This clause simply counts up to the specified number using aninternal temporary variable. The loops@example(loop repeat n do ...)(loop for temp to n do ...)@end example@noindentare identical except that the second one forces you to choosea name for a variable you aren't actually going to use.@item while @var{condition}This clause stops the loop when the specified condition (any Lispexpression) becomes @code{nil}. For example, the following twoloops are equivalent, except for the implicit @code{nil} blockthat surrounds the second one:@example(while @var{cond} @var{forms}@dots{})(loop while @var{cond} do @var{forms}@dots{})@end example@item until @var{condition}This clause stops the loop when the specified condition is true,i.e., non-@code{nil}.@item always @var{condition}This clause stops the loop when the specified condition is @code{nil}.Unlike @code{while}, it stops the loop using @code{return nil} so thatthe @code{finally} clauses are not executed. If all the conditionswere non-@code{nil}, the loop returns @code{t}:@example(if (loop for size in size-list always (> size 10)) (some-big-sizes) (no-big-sizes))@end example@item never @var{condition}This clause is like @code{always}, except that the loop returns@code{t} if any conditions were false, or @code{nil} otherwise.@item thereis @var{condition}This clause stops the loop when the specified form is non-@code{nil};in this case, it returns that non-@code{nil} value. If all thevalues were @code{nil}, the loop returns @code{nil}.@end table@node Accumulation Clauses, Other Clauses, Iteration Clauses, Loop Facility@subsection Accumulation Clauses@noindentThese clauses cause the loop to accumulate information about thespecified Lisp @var{form}. The accumulated result is returnedfrom the loop unless overridden, say, by a @code{return} clause.@table @code@item collect @var{form}This clause collects the values of @var{form} into a list. Severalexamples of @code{collect} appear elsewhere in this manual.The word @code{collecting} is a synonym for @code{collect}, andlikewise for the other accumulation clauses.@item append @var{form}This clause collects lists of values into a result list using@code{append}.@item nconc @var{form}This clause collects lists of values into a result list bydestructively modifying the lists rather than copying them.@item concat @var{form}This clause concatenates the values of the specified @var{form}into a string. (It and the following clause are extensions tostandard Common Lisp.)@item vconcat @var{form}This clause concatenates the values of the specified @var{form}into a vector.@item count @var{form}This clause counts the number of times the specified @var{form}evaluates to a non-@code{nil} value.@item sum @var{form}This clause accumulates the sum of the values of the specified@var{form}, which must evaluate to a number.@item maximize @var{form}This clause accumulates the maximum value of the specified @var{form},which must evaluate to a number. The return value is undefined if@code{maximize} is executed zero times.@item minimize @var{form}This clause accumulates the minimum value of the specified @var{form}.@end tableAccumulation clauses can be followed by @samp{into @var{var}} tocause the data to be collected into variable @var{var} (which isautomatically @code{let}-bound during the loop) rather than anunnamed temporary variable. Also, @code{into} accumulations donot automatically imply a return value. The loop must use someexplicit mechanism, such as @code{finally return}, to returnthe accumulated result.It is valid for several accumulation clauses of the same type toaccumulate into the same place. From Steele:@example(loop for name in '(fred sue alice joe june) for kids in '((bob ken) () () (kris sunshine) ()) collect name append kids) @result{} (fred bob ken sue alice joe kris sunshine june)@end example@node Other Clauses, , Accumulation Clauses, Loop Facility@subsection Other Clauses@noindentThis section describes the remaining loop clauses.@table @code@item with @var{var} = @var{value}This clause binds a variable to a value around the loop, butotherwise leaves the variable alone during the loop. The followingloops are basically equivalent:@example(loop with x = 17 do ...)(let ((x 17)) (loop do ...))(loop for x = 17 then x do ...)@end exampleNaturally, the variable @var{var} might be used for some purposein the rest of the loop. For example:@example(loop for x in my-list with res = nil do (push x res) finally return res)@end exampleThis loop inserts the elements of @code{my-list} at the front ofa new list being accumulated in @code{res}, then returns thelist @code{res} at the end of the loop. The effect is similarto that of a @code{collect} clause, but the list gets reversedby virtue of the fact that elements are being pushed onto thefront of @code{res} rather than the end.If you omit the @code{=} term, the variable is initialized to@code{nil}. (Thus the @samp{= nil} in the above example isunnecessary.)Bindings made by @code{with} are sequential by default, as ifby @code{let*}. Just like @code{for} clauses, @code{with} clausescan be linked with @code{and} to cause the bindings to be made by@code{let} instead.@item if @var{condition} @var{clause}This clause executes the following loop clause only if the specifiedcondition is true. The following @var{clause} should be an accumulation,@code{do}, @code{return}, @code{if}, or @code{unless} clause.Several clauses may be linked by separating them with @code{and}.These clauses may be followed by @code{else} and a clause or clausesto execute if the condition was false. The whole construct mayoptionally be followed by the word @code{end} (which may be used todisambiguate an @code{else} or @code{and} in a nested @code{if}).The actual non-@code{nil} value of the condition form is availableby the name @code{it} in the ``then'' part. For example:@example(setq funny-numbers '(6 13 -1)) @result{} (6 13 -1)(loop for x below 10 if (oddp x) collect x into odds and if (memq x funny-numbers) return (cdr it) end else collect x into evens finally return (vector odds evens)) @result{} [(1 3 5 7 9) (0 2 4 6 8)](setq funny-numbers '(6 7 13 -1)) @result{} (6 7 13 -1)(loop <@r{same thing again}>) @result{} (13 -1)@end exampleNote the use of @code{and} to put two clauses into the ``then''part, one of which is itself an @code{if} clause. Note also that@code{end}, while normally optional, was necessary here to makeit clear that the @code{else} refers to the outermost @code{if}clause. In the first case, the loop returns a vector of listsof the odd and even values of @var{x}. In the second case, theodd number 7 is one of the @code{funny-numbers} so the loopreturns early; the actual returned value is based on the resultof the @code{memq} call.@item when @var{condition} @var{clause}This clause is just a synonym for @code{if}.@item unless @var{condition} @var{clause}The @code{unless} clause is just like @code{if} except that thesense of the condition is reversed.@item named @var{name}This clause gives a name other than @code{nil} to the implicitblock surrounding the loop. The @var{name} is the symbol to beused as the block name.@item initially [do] @var{forms}...This keyword introduces one or more Lisp forms which will beexecuted before the loop itself begins (but after any variablesrequested by @code{for} or @code{with} have been bound to theirinitial values). @code{initially} clauses can appear anywhere;if there are several, they are executed in the order they appearin the loop. The keyword @code{do} is optional.@item finally [do] @var{forms}...This introduces Lisp forms which will be executed after the loopfinishes (say, on request of a @code{for} or @code{while}).@code{initially} and @code{finally} clauses may appear anywherein the loop construct, but they are executed (in the specifiedorder) at the beginning or end, respectively, of the loop.@item finally return @var{form}This says that @var{form} should be executed after the loopis done to obtain a return value. (Without this, or some otherclause like @code{collect} or @code{return}, the loop will simplyreturn @code{nil}.) Variables bound by @code{for}, @code{with},or @code{into} will still contain their final values when @var{form}is executed.@item do @var{forms}...The word @code{do} may be followed by any number of Lisp expressionswhich are executed as an implicit @code{progn} in the body of theloop. Many of the examples in this section illustrate the use of@code{do}.@item return @var{form}This clause causes the loop to return immediately. The followingLisp form is evaluated to give the return value of the @code{loop}form. The @code{finally} clauses, if any, are not executed.Of course, @code{return} is generally used inside an @code{if} or@code{unless}, as its use in a top-level loop clause would meanthe loop would never get to ``loop'' more than once.The clause @samp{return @var{form}} is equivalent to@samp{do (return @var{form})} (or @code{return-from} if the loopwas named). The @code{return} clause is implemented a bit moreefficiently, though.@end tableWhile there is no high-level way to add user extensions to @code{loop}(comparable to @code{defsetf} for @code{setf}, say), this packagedoes offer two properties called @code{cl-loop-handler} and@code{cl-loop-for-handler} which are functions to be called whena given symbol is encountered as a top-level loop clause or@code{for} clause, respectively. Consult the source code infile @file{cl-macs.el} for details.This package's @code{loop} macro is compatible with that of CommonLisp, except that a few features are not implemented: @code{loop-finish}and data-type specifiers. Naturally, the @code{for} clauses whichiterate over keymaps, overlays, intervals, frames, windows, andbuffers are Emacs-specific extensions.@node Multiple Values, , Loop Facility, Control Structure@section Multiple Values@noindentCommon Lisp functions can return zero or more results. Emacs Lispfunctions, by contrast, always return exactly one result. Thispackage makes no attempt to emulate Common Lisp multiple returnvalues; Emacs versions of Common Lisp functions that return morethan one value either return just the first value (as in@code{compiler-macroexpand}) or return a list of values (as in@code{get-setf-method}). This package @emph{does} define placeholdersfor the Common Lisp functions that work with multiple values, butin Emacs Lisp these functions simply operate on lists instead.The @code{values} form, for example, is a synonym for @code{list}in Emacs.@defspec multiple-value-bind (var@dots{}) values-form forms@dots{}This form evaluates @var{values-form}, which must return a list ofvalues. It then binds the @var{var}s to these respective values,as if by @code{let}, and then executes the body @var{forms}.If there are more @var{var}s than values, the extra @var{var}sare bound to @code{nil}. If there are fewer @var{var}s thanvalues, the excess values are ignored.@end defspec@defspec multiple-value-setq (var@dots{}) formThis form evaluates @var{form}, which must return a list of values.It then sets the @var{var}s to these respective values, as if by@code{setq}. Extra @var{var}s or values are treated the same asin @code{multiple-value-bind}.@end defspecThe older Quiroz package attempted a more faithful (but stillimperfect) emulation of Common Lisp multiple values. The oldmethod ``usually'' simulated true multiple values quite well,but under certain circumstances would leave spurious returnvalues in memory where a later, unrelated @code{multiple-value-bind}form would see them.Since a perfect emulation is not feasible in Emacs Lisp, thispackage opts to keep it as simple and predictable as possible.@node Macros, Declarations, Control Structure, Top@chapter Macros@noindentThis package implements the various Common Lisp features of@code{defmacro}, such as destructuring, @code{&environment},and @code{&body}. Top-level @code{&whole} is not implementedfor @code{defmacro} due to technical difficulties.@xref{Argument Lists}.Destructuring is made available to the user by way of thefollowing macro:@defspec destructuring-bind arglist expr forms@dots{}This macro expands to code which executes @var{forms}, withthe variables in @var{arglist} bound to the list of valuesreturned by @var{expr}. The @var{arglist} can include allthe features allowed for @code{defmacro} argument lists,including destructuring. (The @code{&environment} keywordis not allowed.) The macro expansion will signal an errorif @var{expr} returns a list of the wrong number of argumentsor with incorrect keyword arguments.@end defspecThis package also includes the Common Lisp @code{define-compiler-macro}facility, which allows you to define compile-time expansions andoptimizations for your functions.@defspec define-compiler-macro name arglist forms@dots{}This form is similar to @code{defmacro}, except that it only expandscalls to @var{name} at compile-time; calls processed by the Lispinterpreter are not expanded, nor are they expanded by the@code{macroexpand} function.The argument list may begin with a @code{&whole} keyword and avariable. This variable is bound to the macro-call form itself,i.e., to a list of the form @samp{(@var{name} @var{args}@dots{})}.If the macro expander returns this form unchanged, then thecompiler treats it as a normal function call. This allowscompiler macros to work as optimizers for special cases of afunction, leaving complicated cases alone.For example, here is a simplified version of a definition thatappears as a standard part of this package:@example(define-compiler-macro member* (&whole form a list &rest keys) (if (and (null keys) (eq (car-safe a) 'quote) (not (floatp-safe (cadr a)))) (list 'memq a list) form))@end example@noindentThis definition causes @code{(member* @var{a} @var{list})} to changeto a call to the faster @code{memq} in the common case where @var{a}is a non-floating-point constant; if @var{a} is anything else, orif there are any keyword arguments in the call, then the original@code{member*} call is left intact. (The actual compiler macrofor @code{member*} optimizes a number of other cases, includingcommon @code{:test} predicates.)@end defspec@defun compiler-macroexpand formThis function is analogous to @code{macroexpand}, except that itexpands compiler macros rather than regular macros. It returns@var{form} unchanged if it is not a call to a function for whicha compiler macro has been defined, or if that compiler macrodecided to punt by returning its @code{&whole} argument. Like@code{macroexpand}, it expands repeatedly until it reaches a formfor which no further expansion is possible.@end defun@xref{Macro Bindings}, for descriptions of the @code{macrolet}and @code{symbol-macrolet} forms for making ``local'' macrodefinitions.@node Declarations, Symbols, Macros, Top@chapter Declarations@noindentCommon Lisp includes a complex and powerful ``declaration''mechanism that allows you to give the compiler special hintsabout the types of data that will be stored in particular variables,and about the ways those variables and functions will be used. Thispackage defines versions of all the Common Lisp declaration forms:@code{declare}, @code{locally}, @code{proclaim}, @code{declaim},and @code{the}.Most of the Common Lisp declarations are not currently useful inEmacs Lisp, as the byte-code system provides little opportunityto benefit from type information, and @code{special} declarationsare redundant in a fully dynamically-scoped Lisp. A fewdeclarations are meaningful when the optimizing bytecompiler is being used, however. Under the earlier non-optimizingcompiler, these declarations will effectively be ignored.@defun proclaim decl-specThis function records a ``global'' declaration specified by@var{decl-spec}. Since @code{proclaim} is a function, @var{decl-spec}is evaluated and thus should normally be quoted.@end defun@defspec declaim decl-specs@dots{}This macro is like @code{proclaim}, except that it takes any numberof @var{decl-spec} arguments, and the arguments are unevaluated andunquoted. The @code{declaim} macro also puts an @code{(eval-when(compile load eval) ...)} around the declarations so that they willbe registered at compile-time as well as at run-time. (This is vital,since normally the declarations are meant to influence the way thecompiler treats the rest of the file that contains the @code{declaim}form.)@end defspec@defspec declare decl-specs@dots{}This macro is used to make declarations within functions and othercode. Common Lisp allows declarations in various locations, generallyat the beginning of any of the many ``implicit @code{progn}s''throughout Lisp syntax, such as function bodies, @code{let} bodies,etc. Currently the only declaration understood by @code{declare}is @code{special}.@end defspec@defspec locally declarations@dots{} forms@dots{}In this package, @code{locally} is no different from @code{progn}.@end defspec@defspec the type formType information provided by @code{the} is ignored in this package;in other words, @code{(the @var{type} @var{form})} is equivalentto @var{form}. Future versions of the optimizing byte-compiler maymake use of this information.For example, @code{mapcar} can map over both lists and arrays. It ishard for the compiler to expand @code{mapcar} into an in-line loopunless it knows whether the sequence will be a list or an array aheadof time. With @code{(mapcar 'car (the vector foo))}, a futurecompiler would have enough information to expand the loop in-line.For now, Emacs Lisp will treat the above code as exactly equivalentto @code{(mapcar 'car foo)}.@end defspecEach @var{decl-spec} in a @code{proclaim}, @code{declaim}, or@code{declare} should be a list beginning with a symbol that sayswhat kind of declaration it is. This package currently understands@code{special}, @code{inline}, @code{notinline}, @code{optimize},and @code{warn} declarations. (The @code{warn} declaration is anextension of standard Common Lisp.) Other Common Lisp declarations,such as @code{type} and @code{ftype}, are silently ignored.@table @code@item specialSince all variables in Emacs Lisp are ``special'' (in the CommonLisp sense), @code{special} declarations are only advisory. Theysimply tell the optimizing byte compiler that the specifiedvariables are intentionally being referred to without beingbound in the body of the function. The compiler normally emitswarnings for such references, since they could be typographicalerrors for references to local variables.The declaration @code{(declare (special @var{var1} @var{var2}))} isequivalent to @code{(defvar @var{var1}) (defvar @var{var2})} in theoptimizing compiler, or to nothing at all in older compilers (whichdo not warn for non-local references).In top-level contexts, it is generally better to write@code{(defvar @var{var})} than @code{(declaim (special @var{var}))},since @code{defvar} makes your intentions clearer. But the olderbyte compilers can not handle @code{defvar}s appearing inside offunctions, while @code{(declare (special @var{var}))} takes careto work correctly with all compilers.@item inlineThe @code{inline} @var{decl-spec} lists one or more functionswhose bodies should be expanded ``in-line'' into calling functionswhenever the compiler is able to arrange for it. For example,the Common Lisp function @code{cadr} is declared @code{inline}by this package so that the form @code{(cadr @var{x})} willexpand directly into @code{(car (cdr @var{x}))} when it is calledin user functions, for a savings of one (relatively expensive)function call.The following declarations are all equivalent. Note that the@code{defsubst} form is a convenient way to define a functionand declare it inline all at once.@example(declaim (inline foo bar))(eval-when (compile load eval) (proclaim '(inline foo bar)))(defsubst foo (...) ...) ; instead of defun@end example@strong{Please note:} this declaration remains in effect after thecontaining source file is done. It is correct to use it torequest that a function you have defined should be inlined,but it is impolite to use it to request inlining of an externalfunction.In Common Lisp, it is possible to use @code{(declare (inline @dots{}))}before a particular call to a function to cause just that call tobe inlined; the current byte compilers provide no way to implementthis, so @code{(declare (inline @dots{}))} is currently ignored bythis package.@item notinlineThe @code{notinline} declaration lists functions which shouldnot be inlined after all; it cancels a previous @code{inline}declaration.@item optimizeThis declaration controls how much optimization is performed bythe compiler. Naturally, it is ignored by the earlier non-optimizingcompilers.The word @code{optimize} is followed by any number of lists like@code{(speed 3)} or @code{(safety 2)}. Common Lisp defines severaloptimization ``qualities''; this package ignores all but @code{speed}and @code{safety}. The value of a quality should be an integer from0 to 3, with 0 meaning ``unimportant'' and 3 meaning ``very important.''The default level for both qualities is 1.In this package, with the optimizing compiler, the@code{speed} quality is tied to the @code{byte-compile-optimize}flag, which is set to @code{nil} for @code{(speed 0)} and to@code{t} for higher settings; and the @code{safety} quality istied to the @code{byte-compile-delete-errors} flag, which isset to @code{t} for @code{(safety 3)} and to @code{nil} for alllower settings. (The latter flag controls whether the compileris allowed to optimize out code whose only side-effect couldbe to signal an error, e.g., rewriting @code{(progn foo bar)} to@code{bar} when it is not known whether @code{foo} will be boundat run-time.)Note that even compiling with @code{(safety 0)}, the Emacsbyte-code system provides sufficient checking to prevent realharm from being done. For example, barring serious bugs inEmacs itself, Emacs will not crash with a segmentation faultjust because of an error in a fully-optimized Lisp program.The @code{optimize} declaration is normally used in a top-level@code{proclaim} or @code{declaim} in a file; Common Lisp allowsit to be used with @code{declare} to set the level of optimizationlocally for a given form, but this will not work correctly with thecurrent version of the optimizing compiler. (The @code{declare}will set the new optimization level, but that level will notautomatically be unset after the enclosing form is done.)@item warnThis declaration controls what sorts of warnings are generatedby the byte compiler. Again, only the optimizing compilergenerates warnings. The word @code{warn} is followed by anynumber of ``warning qualities,'' similar in form to optimizationqualities. The currently supported warning types are@code{redefine}, @code{callargs}, @code{unresolved}, and@code{free-vars}; in the current system, a value of 0 willdisable these warnings and any higher value will enable them.See the documentation for the optimizing byte compiler for details.@end table@node Symbols, Numbers, Declarations, Top@chapter Symbols@noindentThis package defines several symbol-related features that weremissing from Emacs Lisp.@menu* Property Lists:: `get*', `remprop', `getf', `remf'* Creating Symbols:: `gensym', `gentemp'@end menu@node Property Lists, Creating Symbols, Symbols, Symbols@section Property Lists@noindentThese functions augment the standard Emacs Lisp functions @code{get}and @code{put} for operating on properties attached to symbols.There are also functions for working with property lists asfirst-class data structures not attached to particular symbols.@defun get* symbol property &optional defaultThis function is like @code{get}, except that if the property isnot found, the @var{default} argument provides the return value.(The Emacs Lisp @code{get} function always uses @code{nil} asthe default; this package's @code{get*} is equivalent to CommonLisp's @code{get}.)The @code{get*} function is @code{setf}-able; when used in thisfashion, the @var{default} argument is allowed but ignored.@end defun@defun remprop symbol propertyThis function removes the entry for @var{property} from the propertylist of @var{symbol}. It returns a true value if the property wasindeed found and removed, or @code{nil} if there was no such property.(This function was probably omitted from Emacs originally because,since @code{get} did not allow a @var{default}, it was very difficultto distinguish between a missing property and a property whose valuewas @code{nil}; thus, setting a property to @code{nil} was closeenough to @code{remprop} for most purposes.)@end defun@defun getf place property &optional defaultThis function scans the list @var{place} as if it were a propertylist, i.e., a list of alternating property names and values. Ifan even-numbered element of @var{place} is found which is @code{eq}to @var{property}, the following odd-numbered element is returned.Otherwise, @var{default} is returned (or @code{nil} if no defaultis given).In particular,@example(get sym prop) @equiv{} (getf (symbol-plist sym) prop)@end exampleIt is valid to use @code{getf} as a @code{setf} place, in which caseits @var{place} argument must itself be a valid @code{setf} place.The @var{default} argument, if any, is ignored in this context.The effect is to change (via @code{setcar}) the value cell in thelist that corresponds to @var{property}, or to cons a new property-valuepair onto the list if the property is not yet present.@example(put sym prop val) @equiv{} (setf (getf (symbol-plist sym) prop) val)@end exampleThe @code{get} and @code{get*} functions are also @code{setf}-able.The fact that @code{default} is ignored can sometimes be useful:@example(incf (get* 'foo 'usage-count 0))@end exampleHere, symbol @code{foo}'s @code{usage-count} property is incrementedif it exists, or set to 1 (an incremented 0) otherwise.When not used as a @code{setf} form, @code{getf} is just a regularfunction and its @var{place} argument can actually be any Lispexpression.@end defun@defspec remf place propertyThis macro removes the property-value pair for @var{property} fromthe property list stored at @var{place}, which is any @code{setf}-ableplace expression. It returns true if the property was found. Notethat if @var{property} happens to be first on the list, this willeffectively do a @code{(setf @var{place} (cddr @var{place}))},whereas if it occurs later, this simply uses @code{setcdr} to spliceout the property and value cells.@end defspec@iftex@secno=2@end iftex@node Creating Symbols, , Property Lists, Symbols@section Creating Symbols@noindentThese functions create unique symbols, typically for use astemporary variables.@defun gensym &optional xThis function creates a new, uninterned symbol (using @code{make-symbol})with a unique name. (The name of an uninterned symbol is relevantonly if the symbol is printed.) By default, the name is generatedfrom an increasing sequence of numbers, @samp{G1000}, @samp{G1001},@samp{G1002}, etc. If the optional argument @var{x} is a string, thatstring is used as a prefix instead of @samp{G}. Uninterned symbolsare used in macro expansions for temporary variables, to ensure thattheir names will not conflict with ``real'' variables in the user'scode.@end defun@defvar *gensym-counter*This variable holds the counter used to generate @code{gensym} names.It is incremented after each use by @code{gensym}. In Common Lispthis is initialized with 0, but this package initializes it with arandom (time-dependent) value to avoid trouble when two files thateach used @code{gensym} in their compilation are loaded together.(Uninterned symbols become interned when the compiler writes themout to a file and the Emacs loader loads them, so their names have tobe treated a bit more carefully than in Common Lisp where uninternedsymbols remain uninterned after loading.)@end defvar@defun gentemp &optional xThis function is like @code{gensym}, except that it produces a new@emph{interned} symbol. If the symbol that is generated alreadyexists, the function keeps incrementing the counter and tryingagain until a new symbol is generated.@end defunThe Quiroz @file{cl.el} package also defined a @code{defkeyword}form for creating self-quoting keyword symbols. This packageautomatically creates all keywords that are called for by@code{&key} argument specifiers, and discourages the use ofkeywords as data unrelated to keyword arguments, so the@code{defkeyword} form has been discontinued.@iftex@chapno=11@end iftex@node Numbers, Sequences, Symbols, Top@chapter Numbers@noindentThis section defines a few simple Common Lisp operations on numberswhich were left out of Emacs Lisp.@menu* Predicates on Numbers:: `plusp', `oddp', `floatp-safe', etc.* Numerical Functions:: `abs', `floor*', etc.* Random Numbers:: `random*', `make-random-state'* Implementation Parameters:: `most-positive-float'@end menu@iftex@secno=1@end iftex@node Predicates on Numbers, Numerical Functions, Numbers, Numbers@section Predicates on Numbers@noindentThese functions return @code{t} if the specified condition istrue of the numerical argument, or @code{nil} otherwise.@defun plusp numberThis predicate tests whether @var{number} is positive. It is anerror if the argument is not a number.@end defun@defun minusp numberThis predicate tests whether @var{number} is negative. It is anerror if the argument is not a number.@end defun@defun oddp integerThis predicate tests whether @var{integer} is odd. It is anerror if the argument is not an integer.@end defun@defun evenp integerThis predicate tests whether @var{integer} is even. It is anerror if the argument is not an integer.@end defun@defun floatp-safe objectThis predicate tests whether @var{object} is a floating-pointnumber. On systems that support floating-point, this is equivalentto @code{floatp}. On other systems, this always returns @code{nil}.@end defun@iftex@secno=3@end iftex@node Numerical Functions, Random Numbers, Predicates on Numbers, Numbers@section Numerical Functions@noindentThese functions perform various arithmetic operations on numbers.@defun gcd &rest integersThis function returns the Greatest Common Divisor of the arguments.For one argument, it returns the absolute value of that argument.For zero arguments, it returns zero.@end defun@defun lcm &rest integersThis function returns the Least Common Multiple of the arguments.For one argument, it returns the absolute value of that argument.For zero arguments, it returns one.@end defun@defun isqrt integerThis function computes the ``integer square root'' of its integerargument, i.e., the greatest integer less than or equal to the truesquare root of the argument.@end defun@defun floor* number &optional divisorThis function implements the Common Lisp @code{floor} function.It is called @code{floor*} to avoid name conflicts with thesimpler @code{floor} function built-in to Emacs.With one argument, @code{floor*} returns a list of two numbers:The argument rounded down (toward minus infinity) to an integer,and the ``remainder'' which would have to be added back to thefirst return value to yield the argument again. If the argumentis an integer @var{x}, the result is always the list @code{(@var{x} 0)}.If the argument is a floating-point number, the firstresult is a Lisp integer and the second is a Lisp float between0 (inclusive) and 1 (exclusive).With two arguments, @code{floor*} divides @var{number} by@var{divisor}, and returns the floor of the quotient and thecorresponding remainder as a list of two numbers. If@code{(floor* @var{x} @var{y})} returns @code{(@var{q} @var{r})},then @code{@var{q}*@var{y} + @var{r} = @var{x}}, with @var{r}between 0 (inclusive) and @var{r} (exclusive). Also, notethat @code{(floor* @var{x})} is exactly equivalent to@code{(floor* @var{x} 1)}.This function is entirely compatible with Common Lisp's @code{floor}function, except that it returns the two results in a list sinceEmacs Lisp does not support multiple-valued functions.@end defun@defun ceiling* number &optional divisorThis function implements the Common Lisp @code{ceiling} function,which is analogous to @code{floor} except that it rounds theargument or quotient of the arguments up toward plus infinity.The remainder will be between 0 and minus @var{r}.@end defun@defun truncate* number &optional divisorThis function implements the Common Lisp @code{truncate} function,which is analogous to @code{floor} except that it rounds theargument or quotient of the arguments toward zero. Thus it isequivalent to @code{floor*} if the argument or quotient ispositive, or to @code{ceiling*} otherwise. The remainder hasthe same sign as @var{number}.@end defun@defun round* number &optional divisorThis function implements the Common Lisp @code{round} function,which is analogous to @code{floor} except that it rounds theargument or quotient of the arguments to the nearest integer.In the case of a tie (the argument or quotient is exactlyhalfway between two integers), it rounds to the even integer.@end defun@defun mod* number divisorThis function returns the same value as the second return valueof @code{floor}.@end defun@defun rem* number divisorThis function returns the same value as the second return valueof @code{truncate}.@end defunThese definitions are compatible with those in the Quiroz@file{cl.el} package, except that this package appends @samp{*}to certain function names to avoid conflicts with existingEmacs functions, and that the mechanism for returningmultiple values is different.@iftex@secno=8@end iftex@node Random Numbers, Implementation Parameters, Numerical Functions, Numbers@section Random Numbers@noindentThis package also provides an implementation of the Common Lisprandom number generator. It uses its own additive-congruentialalgorithm, which is much more likely to give statistically cleanrandom numbers than the simple generators supplied by manyoperating systems.@defun random* number &optional stateThis function returns a random nonnegative number less than@var{number}, and of the same type (either integer or floating-point).The @var{state} argument should be a @code{random-state} objectwhich holds the state of the random number generator. Thefunction modifies this state object as a side effect. If@var{state} is omitted, it defaults to the variable@code{*random-state*}, which contains a pre-initialized@code{random-state} object.@end defun@defvar *random-state*This variable contains the system ``default'' @code{random-state}object, used for calls to @code{random*} that do not specify analternative state object. Since any number of programs in theEmacs process may be accessing @code{*random-state*} in interleavedfashion, the sequence generated from this variable will beirreproducible for all intents and purposes.@end defvar@defun make-random-state &optional stateThis function creates or copies a @code{random-state} object.If @var{state} is omitted or @code{nil}, it returns a new copy of@code{*random-state*}. This is a copy in the sense that futuresequences of calls to @code{(random* @var{n})} and@code{(random* @var{n} @var{s})} (where @var{s} is the newrandom-state object) will return identical sequences of randomnumbers.If @var{state} is a @code{random-state} object, this functionreturns a copy of that object. If @var{state} is @code{t}, thisfunction returns a new @code{random-state} object seeded from thedate and time. As an extension to Common Lisp, @var{state} may alsobe an integer in which case the new object is seeded from thatinteger; each different integer seed will result in a completelydifferent sequence of random numbers.It is valid to print a @code{random-state} object to a buffer orfile and later read it back with @code{read}. If a program wishesto use a sequence of pseudo-random numbers which can be reproducedlater for debugging, it can call @code{(make-random-state t)} toget a new sequence, then print this sequence to a file. When theprogram is later rerun, it can read the original run's random-statefrom the file.@end defun@defun random-state-p objectThis predicate returns @code{t} if @var{object} is a@code{random-state} object, or @code{nil} otherwise.@end defun@node Implementation Parameters, , Random Numbers, Numbers@section Implementation Parameters@noindentThis package defines several useful constants having to with numbers.The following parameters have to do with floating-point numbers.This package determines their values by exercising the computer'sfloating-point arithmetic in various ways. Because this operationmight be slow, the code for initializing them is kept in a separatefunction that must be called before the parameters can be used.@defun cl-float-limitsThis function makes sure that the Common Lisp floating-point parameterslike @code{most-positive-float} have been initialized. Until it iscalled, these parameters will be @code{nil}. If this version of Emacsdoes not support floats, the parameters will remain @code{nil}. If theparameters have already been initialized, the function returnsimmediately.The algorithm makes assumptions that will be valid for most modernmachines, but will fail if the machine's arithmetic is extremelyunusual, e.g., decimal.@end defunSince true Common Lisp supports up to four different floating-pointprecisions, it has families of constants like@code{most-positive-single-float}, @code{most-positive-double-float},@code{most-positive-long-float}, and so on. Emacs has only onefloating-point precision, so this package omits the precision wordfrom the constants' names.@defvar most-positive-floatThis constant equals the largest value a Lisp float can hold.For those systems whose arithmetic supports infinities, this isthe largest @emph{finite} value. For IEEE machines, the valueis approximately @code{1.79e+308}.@end defvar@defvar most-negative-floatThis constant equals the most-negative value a Lisp float can hold.(It is assumed to be equal to @code{(- most-positive-float)}.)@end defvar@defvar least-positive-floatThis constant equals the smallest Lisp float value greater than zero.For IEEE machines, it is about @code{4.94e-324} if denormals aresupported or @code{2.22e-308} if not.@end defvar@defvar least-positive-normalized-floatThis constant equals the smallest @emph{normalized} Lisp float greaterthan zero, i.e., the smallest value for which IEEE denormalizationwill not result in a loss of precision. For IEEE machines, thisvalue is about @code{2.22e-308}. For machines that do not supportthe concept of denormalization and gradual underflow, this constantwill always equal @code{least-positive-float}.@end defvar@defvar least-negative-floatThis constant is the negative counterpart of @code{least-positive-float}.@end defvar@defvar least-negative-normalized-floatThis constant is the negative counterpart of@code{least-positive-normalized-float}.@end defvar@defvar float-epsilonThis constant is the smallest positive Lisp float that can be addedto 1.0 to produce a distinct value. Adding a smaller number to 1.0will yield 1.0 again due to roundoff. For IEEE machines, epsilonis about @code{2.22e-16}.@end defvar@defvar float-negative-epsilonThis is the smallest positive value that can be subtracted from1.0 to produce a distinct value. For IEEE machines, it is about@code{1.11e-16}.@end defvar@iftex@chapno=13@end iftex@node Sequences, Lists, Numbers, Top@chapter Sequences@noindentCommon Lisp defines a number of functions that operate on@dfn{sequences}, which are either lists, strings, or vectors.Emacs Lisp includes a few of these, notably @code{elt} and@code{length}; this package defines most of the rest.@menu* Sequence Basics:: Arguments shared by all sequence functions* Mapping over Sequences:: `mapcar*', `mapcan', `map', `every', etc.* Sequence Functions:: `subseq', `remove*', `substitute', etc.* Searching Sequences:: `find', `position', `count', `search', etc.* Sorting Sequences:: `sort*', `stable-sort', `merge'@end menu@node Sequence Basics, Mapping over Sequences, Sequences, Sequences@section Sequence Basics@noindentMany of the sequence functions take keyword arguments; @pxref{ArgumentLists}. All keyword arguments are optional and, if specified,may appear in any order.The @code{:key} argument should be passed either @code{nil}, or afunction of one argument. This key function is used as a filterthrough which the elements of the sequence are seen; for example,@code{(find x y :key 'car)} is similar to @code{(assoc* x y)}:It searches for an element of the list whose @code{car} equals@code{x}, rather than for an element which equals @code{x} itself.If @code{:key} is omitted or @code{nil}, the filter is effectivelythe identity function.The @code{:test} and @code{:test-not} arguments should be either@code{nil}, or functions of two arguments. The test function isused to compare two sequence elements, or to compare a search valuewith sequence elements. (The two values are passed to the testfunction in the same order as the original sequence functionarguments from which they are derived, or, if they both come fromthe same sequence, in the same order as they appear in that sequence.)The @code{:test} argument specifies a function which must returntrue (non-@code{nil}) to indicate a match; instead, you may use@code{:test-not} to give a function which returns @emph{false} toindicate a match. The default test function is @code{:test 'eql}.Many functions which take @var{item} and @code{:test} or @code{:test-not}arguments also come in @code{-if} and @code{-if-not} varieties,where a @var{predicate} function is passed instead of @var{item},and sequence elements match if the predicate returns true on them(or false in the case of @code{-if-not}). For example:@example(remove* 0 seq :test '=) @equiv{} (remove-if 'zerop seq)@end example@noindentto remove all zeros from sequence @code{seq}.Some operations can work on a subsequence of the argument sequence;these function take @code{:start} and @code{:end} arguments whichdefault to zero and the length of the sequence, respectively.Only elements between @var{start} (inclusive) and @var{end}(exclusive) are affected by the operation. The @var{end} argumentmay be passed @code{nil} to signify the length of the sequence;otherwise, both @var{start} and @var{end} must be integers, with@code{0 <= @var{start} <= @var{end} <= (length @var{seq})}.If the function takes two sequence arguments, the limits aredefined by keywords @code{:start1} and @code{:end1} for the first,and @code{:start2} and @code{:end2} for the second.A few functions accept a @code{:from-end} argument, which, ifnon-@code{nil}, causes the operation to go from right-to-leftthrough the sequence instead of left-to-right, and a @code{:count}argument, which specifies an integer maximum number of elementsto be removed or otherwise processed.The sequence functions make no guarantees about the order inwhich the @code{:test}, @code{:test-not}, and @code{:key} functionsare called on various elements. Therefore, it is a bad idea to dependon side effects of these functions. For example, @code{:from-end}may cause the sequence to be scanned actually in reverse, or it maybe scanned forwards but computing a result ``as if'' it were scannedbackwards. (Some functions, like @code{mapcar*} and @code{every},@emph{do} specify exactly the order in which the function is calledso side effects are perfectly acceptable in those cases.)Strings may contain ``text properties'' as wellas character data. Except as noted, it is undefined whether ornot text properties are preserved by sequence functions. Forexample, @code{(remove* ?A @var{str})} may or may not preservethe properties of the characters copied from @var{str} into theresult.@node Mapping over Sequences, Sequence Functions, Sequence Basics, Sequences@section Mapping over Sequences@noindentThese functions ``map'' the function you specify over the elementsof lists or arrays. They are all variations on the theme of thebuilt-in function @code{mapcar}.@defun mapcar* function seq &rest more-seqsThis function calls @var{function} on successive parallel sets ofelements from its argument sequences. Given a single @var{seq}argument it is equivalent to @code{mapcar}; given @var{n} sequences,it calls the function with the first elements of each of the sequencesas the @var{n} arguments to yield the first element of the resultlist, then with the second elements, and so on. The mapping stops assoon as the shortest sequence runs out. The argument sequences maybe any mixture of lists, strings, and vectors; the return sequenceis always a list.Common Lisp's @code{mapcar} accepts multiple arguments but worksonly on lists; Emacs Lisp's @code{mapcar} accepts a single sequenceargument. This package's @code{mapcar*} works as a compatiblesuperset of both.@end defun@defun map result-type function seq &rest more-seqsThis function maps @var{function} over the argument sequences,just like @code{mapcar*}, but it returns a sequence of type@var{result-type} rather than a list. @var{result-type} mustbe one of the following symbols: @code{vector}, @code{string},@code{list} (in which case the effect is the same as for@code{mapcar*}), or @code{nil} (in which case the results arethrown away and @code{map} returns @code{nil}).@end defun@defun maplist function list &rest more-listsThis function calls @var{function} on each of its argument lists,then on the @code{cdr}s of those lists, and so on, until theshortest list runs out. The results are returned in the formof a list. Thus, @code{maplist} is like @code{mapcar*} exceptthat it passes in the list pointers themselves rather than the@code{car}s of the advancing pointers.@end defun@defun mapc function seq &rest more-seqsThis function is like @code{mapcar*}, except that the values returnedby @var{function} are ignored and thrown away rather than beingcollected into a list. The return value of @code{mapc} is @var{seq},the first sequence. This function is more general than the Emacsprimitive @code{mapc}.@end defun@defun mapl function list &rest more-listsThis function is like @code{maplist}, except that it throws awaythe values returned by @var{function}.@end defun@defun mapcan function seq &rest more-seqsThis function is like @code{mapcar*}, except that it concatenatesthe return values (which must be lists) using @code{nconc},rather than simply collecting them into a list.@end defun@defun mapcon function list &rest more-listsThis function is like @code{maplist}, except that it concatenatesthe return values using @code{nconc}.@end defun@defun some predicate seq &rest more-seqsThis function calls @var{predicate} on each element of @var{seq}in turn; if @var{predicate} returns a non-@code{nil} value,@code{some} returns that value, otherwise it returns @code{nil}.Given several sequence arguments, it steps through the sequencesin parallel until the shortest one runs out, just as in@code{mapcar*}. You can rely on the left-to-right order in whichthe elements are visited, and on the fact that mapping stopsimmediately as soon as @var{predicate} returns non-@code{nil}.@end defun@defun every predicate seq &rest more-seqsThis function calls @var{predicate} on each element of the sequence(s)in turn; it returns @code{nil} as soon as @var{predicate} returns@code{nil} for any element, or @code{t} if the predicate was truefor all elements.@end defun@defun notany predicate seq &rest more-seqsThis function calls @var{predicate} on each element of the sequence(s)in turn; it returns @code{nil} as soon as @var{predicate} returnsa non-@code{nil} value for any element, or @code{t} if the predicatewas @code{nil} for all elements.@end defun@defun notevery predicate seq &rest more-seqsThis function calls @var{predicate} on each element of the sequence(s)in turn; it returns a non-@code{nil} value as soon as @var{predicate}returns @code{nil} for any element, or @code{t} if the predicate wastrue for all elements.@end defun@defun reduce function seq @t{&key :from-end :start :end :initial-value :key}This function combines the elements of @var{seq} using an associativebinary operation. Suppose @var{function} is @code{*} and @var{seq} isthe list @code{(2 3 4 5)}. The first two elements of the list arecombined with @code{(* 2 3) = 6}; this is combined with the nextelement, @code{(* 6 4) = 24}, and that is combined with the finalelement: @code{(* 24 5) = 120}. Note that the @code{*} function happensto be self-reducing, so that @code{(* 2 3 4 5)} has the same effect asan explicit call to @code{reduce}.If @code{:from-end} is true, the reduction is right-associative insteadof left-associative:@example(reduce '- '(1 2 3 4)) @equiv{} (- (- (- 1 2) 3) 4) @result{} -8(reduce '- '(1 2 3 4) :from-end t) @equiv{} (- 1 (- 2 (- 3 4))) @result{} -2@end exampleIf @code{:key} is specified, it is a function of one argument whichis called on each of the sequence elements in turn.If @code{:initial-value} is specified, it is effectively added to thefront (or rear in the case of @code{:from-end}) of the sequence.The @code{:key} function is @emph{not} applied to the initial value.If the sequence, including the initial value, has exactly one elementthen that element is returned without ever calling @var{function}.If the sequence is empty (and there is no initial value), then@var{function} is called with no arguments to obtain the return value.@end defunAll of these mapping operations can be expressed conveniently interms of the @code{loop} macro. In compiled code, @code{loop} willbe faster since it generates the loop as in-line code with nofunction calls.@node Sequence Functions, Searching Sequences, Mapping over Sequences, Sequences@section Sequence Functions@noindentThis section describes a number of Common Lisp functions foroperating on sequences.@defun subseq sequence start &optional endThis function returns a given subsequence of the argument@var{sequence}, which may be a list, string, or vector.The indices @var{start} and @var{end} must be in range, and@var{start} must be no greater than @var{end}. If @var{end}is omitted, it defaults to the length of the sequence. Thereturn value is always a copy; it does not share structurewith @var{sequence}.As an extension to Common Lisp, @var{start} and/or @var{end}may be negative, in which case they represent a distance backfrom the end of the sequence. This is for compatibility withEmacs' @code{substring} function. Note that @code{subseq} isthe @emph{only} sequence function that allows negative@var{start} and @var{end}.You can use @code{setf} on a @code{subseq} form to replace aspecified range of elements with elements from another sequence.The replacement is done as if by @code{replace}, described below.@end defun@defun concatenate result-type &rest seqsThis function concatenates the argument sequences together toform a result sequence of type @var{result-type}, one of thesymbols @code{vector}, @code{string}, or @code{list}. Thearguments are always copied, even in cases such as@code{(concatenate 'list '(1 2 3))} where the result isidentical to an argument.@end defun@defun fill seq item @t{&key :start :end}This function fills the elements of the sequence (or the specifiedpart of the sequence) with the value @var{item}.@end defun@defun replace seq1 seq2 @t{&key :start1 :end1 :start2 :end2}This function copies part of @var{seq2} into part of @var{seq1}.The sequence @var{seq1} is not stretched or resized; the amountof data copied is simply the shorter of the source and destination(sub)sequences. The function returns @var{seq1}.If @var{seq1} and @var{seq2} are @code{eq}, then the replacementwill work correctly even if the regions indicated by the startand end arguments overlap. However, if @var{seq1} and @var{seq2}are lists which share storage but are not @code{eq}, and thestart and end arguments specify overlapping regions, the effectis undefined.@end defun@defun remove* item seq @t{&key :test :test-not :key :count :start :end :from-end}This returns a copy of @var{seq} with all elements matching@var{item} removed. The result may share storage with or be@code{eq} to @var{seq} in some circumstances, but the original@var{seq} will not be modified. The @code{:test}, @code{:test-not},and @code{:key} arguments define the matching test that is used;by default, elements @code{eql} to @var{item} are removed. The@code{:count} argument specifies the maximum number of matchingelements that can be removed (only the leftmost @var{count} matchesare removed). The @code{:start} and @code{:end} arguments specifya region in @var{seq} in which elements will be removed; elementsoutside that region are not matched or removed. The @code{:from-end}argument, if true, says that elements should be deleted from theend of the sequence rather than the beginning (this matters onlyif @var{count} was also specified).@end defun@defun delete* item seq @t{&key :test :test-not :key :count :start :end :from-end}This deletes all elements of @var{seq} which match @var{item}.It is a destructive operation. Since Emacs Lisp does not supportstretchable strings or vectors, this is the same as @code{remove*}for those sequence types. On lists, @code{remove*} will copy thelist if necessary to preserve the original list, whereas@code{delete*} will splice out parts of the argument list.Compare @code{append} and @code{nconc}, which are analogousnon-destructive and destructive list operations in Emacs Lisp.@end defun@findex remove-if@findex remove-if-not@findex delete-if@findex delete-if-notThe predicate-oriented functions @code{remove-if}, @code{remove-if-not},@code{delete-if}, and @code{delete-if-not} are defined similarly.@defun remove-duplicates seq @t{&key :test :test-not :key :start :end :from-end}This function returns a copy of @var{seq} with duplicate elementsremoved. Specifically, if two elements from the sequence matchaccording to the @code{:test}, @code{:test-not}, and @code{:key}arguments, only the rightmost one is retained. If @code{:from-end}is true, the leftmost one is retained instead. If @code{:start} or@code{:end} is specified, only elements within that subsequence areexamined or removed.@end defun@defun delete-duplicates seq @t{&key :test :test-not :key :start :end :from-end}This function deletes duplicate elements from @var{seq}. It isa destructive version of @code{remove-duplicates}.@end defun@defun substitute new old seq @t{&key :test :test-not :key :count :start :end :from-end}This function returns a copy of @var{seq}, with all elementsmatching @var{old} replaced with @var{new}. The @code{:count},@code{:start}, @code{:end}, and @code{:from-end} arguments may beused to limit the number of substitutions made.@end defun@defun nsubstitute new old seq @t{&key :test :test-not :key :count :start :end :from-end}This is a destructive version of @code{substitute}; it performsthe substitution using @code{setcar} or @code{aset} rather thanby returning a changed copy of the sequence.@end defun@findex substitute-if@findex substitute-if-not@findex nsubstitute-if@findex nsubstitute-if-notThe @code{substitute-if}, @code{substitute-if-not}, @code{nsubstitute-if},and @code{nsubstitute-if-not} functions are defined similarly. Forthese, a @var{predicate} is given in place of the @var{old} argument.@node Searching Sequences, Sorting Sequences, Sequence Functions, Sequences@section Searching Sequences@noindentThese functions search for elements or subsequences in a sequence.(See also @code{member*} and @code{assoc*}; @pxref{Lists}.)@defun find item seq @t{&key :test :test-not :key :start :end :from-end}This function searches @var{seq} for an element matching @var{item}.If it finds a match, it returns the matching element. Otherwise,it returns @code{nil}. It returns the leftmost match, unless@code{:from-end} is true, in which case it returns the rightmostmatch. The @code{:start} and @code{:end} arguments may be used tolimit the range of elements that are searched.@end defun@defun position item seq @t{&key :test :test-not :key :start :end :from-end}This function is like @code{find}, except that it returns theinteger position in the sequence of the matching item rather thanthe item itself. The position is relative to the start of thesequence as a whole, even if @code{:start} is non-zero. The functionreturns @code{nil} if no matching element was found.@end defun@defun count item seq @t{&key :test :test-not :key :start :end}This function returns the number of elements of @var{seq} whichmatch @var{item}. The result is always a nonnegative integer.@end defun@findex find-if@findex find-if-not@findex position-if@findex position-if-not@findex count-if@findex count-if-notThe @code{find-if}, @code{find-if-not}, @code{position-if},@code{position-if-not}, @code{count-if}, and @code{count-if-not}functions are defined similarly.@defun mismatch seq1 seq2 @t{&key :test :test-not :key :start1 :end1 :start2 :end2 :from-end}This function compares the specified parts of @var{seq1} and@var{seq2}. If they are the same length and the correspondingelements match (according to @code{:test}, @code{:test-not},and @code{:key}), the function returns @code{nil}. If there isa mismatch, the function returns the index (relative to @var{seq1})of the first mismatching element. This will be the leftmost pair ofelements which do not match, or the position at which the shorter ofthe two otherwise-matching sequences runs out.If @code{:from-end} is true, then the elements are compared from rightto left starting at @code{(1- @var{end1})} and @code{(1- @var{end2})}.If the sequences differ, then one plus the index of the rightmostdifference (relative to @var{seq1}) is returned.An interesting example is @code{(mismatch str1 str2 :key 'upcase)},which compares two strings case-insensitively.@end defun@defun search seq1 seq2 @t{&key :test :test-not :key :from-end :start1 :end1 :start2 :end2}This function searches @var{seq2} for a subsequence that matches@var{seq1} (or part of it specified by @code{:start1} and@code{:end1}.) Only matches which fall entirely within the regiondefined by @code{:start2} and @code{:end2} will be considered.The return value is the index of the leftmost element of theleftmost match, relative to the start of @var{seq2}, or @code{nil}if no matches were found. If @code{:from-end} is true, thefunction finds the @emph{rightmost} matching subsequence.@end defun@node Sorting Sequences, , Searching Sequences, Sequences@section Sorting Sequences@defun sort* seq predicate @t{&key :key}This function sorts @var{seq} into increasing order as determinedby using @var{predicate} to compare pairs of elements. @var{predicate}should return true (non-@code{nil}) if and only if its first argumentis less than (not equal to) its second argument. For example,@code{<} and @code{string-lessp} are suitable predicate functionsfor sorting numbers and strings, respectively; @code{>} would sortnumbers into decreasing rather than increasing order.This function differs from Emacs' built-in @code{sort} in that itcan operate on any type of sequence, not just lists. Also, itaccepts a @code{:key} argument which is used to preprocess datafed to the @var{predicate} function. For example,@example(setq data (sort data 'string-lessp :key 'downcase))@end example@noindentsorts @var{data}, a sequence of strings, into increasing alphabeticalorder without regard to case. A @code{:key} function of @code{car}would be useful for sorting association lists.The @code{sort*} function is destructive; it sorts lists by actuallyrearranging the @code{cdr} pointers in suitable fashion.@end defun@defun stable-sort seq predicate @t{&key :key}This function sorts @var{seq} @dfn{stably}, meaning two elementswhich are equal in terms of @var{predicate} are guaranteed not tobe rearranged out of their original order by the sort.In practice, @code{sort*} and @code{stable-sort} are equivalentin Emacs Lisp because the underlying @code{sort} function isstable by default. However, this package reserves the right touse non-stable methods for @code{sort*} in the future.@end defun@defun merge type seq1 seq2 predicate @t{&key :key}This function merges two sequences @var{seq1} and @var{seq2} byinterleaving their elements. The result sequence, of type @var{type}(in the sense of @code{concatenate}), has length equal to the sumof the lengths of the two input sequences. The sequences may bemodified destructively. Order of elements within @var{seq1} and@var{seq2} is preserved in the interleaving; elements of the twosequences are compared by @var{predicate} (in the sense of@code{sort}) and the lesser element goes first in the result.When elements are equal, those from @var{seq1} precede those from@var{seq2} in the result. Thus, if @var{seq1} and @var{seq2} areboth sorted according to @var{predicate}, then the result will bea merged sequence which is (stably) sorted according to@var{predicate}.@end defun@node Lists, Structures, Sequences, Top@chapter Lists@noindentThe functions described here operate on lists.@menu* List Functions:: `caddr', `first', `list*', etc.* Substitution of Expressions:: `subst', `sublis', etc.* Lists as Sets:: `member*', `adjoin', `union', etc.* Association Lists:: `assoc*', `rassoc*', `acons', `pairlis'@end menu@node List Functions, Substitution of Expressions, Lists, Lists@section List Functions@noindentThis section describes a number of simple operations on lists,i.e., chains of cons cells.@defun caddr xThis function is equivalent to @code{(car (cdr (cdr @var{x})))}.Likewise, this package defines all 28 @code{c@var{xxx}r} functionswhere @var{xxx} is up to four @samp{a}s and/or @samp{d}s.All of these functions are @code{setf}-able, and calls to themare expanded inline by the byte-compiler for maximum efficiency.@end defun@defun first xThis function is a synonym for @code{(car @var{x})}. Likewise,the functions @code{second}, @code{third}, @dots{}, through@code{tenth} return the given element of the list @var{x}.@end defun@defun rest xThis function is a synonym for @code{(cdr @var{x})}.@end defun@defun endp xCommon Lisp defines this function to act like @code{null}, butsignaling an error if @code{x} is neither a @code{nil} nor acons cell. This package simply defines @code{endp} as a synonymfor @code{null}.@end defun@defun list-length xThis function returns the length of list @var{x}, exactly like@code{(length @var{x})}, except that if @var{x} is a circularlist (where the cdr-chain forms a loop rather than terminatingwith @code{nil}), this function returns @code{nil}. (The regular@code{length} function would get stuck if given a circular list.)@end defun@defun list* arg &rest othersThis function constructs a list of its arguments. The finalargument becomes the @code{cdr} of the last cell constructed.Thus, @code{(list* @var{a} @var{b} @var{c})} is equivalent to@code{(cons @var{a} (cons @var{b} @var{c}))}, and@code{(list* @var{a} @var{b} nil)} is equivalent to@code{(list @var{a} @var{b})}.(Note that this function really is called @code{list*} in CommonLisp; it is not a name invented for this package like @code{member*}or @code{defun*}.)@end defun@defun ldiff list sublistIf @var{sublist} is a sublist of @var{list}, i.e., is @code{eq} toone of the cons cells of @var{list}, then this function returnsa copy of the part of @var{list} up to but not including@var{sublist}. For example, @code{(ldiff x (cddr x))} returnsthe first two elements of the list @code{x}. The result is acopy; the original @var{list} is not modified. If @var{sublist}is not a sublist of @var{list}, a copy of the entire @var{list}is returned.@end defun@defun copy-list listThis function returns a copy of the list @var{list}. It copiesdotted lists like @code{(1 2 . 3)} correctly.@end defun@defun copy-tree x &optional vecpThis function returns a copy of the tree of cons cells @var{x}.Unlike @code{copy-sequence} (and its alias @code{copy-list}),which copies only along the @code{cdr} direction, this functioncopies (recursively) along both the @code{car} and the @code{cdr}directions. If @var{x} is not a cons cell, the function simplyreturns @var{x} unchanged. If the optional @var{vecp} argumentis true, this function copies vectors (recursively) as well ascons cells.@end defun@defun tree-equal x y @t{&key :test :test-not :key}This function compares two trees of cons cells. If @var{x} and@var{y} are both cons cells, their @code{car}s and @code{cdr}s arecompared recursively. If neither @var{x} nor @var{y} is a conscell, they are compared by @code{eql}, or according to thespecified test. The @code{:key} function, if specified, isapplied to the elements of both trees. @xref{Sequences}.@end defun@iftex@secno=3@end iftex@node Substitution of Expressions, Lists as Sets, List Functions, Lists@section Substitution of Expressions@noindentThese functions substitute elements throughout a tree of conscells. (@xref{Sequence Functions}, for the @code{substitute}function, which works on just the top-level elements of a list.)@defun subst new old tree @t{&key :test :test-not :key}This function substitutes occurrences of @var{old} with @var{new}in @var{tree}, a tree of cons cells. It returns a substitutedtree, which will be a copy except that it may share storage withthe argument @var{tree} in parts where no substitutions occurred.The original @var{tree} is not modified. This function recurseson, and compares against @var{old}, both @code{car}s and @code{cdr}sof the component cons cells. If @var{old} is itself a cons cell,then matching cells in the tree are substituted as usual withoutrecursively substituting in that cell. Comparisons with @var{old}are done according to the specified test (@code{eql} by default).The @code{:key} function is applied to the elements of the treebut not to @var{old}.@end defun@defun nsubst new old tree @t{&key :test :test-not :key}This function is like @code{subst}, except that it works bydestructive modification (by @code{setcar} or @code{setcdr})rather than copying.@end defun@findex subst-if@findex subst-if-not@findex nsubst-if@findex nsubst-if-notThe @code{subst-if}, @code{subst-if-not}, @code{nsubst-if}, and@code{nsubst-if-not} functions are defined similarly.@defun sublis alist tree @t{&key :test :test-not :key}This function is like @code{subst}, except that it takes anassociation list @var{alist} of @var{old}-@var{new} pairs.Each element of the tree (after applying the @code{:key}function, if any), is compared with the @code{car}s of@var{alist}; if it matches, it is replaced by the corresponding@code{cdr}.@end defun@defun nsublis alist tree @t{&key :test :test-not :key}This is a destructive version of @code{sublis}.@end defun@node Lists as Sets, Association Lists, Substitution of Expressions, Lists@section Lists as Sets@noindentThese functions perform operations on lists which represent setsof elements.@defun member* item list @t{&key :test :test-not :key}This function searches @var{list} for an element matching @var{item}.If a match is found, it returns the cons cell whose @code{car} wasthe matching element. Otherwise, it returns @code{nil}. Elementsare compared by @code{eql} by default; you can use the @code{:test},@code{:test-not}, and @code{:key} arguments to modify this behavior.@xref{Sequences}.Note that this function's name is suffixed by @samp{*} to avoidthe incompatible @code{member} function defined in Emacs.(That function uses @code{equal} for comparisons; it is equivalentto @code{(member* @var{item} @var{list} :test 'equal)}.)@end defun@findex member-if@findex member-if-notThe @code{member-if} and @code{member-if-not} functionsanalogously search for elements which satisfy a given predicate.@defun tailp sublist listThis function returns @code{t} if @var{sublist} is a sublist of@var{list}, i.e., if @var{sublist} is @code{eql} to @var{list} or toany of its @code{cdr}s.@end defun@defun adjoin item list @t{&key :test :test-not :key}This function conses @var{item} onto the front of @var{list},like @code{(cons @var{item} @var{list})}, but only if @var{item}is not already present on the list (as determined by @code{member*}).If a @code{:key} argument is specified, it is applied to@var{item} as well as to the elements of @var{list} duringthe search, on the reasoning that @var{item} is ``about'' tobecome part of the list.@end defun@defun union list1 list2 @t{&key :test :test-not :key}This function combines two lists which represent sets of items,returning a list that represents the union of those two sets.The result list will contain all items which appear in @var{list1}or @var{list2}, and no others. If an item appears in both@var{list1} and @var{list2} it will be copied only once. Ifan item is duplicated in @var{list1} or @var{list2}, it isundefined whether or not that duplication will survive in theresult list. The order of elements in the result list is alsoundefined.@end defun@defun nunion list1 list2 @t{&key :test :test-not :key}This is a destructive version of @code{union}; rather than copying,it tries to reuse the storage of the argument lists if possible.@end defun@defun intersection list1 list2 @t{&key :test :test-not :key}This function computes the intersection of the sets representedby @var{list1} and @var{list2}. It returns the list of itemswhich appear in both @var{list1} and @var{list2}.@end defun@defun nintersection list1 list2 @t{&key :test :test-not :key}This is a destructive version of @code{intersection}. Ittries to reuse storage of @var{list1} rather than copying.It does @emph{not} reuse the storage of @var{list2}.@end defun@defun set-difference list1 list2 @t{&key :test :test-not :key}This function computes the ``set difference'' of @var{list1}and @var{list2}, i.e., the set of elements that appear in@var{list1} but @emph{not} in @var{list2}.@end defun@defun nset-difference list1 list2 @t{&key :test :test-not :key}This is a destructive @code{set-difference}, which will tryto reuse @var{list1} if possible.@end defun@defun set-exclusive-or list1 list2 @t{&key :test :test-not :key}This function computes the ``set exclusive or'' of @var{list1}and @var{list2}, i.e., the set of elements that appear inexactly one of @var{list1} and @var{list2}.@end defun@defun nset-exclusive-or list1 list2 @t{&key :test :test-not :key}This is a destructive @code{set-exclusive-or}, which will tryto reuse @var{list1} and @var{list2} if possible.@end defun@defun subsetp list1 list2 @t{&key :test :test-not :key}This function checks whether @var{list1} represents a subsetof @var{list2}, i.e., whether every element of @var{list1}also appears in @var{list2}.@end defun@node Association Lists, , Lists as Sets, Lists@section Association Lists@noindentAn @dfn{association list} is a list representing a mapping fromone set of values to another; any list whose elements are conscells is an association list.@defun assoc* item a-list @t{&key :test :test-not :key}This function searches the association list @var{a-list} for anelement whose @code{car} matches (in the sense of @code{:test},@code{:test-not}, and @code{:key}, or by comparison with @code{eql})a given @var{item}. It returns the matching element, if any,otherwise @code{nil}. It ignores elements of @var{a-list} whichare not cons cells. (This corresponds to the behavior of@code{assq} and @code{assoc} in Emacs Lisp; Common Lisp's@code{assoc} ignores @code{nil}s but considers any other non-conselements of @var{a-list} to be an error.)@end defun@defun rassoc* item a-list @t{&key :test :test-not :key}This function searches for an element whose @code{cdr} matches@var{item}. If @var{a-list} represents a mapping, this appliesthe inverse of the mapping to @var{item}.@end defun@findex assoc-if@findex assoc-if-not@findex rassoc-if@findex rassoc-if-notThe @code{assoc-if}, @code{assoc-if-not}, @code{rassoc-if},and @code{rassoc-if-not} functions are defined similarly.Two simple functions for constructing association lists are:@defun acons key value alistThis is equivalent to @code{(cons (cons @var{key} @var{value}) @var{alist})}.@end defun@defun pairlis keys values &optional alistThis is equivalent to @code{(nconc (mapcar* 'cons @var{keys} @var{values})@var{alist})}.@end defun@iftex@chapno=18@end iftex@node Structures, Assertions, Lists, Top@chapter Structures@noindentThe Common Lisp @dfn{structure} mechanism provides a general wayto define data types similar to C's @code{struct} types. Astructure is a Lisp object containing some number of @dfn{slots},each of which can hold any Lisp data object. Functions areprovided for accessing and setting the slots, creating or copyingstructure objects, and recognizing objects of a particular structuretype.In true Common Lisp, each structure type is a new type distinctfrom all existing Lisp types. Since the underlying Emacs Lispsystem provides no way to create new distinct types, this packageimplements structures as vectors (or lists upon request) with aspecial ``tag'' symbol to identify them.@defspec defstruct name slots@dots{}The @code{defstruct} form defines a new structure type called@var{name}, with the specified @var{slots}. (The @var{slots}may begin with a string which documents the structure type.)In the simplest case, @var{name} and each of the @var{slots}are symbols. For example,@example(defstruct person name age sex)@end example@noindentdefines a struct type called @code{person} which contains threeslots. Given a @code{person} object @var{p}, you can access thoseslots by calling @code{(person-name @var{p})}, @code{(person-age @var{p})},and @code{(person-sex @var{p})}. You can also change these slots byusing @code{setf} on any of these place forms:@example(incf (person-age birthday-boy))@end exampleYou can create a new @code{person} by calling @code{make-person},which takes keyword arguments @code{:name}, @code{:age}, and@code{:sex} to specify the initial values of these slots in thenew object. (Omitting any of these arguments leaves the correspondingslot ``undefined,'' according to the Common Lisp standard; in EmacsLisp, such uninitialized slots are filled with @code{nil}.)Given a @code{person}, @code{(copy-person @var{p})} makes a newobject of the same type whose slots are @code{eq} to those of @var{p}.Given any Lisp object @var{x}, @code{(person-p @var{x})} returnstrue if @var{x} looks like a @code{person}, false otherwise. (Again,in Common Lisp this predicate would be exact; in Emacs Lisp thebest it can do is verify that @var{x} is a vector of the correctlength which starts with the correct tag symbol.)Accessors like @code{person-name} normally check their arguments(effectively using @code{person-p}) and signal an error if theargument is the wrong type. This check is affected by@code{(optimize (safety @dots{}))} declarations. Safety level 1,the default, uses a somewhat optimized check that will detect allincorrect arguments, but may use an uninformative error message(e.g., ``expected a vector'' instead of ``expected a @code{person}'').Safety level 0 omits all checks except as provided by the underlying@code{aref} call; safety levels 2 and 3 do rigorous checking that willalways print a descriptive error message for incorrect inputs.@xref{Declarations}.@example(setq dave (make-person :name "Dave" :sex 'male)) @result{} [cl-struct-person "Dave" nil male](setq other (copy-person dave)) @result{} [cl-struct-person "Dave" nil male](eq dave other) @result{} nil(eq (person-name dave) (person-name other)) @result{} t(person-p dave) @result{} t(person-p [1 2 3 4]) @result{} nil(person-p "Bogus") @result{} nil(person-p '[cl-struct-person counterfeit person object]) @result{} t@end exampleIn general, @var{name} is either a name symbol or a list of a namesymbol followed by any number of @dfn{struct options}; each @var{slot}is either a slot symbol or a list of the form @samp{(@var{slot-name}@var{default-value} @var{slot-options}@dots{})}. The @var{default-value}is a Lisp form which is evaluated any time an instance of thestructure type is created without specifying that slot's value.Common Lisp defines several slot options, but the only oneimplemented in this package is @code{:read-only}. A non-@code{nil}value for this option means the slot should not be @code{setf}-able;the slot's value is determined when the object is created and doesnot change afterward.@example(defstruct person (name nil :read-only t) age (sex 'unknown))@end exampleAny slot options other than @code{:read-only} are ignored.For obscure historical reasons, structure options take a differentform than slot options. A structure option is either a keywordsymbol, or a list beginning with a keyword symbol possibly followedby arguments. (By contrast, slot options are key-value pairs notenclosed in lists.)@example(defstruct (person (:constructor create-person) (:type list) :named) name age sex)@end exampleThe following structure options are recognized.@table @code@iftex@itemmax=0 in@advance@leftskip-.5@tableindent@end iftex@item :conc-nameThe argument is a symbol whose print name is used as the prefix forthe names of slot accessor functions. The default is the name ofthe struct type followed by a hyphen. The option @code{(:conc-name p-)}would change this prefix to @code{p-}. Specifying @code{nil} as anargument means no prefix, so that the slot names themselves are usedto name the accessor functions.@item :constructorIn the simple case, this option takes one argument which is analternate name to use for the constructor function. The defaultis @code{make-@var{name}}, e.g., @code{make-person}. The aboveexample changes this to @code{create-person}. Specifying @code{nil}as an argument means that no standard constructor should begenerated at all.In the full form of this option, the constructor name is followedby an arbitrary argument list. @xref{Program Structure}, for adescription of the format of Common Lisp argument lists. Alloptions, such as @code{&rest} and @code{&key}, are supported.The argument names should match the slot names; each slot isinitialized from the corresponding argument. Slots whose namesdo not appear in the argument list are initialized based on the@var{default-value} in their slot descriptor. Also, @code{&optional}and @code{&key} arguments which don't specify defaults take theirdefaults from the slot descriptor. It is valid to include argumentswhich don't correspond to slot names; these are useful if they arereferred to in the defaults for optional, keyword, or @code{&aux}arguments which @emph{do} correspond to slots.You can specify any number of full-format @code{:constructor}options on a structure. The default constructor is still generatedas well unless you disable it with a simple-format @code{:constructor}option.@example(defstruct (person (:constructor nil) ; no default constructor (:constructor new-person (name sex &optional (age 0))) (:constructor new-hound (&key (name "Rover") (dog-years 0) &aux (age (* 7 dog-years)) (sex 'canine)))) name age sex)@end exampleThe first constructor here takes its arguments positionally ratherthan by keyword. (In official Common Lisp terminology, constructorsthat work By Order of Arguments instead of by keyword are called``BOA constructors.'' No, I'm not making this up.) For example,@code{(new-person "Jane" 'female)} generates a person whose slotsare @code{"Jane"}, 0, and @code{female}, respectively.The second constructor takes two keyword arguments, @code{:name},which initializes the @code{name} slot and defaults to @code{"Rover"},and @code{:dog-years}, which does not itself correspond to a slotbut which is used to initialize the @code{age} slot. The @code{sex}slot is forced to the symbol @code{canine} with no syntax foroverriding it.@item :copierThe argument is an alternate name for the copier function forthis type. The default is @code{copy-@var{name}}. @code{nil}means not to generate a copier function. (In this implementation,all copier functions are simply synonyms for @code{copy-sequence}.)@item :predicateThe argument is an alternate name for the predicate which recognizesobjects of this type. The default is @code{@var{name}-p}. @code{nil}means not to generate a predicate function. (If the @code{:type}option is used without the @code{:named} option, no predicate isever generated.)In true Common Lisp, @code{typep} is always able to recognize astructure object even if @code{:predicate} was used. In thispackage, @code{typep} simply looks for a function called@code{@var{typename}-p}, so it will work for structure typesonly if they used the default predicate name.@item :includeThis option implements a very limited form of C++-style inheritance.The argument is the name of another structure type previouslycreated with @code{defstruct}. The effect is to cause the newstructure type to inherit all of the included structure's slots(plus, of course, any new slots described by this struct's slotdescriptors). The new structure is considered a ``specialization''of the included one. In fact, the predicate and slot accessorsfor the included type will also accept objects of the new type.If there are extra arguments to the @code{:include} option afterthe included-structure name, these options are treated as replacementslot descriptors for slots in the included structure, possibly withmodified default values. Borrowing an example from Steele:@example(defstruct person name (age 0) sex) @result{} person(defstruct (astronaut (:include person (age 45))) helmet-size (favorite-beverage 'tang)) @result{} astronaut(setq joe (make-person :name "Joe")) @result{} [cl-struct-person "Joe" 0 nil](setq buzz (make-astronaut :name "Buzz")) @result{} [cl-struct-astronaut "Buzz" 45 nil nil tang](list (person-p joe) (person-p buzz)) @result{} (t t)(list (astronaut-p joe) (astronaut-p buzz)) @result{} (nil t)(person-name buzz) @result{} "Buzz"(astronaut-name joe) @result{} error: "astronaut-name accessing a non-astronaut"@end exampleThus, if @code{astronaut} is a specialization of @code{person},then every @code{astronaut} is also a @code{person} (but not theother way around). Every @code{astronaut} includes all the slotsof a @code{person}, plus extra slots that are specific toastronauts. Operations that work on people (like @code{person-name})work on astronauts just like other people.@item :print-functionIn full Common Lisp, this option allows you to specify a functionwhich is called to print an instance of the structure type. TheEmacs Lisp system offers no hooks into the Lisp printer which wouldallow for such a feature, so this package simply ignores@code{:print-function}.@item :typeThe argument should be one of the symbols @code{vector} or @code{list}.This tells which underlying Lisp data type should be used to implementthe new structure type. Vectors are used by default, but@code{(:type list)} will cause structure objects to be stored aslists instead.The vector representation for structure objects has the advantagethat all structure slots can be accessed quickly, although creatingvectors is a bit slower in Emacs Lisp. Lists are easier to create,but take a relatively long time accessing the later slots.@item :namedThis option, which takes no arguments, causes a characteristic ``tag''symbol to be stored at the front of the structure object. Using@code{:type} without also using @code{:named} will result in astructure type stored as plain vectors or lists with no identifyingfeatures.The default, if you don't specify @code{:type} explicitly, is touse named vectors. Therefore, @code{:named} is only useful inconjunction with @code{:type}.@example(defstruct (person1) name age sex)(defstruct (person2 (:type list) :named) name age sex)(defstruct (person3 (:type list)) name age sex)(setq p1 (make-person1)) @result{} [cl-struct-person1 nil nil nil](setq p2 (make-person2)) @result{} (person2 nil nil nil)(setq p3 (make-person3)) @result{} (nil nil nil)(person1-p p1) @result{} t(person2-p p2) @result{} t(person3-p p3) @result{} error: function person3-p undefined@end exampleSince unnamed structures don't have tags, @code{defstruct} is notable to make a useful predicate for recognizing them. Also,accessors like @code{person3-name} will be generated but theywill not be able to do any type checking. The @code{person3-name}function, for example, will simply be a synonym for @code{car} inthis case. By contrast, @code{person2-name} is able to verifythat its argument is indeed a @code{person2} object beforeproceeding.@item :initial-offsetThe argument must be a nonnegative integer. It specifies anumber of slots to be left ``empty'' at the front of thestructure. If the structure is named, the tag appears at thespecified position in the list or vector; otherwise, the firstslot appears at that position. Earlier positions are filledwith @code{nil} by the constructors and ignored otherwise. Ifthe type @code{:include}s another type, then @code{:initial-offset}specifies a number of slots to be skipped between the last slotof the included type and the first new slot.@end table@end defspecExcept as noted, the @code{defstruct} facility of this package isentirely compatible with that of Common Lisp.@iftex@chapno=23@end iftex@node Assertions, Efficiency Concerns, Structures, Top@chapter Assertions and Errors@noindentThis section describes two macros that test @dfn{assertions}, i.e.,conditions which must be true if the program is operating correctly.Assertions never add to the behavior of a Lisp program; they simplymake ``sanity checks'' to make sure everything is as it should be.If the optimization property @code{speed} has been set to 3, and@code{safety} is less than 3, then the byte-compiler will optimizeaway the following assertions. Because assertions might be optimizedaway, it is a bad idea for them to include side-effects.@defspec assert test-form [show-args string args@dots{}]This form verifies that @var{test-form} is true (i.e., evaluates toa non-@code{nil} value). If so, it returns @code{nil}. If the testis not satisfied, @code{assert} signals an error.A default error message will be supplied which includes @var{test-form}.You can specify a different error message by including a @var{string}argument plus optional extra arguments. Those arguments are simplypassed to @code{error} to signal the error.If the optional second argument @var{show-args} is @code{t} insteadof @code{nil}, then the error message (with or without @var{string})will also include all non-constant arguments of the top-level@var{form}. For example:@example(assert (> x 10) t "x is too small: %d")@end exampleThis usage of @var{show-args} is an extension to Common Lisp. Intrue Common Lisp, the second argument gives a list of @var{places}which can be @code{setf}'d by the user before continuing from theerror. Since Emacs Lisp does not support continuable errors, itmakes no sense to specify @var{places}.@end defspec@defspec check-type form type [string]This form verifies that @var{form} evaluates to a value of type@var{type}. If so, it returns @code{nil}. If not, @code{check-type}signals a @code{wrong-type-argument} error. The default error messagelists the erroneous value along with @var{type} and @var{form}themselves. If @var{string} is specified, it is included in theerror message in place of @var{type}. For example:@example(check-type x (integer 1 *) "a positive integer")@end example@xref{Type Predicates}, for a description of the type specifiersthat may be used for @var{type}.Note that in Common Lisp, the first argument to @code{check-type}must be a @var{place} suitable for use by @code{setf}, because@code{check-type} signals a continuable error that allows theuser to modify @var{place}.@end defspecThe following error-related macro is also defined:@defspec ignore-errors forms@dots{}This executes @var{forms} exactly like a @code{progn}, except thaterrors are ignored during the @var{forms}. More precisely, ifan error is signaled then @code{ignore-errors} immediatelyaborts execution of the @var{forms} and returns @code{nil}.If the @var{forms} complete successfully, @code{ignore-errors}returns the result of the last @var{form}.@end defspec@node Efficiency Concerns, Common Lisp Compatibility, Assertions, Top@appendix Efficiency Concerns@appendixsec Macros@noindentMany of the advanced features of this package, such as @code{defun*},@code{loop}, and @code{setf}, are implemented as Lisp macros. Inbyte-compiled code, these complex notations will be expanded intoequivalent Lisp code which is simple and efficient. For example,the forms@example(incf i n)(push x (car p))@end example@noindentare expanded at compile-time to the Lisp forms@example(setq i (+ i n))(setcar p (cons x (car p)))@end example@noindentwhich are the most efficient ways of doing these respective operationsin Lisp. Thus, there is no performance penalty for using the morereadable @code{incf} and @code{push} forms in your compiled code.@emph{Interpreted} code, on the other hand, must expand these macrosevery time they are executed. For this reason it is stronglyrecommended that code making heavy use of macros be compiled.(The features labeled ``Special Form'' instead of ``Function'' inthis manual are macros.) A loop using @code{incf} a hundred timeswill execute considerably faster if compiled, and will alsogarbage-collect less because the macro expansion will not haveto be generated, used, and thrown away a hundred times.You can find out how a macro expands by using the@code{cl-prettyexpand} function.@defun cl-prettyexpand form &optional fullThis function takes a single Lisp form as an argument and insertsa nicely formatted copy of it in the current buffer (which must bein Lisp mode so that indentation works properly). It also expandsall Lisp macros which appear in the form. The easiest way to usethis function is to go to the @code{*scratch*} buffer and type, say,@example(cl-prettyexpand '(loop for x below 10 collect x))@end example@noindentand type @kbd{C-x C-e} immediately after the closing parenthesis;the expansion@example(block nil (let* ((x 0) (G1004 nil)) (while (< x 10) (setq G1004 (cons x G1004)) (setq x (+ x 1))) (nreverse G1004)))@end example@noindentwill be inserted into the buffer. (The @code{block} macro isexpanded differently in the interpreter and compiler, so@code{cl-prettyexpand} just leaves it alone. The temporaryvariable @code{G1004} was created by @code{gensym}.)If the optional argument @var{full} is true, then @emph{all}macros are expanded, including @code{block}, @code{eval-when},and compiler macros. Expansion is done as if @var{form} werea top-level form in a file being compiled. For example,@example(cl-prettyexpand '(pushnew 'x list)) @print{} (setq list (adjoin 'x list))(cl-prettyexpand '(pushnew 'x list) t) @print{} (setq list (if (memq 'x list) list (cons 'x list)))(cl-prettyexpand '(caddr (member* 'a list)) t) @print{} (car (cdr (cdr (memq 'a list))))@end exampleNote that @code{adjoin}, @code{caddr}, and @code{member*} allhave built-in compiler macros to optimize them in common cases.@end defun@ifinfo@example@end example@end ifinfo@appendixsec Error Checking@noindentCommon Lisp compliance has in general not been sacrificed for thesake of efficiency. A few exceptions have been made for caseswhere substantial gains were possible at the expense of marginalincompatibility.The Common Lisp standard (as embodied in Steele's book) uses thephrase ``it is an error if'' to indicate a situation which is notsupposed to arise in complying programs; implementations are stronglyencouraged but not required to signal an error in these situations.This package sometimes omits such error checking in the interest ofcompactness and efficiency. For example, @code{do} variablespecifiers are supposed to be lists of one, two, or three forms;extra forms are ignored by this package rather than signaling asyntax error. The @code{endp} function is simply a synonym for@code{null} in this package. Functions taking keyword argumentswill accept an odd number of arguments, treating the trailingkeyword as if it were followed by the value @code{nil}.Argument lists (as processed by @code{defun*} and friends)@emph{are} checked rigorously except for the minor point justmentioned; in particular, keyword arguments are checked forvalidity, and @code{&allow-other-keys} and @code{:allow-other-keys}are fully implemented. Keyword validity checking is slightlytime consuming (though not too bad in byte-compiled code);you can use @code{&allow-other-keys} to omit this check. Functionsdefined in this package such as @code{find} and @code{member*}do check their keyword arguments for validity.@ifinfo@example@end example@end ifinfo@appendixsec Optimizing Compiler@noindentUse of the optimizing Emacs compiler is highly recommended; many of the CommonLisp macros emitcode which can be improved by optimization. In particular,@code{block}s (whether explicit or implicit in constructs like@code{defun*} and @code{loop}) carry a fair run-time penalty; theoptimizing compiler removes @code{block}s which are not actuallyreferenced by @code{return} or @code{return-from} inside the block.@node Common Lisp Compatibility, Old CL Compatibility, Efficiency Concerns, Top@appendix Common Lisp Compatibility@noindentFollowing is a list of all known incompatibilities between thispackage and Common Lisp as documented in Steele (2nd edition).Certain function names, such as @code{member}, @code{assoc}, and@code{floor}, were already taken by (incompatible) Emacs Lispfunctions; this package appends @samp{*} to the names of itsCommon Lisp versions of these functions.The word @code{defun*} is required instead of @code{defun} in orderto use extended Common Lisp argument lists in a function. Likewise,@code{defmacro*} and @code{function*} are versions of those formswhich understand full-featured argument lists. The @code{&whole}keyword does not work in @code{defmacro} argument lists (exceptinside recursive argument lists).The @code{eql} and @code{equal} predicates do not distinguishbetween IEEE floating-point plus and minus zero. The @code{equalp}predicate has several differences with Common Lisp; @pxref{Predicates}.The @code{setf} mechanism is entirely compatible, except thatsetf-methods return a list of five values rather than fivevalues directly. Also, the new ``@code{setf} function'' concept(typified by @code{(defun (setf foo) @dots{})}) is not implemented.The @code{do-all-symbols} form is the same as @code{do-symbols}with no @var{obarray} argument. In Common Lisp, this form woulditerate over all symbols in all packages. Since Emacs obarraysare not a first-class package mechanism, there is no way for@code{do-all-symbols} to locate any but the default obarray.The @code{loop} macro is complete except that @code{loop-finish}and type specifiers are unimplemented.The multiple-value return facility treats lists as multiplevalues, since Emacs Lisp cannot support multiple return valuesdirectly. The macros will be compatible with Common Lisp if@code{values} or @code{values-list} is always used to return toa @code{multiple-value-bind} or other multiple-value receiver;if @code{values} is used without @code{multiple-value-@dots{}}or vice-versa the effect will be different from Common Lisp.Many Common Lisp declarations are ignored, and others matchthe Common Lisp standard in concept but not in detail. Forexample, local @code{special} declarations, which are purelyadvisory in Emacs Lisp, do not rigorously obey the scoping rulesset down in Steele's book.The variable @code{*gensym-counter*} starts out with a pseudo-randomvalue rather than with zero. This is to cope with the fact thatgenerated symbols become interned when they are written to andloaded back from a file.The @code{defstruct} facility is compatible, except that structuresare of type @code{:type vector :named} by default rather than somespecial, distinct type. Also, the @code{:type} slot option is ignored.The second argument of @code{check-type} is treated differently.@node Old CL Compatibility, Porting Common Lisp, Common Lisp Compatibility, Top@appendix Old CL Compatibility@noindentFollowing is a list of all known incompatibilities between this packageand the older Quiroz @file{cl.el} package.This package's emulation of multiple return values in functions isincompatible with that of the older package. That package attemptedto come as close as possible to true Common Lisp multiple returnvalues; unfortunately, it could not be 100% reliable and so was proneto occasional surprises if used freely. This package uses a simplermethod, namely replacing multiple values with lists of values, whichis more predictable though more noticeably different from Common Lisp.The @code{defkeyword} form and @code{keywordp} function are notimplemented in this package.The @code{member}, @code{floor}, @code{ceiling}, @code{truncate},@code{round}, @code{mod}, and @code{rem} functions are suffixedby @samp{*} in this package to avoid collision with existingfunctions in Emacs. The older package simplyredefined these functions, overwriting the built-in meanings andcausing serious portability problems. (Some morerecent versions of the Quiroz package changed the names to@code{cl-member}, etc.; this package defines the latter names asaliases for @code{member*}, etc.)Certain functions in the old package which were buggy or inconsistentwith the Common Lisp standard are incompatible with the conformingversions in this package. For example, @code{eql} and @code{member}were synonyms for @code{eq} and @code{memq} in that package, @code{setf}failed to preserve correct order of evaluation of its arguments, etc.Finally, unlike the older package, this package is careful toprefix all of its internal names with @code{cl-}. Except for afew functions which are explicitly defined as additional features(such as @code{floatp-safe} and @code{letf}), this package does notexport any non-@samp{cl-} symbols which are not also part of CommonLisp.@ifinfo@example@end example@end ifinfo@appendixsec The @code{cl-compat} package@noindentThe @dfn{CL} package includes emulations of some features of theold @file{cl.el}, in the form of a compatibility package@code{cl-compat}. To use it, put @code{(require 'cl-compat)} inyour program.The old package defined a number of internal routines without@code{cl-} prefixes or other annotations. Call to these routinesmay have crept into existing Lisp code. @code{cl-compat}provides emulations of the following internal routines:@code{pair-with-newsyms}, @code{zip-lists}, @code{unzip-lists},@code{reassemble-arglists}, @code{duplicate-symbols-p},@code{safe-idiv}.Some @code{setf} forms translated into calls to internalfunctions that user code might call directly. The functions@code{setnth}, @code{setnthcdr}, and @code{setelt} fall inthis category; they are defined by @code{cl-compat}, but thebest fix is to change to use @code{setf} properly.The @code{cl-compat} file defines the keyword functions@code{keywordp}, @code{keyword-of}, and @code{defkeyword},which are not defined by the new @dfn{CL} package because theuse of keywords as data is discouraged.The @code{build-klist} mechanism for parsing keyword argumentsis emulated by @code{cl-compat}; the @code{with-keyword-args}macro is not, however, and in any case it's best to change touse the more natural keyword argument processing offered by@code{defun*}.Multiple return values are treated differently by the twoCommon Lisp packages. The old package's method was morecompatible with true Common Lisp, though it used heuristicsthat caused it to report spurious multiple return values incertain cases. The @code{cl-compat} package defines a setof multiple-value macros that are compatible with the oldCL package; again, they are heuristic in nature, but theyare guaranteed to work in any case where the old package'smacros worked. To avoid name collision with the ``official''multiple-value facilities, the ones in @code{cl-compat} havecapitalized names: @code{Values}, @code{Values-list},@code{Multiple-value-bind}, etc.The functions @code{cl-floor}, @code{cl-ceiling}, @code{cl-truncate},and @code{cl-round} are defined by @code{cl-compat} to use theold-style multiple-value mechanism, just as they did in the oldpackage. The newer @code{floor*} and friends return their tworesults in a list rather than as multiple values. Note thatolder versions of the old package used the unadorned names@code{floor}, @code{ceiling}, etc.; @code{cl-compat} cannot usethese names because they conflict with Emacs built-ins.@node Porting Common Lisp, Function Index, Old CL Compatibility, Top@appendix Porting Common Lisp@noindentThis package is meant to be used as an extension to Emacs Lisp,not as an Emacs implementation of true Common Lisp. Some of theremaining differences between Emacs Lisp and Common Lisp make itdifficult to port large Common Lisp applications to Emacs. Forone, some of the features in this package are not fully compliantwith ANSI or Steele; @pxref{Common Lisp Compatibility}. But thereare also quite a few features that this package does not provideat all. Here are some major omissions that you will want to watch outfor when bringing Common Lisp code into Emacs.@itemize @bullet@itemCase-insensitivity. Symbols in Common Lisp are case-insensitiveby default. Some programs refer to a function or variable as@code{foo} in one place and @code{Foo} or @code{FOO} in another.Emacs Lisp will treat these as three distinct symbols.Some Common Lisp code is written entirely in upper case. While Emacsis happy to let the program's own functions and variables usethis convention, calls to Lisp builtins like @code{if} and@code{defun} will have to be changed to lower case.@itemLexical scoping. In Common Lisp, function arguments and @code{let}bindings apply only to references physically within their bodies(or within macro expansions in their bodies). Emacs Lisp, bycontrast, uses @dfn{dynamic scoping} wherein a binding to avariable is visible even inside functions called from the body.Variables in Common Lisp can be made dynamically scoped bydeclaring them @code{special} or using @code{defvar}. In EmacsLisp it is as if all variables were declared @code{special}.Often you can use code that was written for lexical scopingeven in a dynamically scoped Lisp, but not always. Here isan example of a Common Lisp code fragment that would fail inEmacs Lisp:@example(defun map-odd-elements (func list) (loop for x in list for flag = t then (not flag) collect (if flag x (funcall func x))))(defun add-odd-elements (list x) (map-odd-elements (lambda (a) (+ a x))) list)@end example@noindentIn Common Lisp, the two functions' usages of @code{x} are completelyindependent. In Emacs Lisp, the binding to @code{x} made by@code{add-odd-elements} will have been hidden by the bindingin @code{map-odd-elements} by the time the @code{(+ a x)} functionis called.(This package avoids such problems in its own mapping functionsby using names like @code{cl-x} instead of @code{x} internally;as long as you don't use the @code{cl-} prefix for your ownvariables no collision can occur.)@xref{Lexical Bindings}, for a description of the @code{lexical-let}form which establishes a Common Lisp-style lexical binding, and someexamples of how it differs from Emacs' regular @code{let}.@itemReader macros. Common Lisp includes a second type of macro thatworks at the level of individual characters. For example, CommonLisp implements the quote notation by a reader macro called @code{'},whereas Emacs Lisp's parser just treats quote as a special case.Some Lisp packages use reader macros to create special syntaxesfor themselves, which the Emacs parser is incapable of reading.The lack of reader macros, incidentally, is the reason behindEmacs Lisp's unusual backquote syntax. Since backquotes areimplemented as a Lisp package and not built-in to the Emacsparser, they are forced to use a regular macro named @code{`}which is used with the standard function/macro call notation.@itemOther syntactic features. Common Lisp provides a number ofnotations beginning with @code{#} that the Emacs Lisp parserwon't understand. For example, @samp{#| ... |#} is analternate comment notation, and @samp{#+lucid (foo)} tellsthe parser to ignore the @code{(foo)} except in Lucid CommonLisp.@itemPackages. In Common Lisp, symbols are divided into @dfn{packages}.Symbols that are Lisp built-ins are typically stored in one package;symbols that are vendor extensions are put in another, and eachapplication program would have a package for its own symbols.Certain symbols are ``exported'' by a package and others areinternal; certain packages ``use'' or import the exported symbolsof other packages. To access symbols that would not normally bevisible due to this importing and exporting, Common Lisp providesa syntax like @code{package:symbol} or @code{package::symbol}.Emacs Lisp has a single namespace for all interned symbols, andthen uses a naming convention of putting a prefix like @code{cl-}in front of the name. Some Emacs packages adopt the Common Lisp-likeconvention of using @code{cl:} or @code{cl::} as the prefix.However, the Emacs parser does not understand colons and justtreats them as part of the symbol name. Thus, while @code{mapcar}and @code{lisp:mapcar} may refer to the same symbol in CommonLisp, they are totally distinct in Emacs Lisp. Common Lispprograms which refer to a symbol by the full name sometimesand the short name other times will not port cleanly to Emacs.Emacs Lisp does have a concept of ``obarrays,'' which arepackage-like collections of symbols, but this feature is notstrong enough to be used as a true package mechanism.@itemThe @code{format} function is quite different between CommonLisp and Emacs Lisp. It takes an additional ``destination''argument before the format string. A destination of @code{nil}means to format to a string as in Emacs Lisp; a destinationof @code{t} means to write to the terminal (similar to@code{message} in Emacs). Also, format control strings areutterly different; @code{~} is used instead of @code{%} tointroduce format codes, and the set of available codes ismuch richer. There are no notations like @code{\n} forstring literals; instead, @code{format} is used with the``newline'' format code, @code{~%}. More advanced formattingcodes provide such features as paragraph filling, caseconversion, and even loops and conditionals.While it would have been possible to implement most of CommonLisp @code{format} in this package (under the name @code{format*},of course), it was not deemed worthwhile. It would have requireda huge amount of code to implement even a decent subset of@code{format*}, yet the functionality it would provide overEmacs Lisp's @code{format} would rarely be useful.@itemVector constants use square brackets in Emacs Lisp, but@code{#(a b c)} notation in Common Lisp. To further complicatematters, Emacs has its own @code{#(} notation forsomething entirely different---strings with properties.@itemCharacters are distinct from integers in Common Lisp. Thenotation for character constants is also different: @code{#\A}instead of @code{?A}. Also, @code{string=} and @code{string-equal}are synonyms in Emacs Lisp whereas the latter is case-insensitivein Common Lisp.@itemData types. Some Common Lisp data types do not exist in EmacsLisp. Rational numbers and complex numbers are not present,nor are large integers (all integers are ``fixnums''). Allarrays are one-dimensional. There are no readtables or pathnames;streams are a set of existing data types rather than a new datatype of their own. Hash tables, random-states, structures, andpackages (obarrays) are built from Lisp vectors or lists ratherthan being distinct types.@itemThe Common Lisp Object System (CLOS) is not implemented,nor is the Common Lisp Condition System. However, the EIEIO packagefrom @uref{ftp://ftp.ultranet.com/pub/zappo} does implement someCLOS functionality.@itemCommon Lisp features that are completely redundant with EmacsLisp features of a different name generally have not beenimplemented. For example, Common Lisp writes @code{defconstant}where Emacs Lisp uses @code{defconst}. Similarly, @code{make-list}takes its arguments in different ways in the two Lisps but doesexactly the same thing, so this package has not bothered toimplement a Common Lisp-style @code{make-list}.@itemA few more notable Common Lisp features not included in thispackage: @code{compiler-let}, @code{tagbody}, @code{prog},@code{ldb/dpb}, @code{parse-integer}, @code{cerror}.@itemRecursion. While recursion works in Emacs Lisp just like itdoes in Common Lisp, various details of the Emacs Lisp systemand compiler make recursion much less efficient than it is inmost Lisps. Some schools of thought prefer to use recursionin Lisp over other techniques; they would sum a list ofnumbers using something like@example(defun sum-list (list) (if list (+ (car list) (sum-list (cdr list))) 0))@end example@noindentwhere a more iteratively-minded programmer might write one ofthese forms:@example(let ((total 0)) (dolist (x my-list) (incf total x)) total)(loop for x in my-list sum x)@end exampleWhile this would be mainly a stylistic choice in most Common Lisps,in Emacs Lisp you should be aware that the iterative forms aremuch faster than recursion. Also, Lisp programmers will want tonote that the current Emacs Lisp compiler does not optimize tailrecursion.@end itemize@node Function Index, Variable Index, Porting Common Lisp, Top@unnumbered Function Index@printindex fn@node Variable Index, , Function Index, Top@unnumbered Variable Index@printindex vr@setchapternewpage odd@contents@bye@ignore arch-tag: b61e7200-3bfa-4a70-a9d3-095e152696f8@end ignore